Motorcortex Core  version: 2.7.6
utl_sched.h
1 /*
2  * Developer : Alexey Zakharov (alexey.zakharov@vectioneer.com)
3  * All rights reserved. Copyright (c) 2015 VECTIONEER.
4  */
5 
6 #ifndef UTILS_UTL_SCHED_H
7 #define UTILS_UTL_SCHED_H
8 
9 #include <linux/sched.h>
10 #include <linux/types.h>
11 #include <unistd.h>
12 
13 #define gettid() syscall(__NR_gettid)
14 
15 /* XXX use the proper syscall numbers */
16 #ifdef __x86_64__
17 #define __NR_sched_setattr 314
18 #define __NR_sched_getattr 315
19 #endif
20 
21 #ifdef __i386__
22 #define __NR_sched_setattr 351
23 #define __NR_sched_getattr 352
24 #endif
25 
26 #ifdef __arm__
27 #define __NR_sched_setattr 380
28 #define __NR_sched_getattr 381
29 #endif
30 
31 namespace mcx {
32 
33 namespace utils {
34 
35 enum class SchedType { OTHER, DEADLINE, FIFO, RR };
36 
37 struct SchedAttr {
38  __u32 size;
39 
40  __u32 sched_policy;
41  __u64 sched_flags;
42 
43  /* SCHED_NORMAL, SCHED_BATCH */
44  __s32 sched_nice;
45 
46  /* SCHED_FIFO, SCHED_RR */
47  __u32 sched_priority;
48 
49  /* SCHED_DEADLINE (nsec) */
50  __u64 sched_runtime;
51  __u64 sched_deadline;
52  __u64 sched_period;
53 };
54 
55 inline int schedSetAttr(pid_t pid, const SchedAttr* attr, unsigned int flags) {
56  return syscall(__NR_sched_setattr, pid, attr, flags);
57 }
58 
59 inline int schedGetAttr(pid_t pid, SchedAttr* attr, unsigned int size, unsigned int flags) {
60  return syscall(__NR_sched_getattr, pid, attr, size, flags);
61 }
62 
63 inline bool schedSelect(pid_t pid, SchedType sched_type, unsigned int dt_usec, int priority = 0) {
64  SchedAttr sched_attr = {};
65  sched_attr.size = sizeof(sched_attr);
66  switch (sched_type) {
67  case SchedType::DEADLINE:
68  sched_attr.sched_policy = SCHED_DEADLINE;
69  sched_attr.sched_period = sched_attr.sched_deadline = dt_usec * 1000;
70  sched_attr.sched_runtime = sched_attr.sched_period * 0.9;
71  break;
72  case SchedType::FIFO:
73  sched_attr.sched_policy = SCHED_FIFO;
74  sched_attr.sched_priority = priority;
75  break;
76  case SchedType::RR:
77  sched_attr.sched_policy = SCHED_RR;
78  sched_attr.sched_priority = priority;
79  break;
80  case SchedType::OTHER:
81  default:
82  sched_attr.sched_policy = SCHED_OTHER;
83  sched_attr.sched_nice = priority;
84  break;
85  }
86 
87  return schedSetAttr(pid, &sched_attr, 0) >= 0;
88 }
89 
90 } // namespace utils
91 
92 } // namespace mcx
93 
94 #endif // UTILS_UTL_SCHED_H
mcx::utils::SchedAttr
Definition: utl_sched.h:37