-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdeadline_test.c
2098 lines (1816 loc) · 48.9 KB
/
deadline_test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016 Red Hat Inc, Steven Rostedt <[email protected]>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License (not later!)
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* deadline_test.c
*
* This program is used to test the deadline scheduler (SCHED_DEADLINE tasks).
* It is broken up into various degrees of complexity that can be set with
* options.
*
* Here are the test cases:
*
* 1) Simplest - create one deadline task that can migrate across all CPUS.
* Look for "simple_test"
*
*/
#define _GNU_SOURCE
#include <pthread.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sched.h>
#include <ctype.h>
#include <errno.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <linux/unistd.h>
#include <linux/magic.h>
/**
* usage - show the usage of the program and exit.
* @argv: The program passed in args
*
* This is defined here to show people looking at this code how
* to use this program as well.
*/
static void usage(char **argv)
{
char *arg = argv[0];
char *p = arg+strlen(arg);
while (p >= arg && *p != '/')
p--;
p++;
printf("usage: %s [options]\n"
" -h - Show this help menu\n"
" -b - Bind on the last cpu. (shortcut for -c <lastcpu>)\n"
" -r prio - Add an RT task with given prio to stress system\n"
" -c cpulist - Comma/hyphen separated list of CPUs to run deadline tasks on\n"
" -i interval - The shortest deadline for the tasks\n"
" -p percent - The percent of bandwidth to use (1-90%%)\n"
" -P percent - The percent of runtime for execution completion\n"
" (Default 100%%)\n"
" -t threads - The number of threads to run as deadline (default 1)\n"
" -s step(us) - The amount to increase the deadline for each task (default 500us)\n"
"\n", p);
exit(-1);
}
/*
* sched_setattr() and sched_getattr() are new system calls. We need to
* hardcode it here.
*/
#if defined(__i386__)
#ifndef __NR_sched_setattr
#define __NR_sched_setattr 351
#endif
#ifndef __NR_sched_getattr
#define __NR_sched_getattr 352
#endif
#elif defined(__x86_64__)
#ifndef __NR_sched_setattr
#define __NR_sched_setattr 314
#endif
#ifndef __NR_sched_getattr
#define __NR_sched_getattr 315
#endif
#endif /* i386 or x86_64 */
#if !defined(__NR_sched_setattr)
# error "Your arch does not support sched_setattr()"
#endif
#if !defined(__NR_sched_getattr)
# error "Your arch does not support sched_getattr()"
#endif
/* If not included in the headers, define sched deadline policy numbe */
#ifndef SCHED_DEADLINE
#define SCHED_DEADLINE 6
#endif
#define _STR(x) #x
#define STR(x) _STR(x)
/* Max path for cpuset path names. 1K should be enough */
#ifndef MAXPATH
#define MAXPATH 1024
#endif
/*
* "my_cpuset" is the cpuset that will hold the SCHED_DEADLINE tasks that
* want to limit their affinity.
*
* "my_cpuset_all" is the cpuset that will have the affinity of all the
* other CPUs outside the ones for SCHED_DEADLINE threads. It will hold
* all other tasks.
*/
#define CPUSET_ALL "my_cpuset_all"
#define CPUSET_LOCAL "my_cpuset"
/* Define the system call interfaces */
#define gettid() syscall(__NR_gettid)
#define sched_setattr(pid, attr, flags) syscall(__NR_sched_setattr, pid, attr, flags)
#define sched_getattr(pid, attr, size, flags) syscall(__NR_sched_getattr, pid, attr, size, flags)
typedef unsigned long long u64;
typedef unsigned int u32;
typedef int s32;
/**
* struct sched_attr - get/set attr system call descriptor.
*
* This is the descriptor defined for setting SCHED_DEADLINE tasks.
* It will someday be in a header file.
*
* The fields specific for deadline:
*
* @sched_policy: 6 is for deadline
* @sched_runtime: The runtime in nanoseconds
* @sched_deadline: The deadline in nanoseconds.
* @sched_period: The period, if different than deadline (not used here)
*/
struct sched_attr {
u32 size;
u32 sched_policy;
u64 sched_flags;
/* SCHED_NORMAL, SCHED_BATCH */
s32 sched_nice;
/* SCHED_FIFO, SCHED_RR */
u32 sched_priority;
/* SCHED_DEADLINE */
u64 sched_runtime;
u64 sched_deadline;
u64 sched_period;
};
/**
* struct sched_data - the descriptor for the threads.
*
* This is the descriptor that will be passed as the thread data.
* It is used as both input to the thread, as well as output to
* the main program.
*
* @runtime_us: The runtime for sched_deadline tasks in microseconds
* @deadline_us: The deadline for sched_deadline tasks in microseconds
* @loops_per_period: The amount of loops to run for the runtime
* @max_time: Recorded max time to complete loops
* @min_time: Recorded min time to complete loops
* @total_time: The total time of all periods to perform the loops
* @nr_periods: The number of periods executed
* @prime: Calculating a prime number.
* @missed_periods: The number of periods that were missed (started late)
* @missed_deadlines: The number of deadlines that were missed (ended late)
* @total_adjust: The time in microseconds adjusted for starting early
* @nr_adjust: The number of times adjusted for starting early
* @last_time: Last runtime of loops (used to calculate runtime to give)
* @prio: The priority for SCHED_FIFO threads (uses same descriptor)
* @tid: Stores the thread ID of the thread.
* @vol: The number of voluntary schedules the thread made
* @nonvol: The number of non-voluntary schedules the thread made (preempted)
* @migrate: The number of migrations the thread made.
* @buff: A string buffer to store data to write to ftrace
*
*/
struct sched_data {
u64 runtime_us;
u64 deadline_us;
u64 loops_per_period;
u64 max_time;
u64 min_time;
u64 total_time;
u64 nr_periods;
u64 prime;
int missed_periods;
int missed_deadlines;
u64 total_adjust;
u64 nr_adjust;
u64 last_time;
int prio;
int tid;
int vol;
int nonvol;
int migrate;
char buff[BUFSIZ+1];
/* Try to keep each sched_data out of cache lines */
char padding[256];
};
/* Barrier to synchronize the threads for initialization */
static pthread_barrier_t barrier;
/* cpu_count is the number of detected cpus on the running machine */
static int cpu_count;
/*
* cpusetp and cpuset_size is for cpumasks, in case we run on a machine with
* more than 64 CPUs.
*/
static cpu_set_t *cpusetp;
static int cpuset_size;
/* Number of threads to create to run deadline scheduler with (default two) */
static int nr_threads = 2;
/**
* find_mount - Find if a file system type is already mounted
* @mount: The type of files system to find
* @debugfs: Where to place the path to the found file system.
*
* Returns 1 if found and sets @debugfs.
* Returns 0 otherwise.
*/
static int find_mount(const char *mount, char *debugfs)
{
char type[100];
FILE *fp;
if ((fp = fopen("/proc/mounts","r")) == NULL)
return 0;
while (fscanf(fp, "%*s %"
STR(MAXPATH)
"s %99s %*s %*d %*d\n",
debugfs, type) == 2) {
if (strcmp(type, mount) == 0)
break;
}
fclose(fp);
if (strcmp(type, mount) != 0)
return 0;
return 1;
}
/**
* find_debugfs - Search for where debugfs is found
*
* Finds where debugfs is mounted and returns the path.
* The returned string is static and should not be modified.
*/
static const char *find_debugfs(void)
{
static int debugfs_found;
static char debugfs[MAXPATH+1];
if (debugfs_found)
return debugfs;
if (!find_mount("debugfs", debugfs))
return "";
debugfs_found = 1;
return debugfs;
}
/**
* my_vsprintf - simplified vsprintf()
* @buf: The buffer to write the string to
* @size: The allocated size of @buf
* @fmmt: The format to parse
* @ap: The variable arguments
*
* Because there's no real way to prevent glibc's vsprintf from
* allocating more memory, or doing any type of system call,
* This is a simple version of the function that is under
* our control, to make sure we stay in userspace when creating
* a ftrace_write string, and only do a system call for the
* actual ftrace_write.
*/
static int my_vsprintf(char *buf, int size, const char *fmt, va_list ap)
{
const char *p;
char tmp[100];
char *s = buf;
char *end = buf + size;
char *str;
long long lng;
int l;
int i;
end[-1] = 0;
for (p = fmt; *p && s < end; p++) {
if (*p == '%') {
l = 0;
again:
p++;
switch (*p) {
case 's':
if (l) {
fprintf(stderr, "Illegal print format l used with %%s\n");
exit(-1);
}
str = va_arg(ap, char *);
l = strlen(str);
strncpy(s, str, end - s);
s += l;
break;
case 'l':
l++;
goto again;
case 'd':
if (l == 1) {
if (sizeof(long) == 8)
l = 2;
}
if (l == 2)
lng = va_arg(ap, long long);
else if (l > 2) {
fprintf(stderr, "Illegal print format l=%d\n", l);
exit(-1);
} else
lng = va_arg(ap, int);
i = 0;
while (lng > 0) {
tmp[i++] = (lng % 10) + '0';
lng /= 10;
}
tmp[i] = 0;
l = strlen(tmp);
if (!l) {
*s++ = '0';
} else {
while (l)
*s++ = tmp[--l];
}
break;
default:
fprintf(stderr, "Illegal print format '%c'\n", *p);
exit(-1);
}
continue;
}
*s++ = *p;
}
return s - buf;
}
/* The ftrace tracing_marker file descriptor to write to ftrace */
static int mark_fd;
/**
* ftrace_write - write a string to ftrace tracing_marker
* @buf: A BUFSIZ + 1 allocated scratch pad
* @fmt: The format of the sting to write
* @va_arg: The arguments for @fmt
*
* If mark_fd is not less than zero, format the input
* and write it out to trace_marker (where mark_fd is a file
* descriptor of).
*/
static void ftrace_write(char *buf, const char *fmt, ...)
{
va_list ap;
int n;
if (mark_fd < 0)
return;
va_start(ap, fmt);
n = my_vsprintf(buf, BUFSIZ, fmt, ap);
va_end(ap);
write(mark_fd, buf, n);
}
/**
* setup_ftrace_marker - Check if trace_marker exists and open if it does
*
* Tests if debugfs is mounted, and if it is, it tests to see if the
* trace_marker exists. If it does, it opens trace_marker and sets
* mark_fd to the file descriptor. Then ftrace_write() will be able
* to write to the ftrace marker, otherwise ftrace_write() becomes
* a nop.
*
* Failure to open the trace_marker file will not stop this application
* from executing. Only ftrace writes will not be performed.
*/
static void setup_ftrace_marker(void)
{
struct stat st;
const char *debugfs = find_debugfs();
char files[strlen(debugfs) + 14];
int ret;
if (strlen(debugfs) == 0)
return;
sprintf(files, "%s/tracing/trace_marker", debugfs);
ret = stat(files, &st);
if (ret >= 0)
goto found;
/* Do nothing if not mounted */
return;
found:
mark_fd = open(files, O_WRONLY);
}
/**
* setup_hr_tick - Enable the HRTICK in sched_features (if available)
*
* SCHED_DEADLINE tasks are based on HZ, which could be as slow as
* 100 times a second (10ms). Which is incredibly slow for scheduling.
* For SCHED_DEADLINE to have finer resolution, HRTICK feature must be
* set. That's located in the debugfs/sched_features directory.
*
* This will not mount debugfs. If debugfs is not mounted, this simply
* will fail.
*/
static int setup_hr_tick(void)
{
const char *debugfs = find_debugfs();
char files[strlen(debugfs) + strlen("/sched_features") + 1];
char buf[500];
struct stat st;
static int set = 0;
char *p;
int ret;
int len;
int fd;
if (set)
return 1;
set = 1;
if (strlen(debugfs) == 0)
return 0;
sprintf(files, "%s/sched_features", debugfs);
ret = stat(files, &st);
if (ret < 0)
return 0;
fd = open(files, O_RDWR);
if (fd < 0) {
perror(files);
return 0;
}
len = sizeof(buf);
ret = read(fd, buf, len);
if (ret < 0) {
perror(files);
close(fd);
return 0;
}
if (ret >= len)
ret = len - 1;
buf[ret] = 0;
ret = 1;
p = strstr(buf, "HRTICK");
if (p + 3 >= buf) {
p -= 3;
if (strncmp(p, "NO_HRTICK", 9) == 0) {
ret = write(fd, "HRTICK", 6);
if (ret != 6)
ret = 0;
else
ret = 1;
}
}
close(fd);
return ret;
}
/**
* mounted - test if a path is mounted via the given mount type
* @path: The path to check is mounted
* @magic: The magic number of the mount type.
*
* Returns -1 if the path does not exist.
* Returns 0 if it is mounted but not of the given @magic type.
* Returns 1 if mounted and the @magic type matches.
*/
static int mounted(const char *path, long magic)
{
struct statfs st_fs;
if (statfs(path, &st_fs) < 0)
return -1;
if ((long)st_fs.f_type != magic)
return 0;
return 1;
}
#define CGROUP_PATH "/sys/fs/cgroup"
#define CPUSET_PATH CGROUP_PATH "/cpuset"
/**
* open_cpuset - open a file (usually a cpuset file)
* @path: The path of the directory the file is in
* @name: The name of the file in the path to open.
*
* Open a file, used to open cpuset files. This function simply is
* made to open many files in the same directory.
*
* Returns the file descriptor of the opened file or less than zero
* on error.
*/
static int open_cpuset(const char *path, const char *name)
{
char buf[MAXPATH];
struct stat st;
int ret;
int fd;
buf[MAXPATH - 1] = 0;
snprintf(buf, MAXPATH - 1, "%s/%s", path, name);
ret = stat(buf, &st);
if (ret < 0)
return ret;
fd = open(buf, O_WRONLY);
return fd;
}
/**
* mount_cpuset - Inialize the cpuset system
*
* Looks to see if cgroups are mounted, if it is not, then it mounts
* the cgroup_root to /sys/fs/cgroup. Then the directory cpuset exists
* and is mounted in that directory. If it is not, it is created and
* mounted.
*
* The toplevel cpuset "cpu_exclusive" flag is set, this allows child
* cpusets to set the flag too.
*
* The toplevel cpuset "load_balance" flag is cleared, letting the
* child cpusets take over load balancing.
*/
static int mount_cpuset(void)
{
struct stat st;
int ret;
int fd;
/* Check if cgroups is already mounted. */
ret = mounted(CGROUP_PATH, TMPFS_MAGIC);
if (ret < 0)
return ret;
if (!ret) {
ret = mount("cgroup_root", CGROUP_PATH, "tmpfs", 0, NULL);
if (ret < 0)
return ret;
}
ret = stat(CPUSET_PATH, &st);
if (ret < 0) {
ret = mkdir(CPUSET_PATH, 0755);
if (ret < 0)
return ret;
}
ret = mounted(CPUSET_PATH, CGROUP_SUPER_MAGIC);
if (ret < 0)
return ret;
if (!ret) {
ret = mount("cpuset", CPUSET_PATH, "cgroup", 0, "cpuset");
if (ret < 0)
return ret;
}
fd = open_cpuset(CPUSET_PATH, "cpuset.cpu_exclusive");
if (fd < 0)
return fd;
ret = write(fd, "1", 2);
close(fd);
fd = open_cpuset(CPUSET_PATH, "cpuset.sched_load_balance");
if (fd < 0)
return fd;
ret = write(fd, "0", 2);
close(fd);
return 0;
}
/*
* CPUSET flags: used for creating cpusets
*
* CPU_EXCLUSIVE - Set the cpu exclusive flag
* MEM_EXCLUSIVE - Set the mem exclusive flag
* ALL_TASKS - Move all tasks from the toplevel cpuset to this one
* TASKS - Supply a list of thread IDs to move to this cpuset
* CLEAR_LOADBALANCE - clear the loadbalance flag
* SET_LOADBALANCE - set the loadbalance flag
* CLONE_CHILDREN - set the clone_children flag
*/
enum {
CPUSET_FL_CPU_EXCLUSIVE = (1 << 0),
CPUSET_FL_MEM_EXCLUSIVE = (1 << 1),
CPUSET_FL_ALL_TASKS = (1 << 2),
CPUSET_FL_TASKS = (1 << 3),
CPUSET_FL_CLEAR_LOADBALANCE = (1 << 4),
CPUSET_FL_SET_LOADBALANCE = (1 << 5),
CPUSET_FL_CLONE_CHILDREN = (1 << 6),
};
/**
* make_cpuset - create a cpuset
* @name: The name of the cpuset
* @cpus: A string list of cpus this set is for e.g. "1,3,4-7"
* @mems: The memory nodes to use (usually just "0") (set to NULL to ignore)
* @flags: See the CPUSET_FL_* flags above for information
* @va_args: An array of tasks to move if TASKS flag is set.
*
* Creates a cpuset.
*
* If TASKS is set, then @va_args will be an array of PIDs to move from
* the main cpuset, to this cpuset. The last element of the array must
* be a zero, to stop the processing of arrays.
*
* Returns NULL on success, and a string to describe what went wrong on error.
*/
static const char *make_cpuset(const char *name, const char *cpus,
const char *mems, unsigned flags, ...)
{
struct stat st;
char path[MAXPATH];
char buf[100];
va_list ap;
int ret;
int fd;
printf("Creating cpuset '%s'\n", name);
snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
path[MAXPATH - 1] = 0;
ret = mount_cpuset();
if (ret < 0)
return "mount_cpuset";
/* Only create the new cpuset directory if it does not yet exist */
ret = stat(path, &st);
if (ret < 0) {
ret = mkdir(path, 0755);
if (ret < 0)
return "mkdir";
}
/* Assign the CPUs */
fd = open_cpuset(path, "cpuset.cpus");
if (fd < 0)
return "cset";
ret = write(fd, cpus, strlen(cpus));
close(fd);
if (ret < 0)
return "write cpus";
/* Assign the "mems" if it exists */
if (mems) {
fd = open_cpuset(path, "cpuset.mems");
if (fd < 0)
return "open mems";
ret = write(fd, mems, strlen(mems));
close(fd);
if (ret < 0)
return "write mems";
}
if (flags & CPUSET_FL_CPU_EXCLUSIVE) {
fd = open_cpuset(path, "cpuset.cpu_exclusive");
if (fd < 0)
return "open cpu_exclusive";
ret = write(fd, "1", 2);
close(fd);
if (ret < 0)
return "write cpu_exclusive";
}
if (flags & (CPUSET_FL_CLEAR_LOADBALANCE | CPUSET_FL_SET_LOADBALANCE)) {
fd = open_cpuset(path, "cpuset.sched_load_balance");
if (fd < 0)
return "open sched_load_balance";
if (flags & CPUSET_FL_SET_LOADBALANCE)
ret = write(fd, "1", 2);
else
ret = write(fd, "0", 2);
close(fd);
if (ret < 0)
return "write sched_load_balance";
}
if (flags & CPUSET_FL_CLONE_CHILDREN) {
fd = open_cpuset(path, "cgroup.clone_children");
if (fd < 0)
return "open clone_children";
ret = write(fd, "1", 2);
close(fd);
if (ret < 0)
return "write clone_children";
}
/* If TASKS flag is set, then an array of tasks is passed it */
if (flags & CPUSET_FL_TASKS) {
int *pids;
int i;
va_start(ap, flags);
fd = open_cpuset(path, "tasks");
if (fd < 0)
return "open tasks";
ret = 0;
pids = va_arg(ap, int *);
/* The array ends with pids[i] == 0 */
for (i = 0; pids[i]; i++) {
sprintf(buf, "%d ", pids[i]);
ret = write(fd, buf, strlen(buf));
if (ret < 0)
break;
}
va_end(ap);
close(fd);
if (ret < 0) {
fprintf(stderr, "Failed on task %d\n", pids[i]);
return "write tasks";
}
}
/* If ALL_TASKS flag is set, move all tasks from the top level cpuset */
if (flags & CPUSET_FL_ALL_TASKS) {
FILE *fp;
int pid;
fd = open_cpuset(path, "tasks");
snprintf(path, MAXPATH - 1, "%s/tasks", CPUSET_PATH);
if ((fp = fopen(path,"r")) == NULL) {
close (fd);
return "opening cpuset tasks";
}
while (fscanf(fp, "%d", &pid) == 1) {
sprintf(buf, "%d", pid);
ret = write(fd, buf, strlen(buf));
/*
* Tasks can come and go, and some tasks are kernel
* threads that cannot be moved. The only error we care
* about is ENOSPC, as that means something went
* wrong that we did not expect.
*/
if (ret < 0 && errno == ENOSPC) {
fclose(fp);
close(fd);
return "Can not move tasks";
}
}
fclose(fp);
close(fd);
}
return NULL;
}
/**
* destroy_cpuset - tear down a cpuset that was created
* @name: The name of the cpuset to destroy
* @print: If the tasks being moved should be displayed
*
* Reads the tasks in the cpuset and moves them to the top level cpuset
* then destroys the @name cpuset.
*/
static void destroy_cpuset(const char *name, int print)
{
struct stat st;
char path[MAXPATH];
char buf[100];
FILE *fp;
int pid;
int ret;
int fd;
int retry = 0;
printf("Removing %s\n", name);
/* Set path to the cpuset name that we will destroy */
snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
path[MAXPATH - 1] = 0;
/* Make sure it exists! */
ret = stat(path, &st);
if (ret < 0)
return;
again:
/*
* Append "/tasks" to the cpuset name, to read the tasks that are
* in this cpuset, that must be moved before destroying the cpuset.
*/
strncat(path, "/tasks", MAXPATH - 1);
if ((fp = fopen(path,"r")) == NULL) {
fprintf(stderr, "Failed opening %s\n", path);
perror("fopen");
return;
}
/* Set path to the toplevel cpuset tasks file */
snprintf(path, MAXPATH - 1, "%s/tasks", CPUSET_PATH);
path[MAXPATH - 1] = 0;
fd = open(path, O_WRONLY);
if (fd < 0) {
fclose(fp);
fprintf(stderr, "Failed opening %s\n", path);
perror("open");
return;
}
/*
* Now fp points to the destroying cpuset tasks file, and
* fd is the toplevel cpuset file descriptor. Scan in the
* tasks that are in the cpuset that is being destroyed and
* write their pids into the toplevel cpuset.
*/
while (fscanf(fp, "%d", &pid) == 1) {
sprintf(buf, "%d", pid);
if (print)
printf("Moving %d out of %s\n", pid, name);
write(fd, buf, strlen(buf));
}
fclose(fp);
close(fd);
/* Reset the path name back to the cpuset to destroy */
snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
path[MAXPATH - 1] = 0;
/* Sleep a bit to let all tasks migrate out of this cpuset. */
sleep(1);
ret = rmdir(path);
if (ret < 0) {
/*
* Sometimes there appears to be a delay, and tasks don't
* always move when you expect them to. Try 5 times, and
* give up after that.
*/
if (retry++ < 5)
goto again;
fprintf(stderr, "Failed to remove %s\n", path);
perror("rmdir");
if (retry++ < 5) {
fprintf(stderr, "Trying again\n");
goto again;
}
}
}
/**
* teardown - Called atexit() to reset the system back to normal
*
* If cpusets were created, this destroys them and puts all tasks
* back to the main cgroup.
*/
static void teardown(void)
{
int fd;
fd = open_cpuset(CPUSET_PATH, "cpuset.cpu_exclusive");
if (fd >= 0) {
write(fd, "0", 2);
close(fd);
}
fd = open_cpuset(CPUSET_PATH, "cpuset.sched_load_balance");
if (fd >= 0) {
write(fd, "1", 2);
close(fd);
}
destroy_cpuset(CPUSET_ALL, 0);
destroy_cpuset(CPUSET_LOCAL, 1);
}
/**
* bind_cpu - Set the affinity of a thread to a specific CPU.
* @cpu: The CPU to bind to.
*
* Sets the current thread to have an affinity of a sigle CPU.
* Does not work on SCHED_DEADLINE tasks.
*/
static void bind_cpu(int cpu)
{
int ret;
CPU_ZERO_S(cpuset_size, cpusetp);
CPU_SET_S(cpu, cpuset_size, cpusetp);
ret = sched_setaffinity(0, cpuset_size, cpusetp);
if (ret < 0)
perror("sched_setaffinity bind");
}
/**
* unbind_cpu - Set the affinity of a task to all CPUs
*
* Sets the current thread to have an affinity for all CPUs.
* Does not work on SCHED_DEADLINE tasks.
*/
static void unbind_cpu(void)
{
int cpu;
int ret;
for (cpu = 0; cpu < cpu_count; cpu++)
CPU_SET_S(cpu, cpuset_size, cpusetp);
ret = sched_setaffinity(0, cpuset_size, cpusetp);
if (ret < 0)
perror("sched_setaffinity unbind");
}
/*
* Used by set_prio, but can be used for any task not just current.
*/
static int set_thread_prio(pid_t pid, int prio)
{
struct sched_param sp = { .sched_priority = prio };
int policy = SCHED_FIFO;
if (!prio)
policy = SCHED_OTHER;
/* set up our priority */
return sched_setscheduler(pid, policy, &sp);
}
/**
* set_prio - Set the SCHED_FIFO priority of a thread
* @prio: The priority to set a thread to
*
* Converts a SCHED_OTHER task into a SCHED_FIFO task and sets
* its priority to @prio. If @prio is zero, then it converts
* a SCHED_FIFO task back to a SCHED_OTHER task.
*
* Returns 0 on success, otherwise it failed.
*/