sched-deadline.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. Deadline Task Scheduling
  2. ------------------------
  3. CONTENTS
  4. ========
  5. 0. WARNING
  6. 1. Overview
  7. 2. Scheduling algorithm
  8. 3. Scheduling Real-Time Tasks
  9. 4. Bandwidth management
  10. 4.1 System-wide settings
  11. 4.2 Task interface
  12. 4.3 Default behavior
  13. 5. Tasks CPU affinity
  14. 5.1 SCHED_DEADLINE and cpusets HOWTO
  15. 6. Future plans
  16. A. Test suite
  17. B. Minimal main()
  18. 0. WARNING
  19. ==========
  20. Fiddling with these settings can result in an unpredictable or even unstable
  21. system behavior. As for -rt (group) scheduling, it is assumed that root users
  22. know what they're doing.
  23. 1. Overview
  24. ===========
  25. The SCHED_DEADLINE policy contained inside the sched_dl scheduling class is
  26. basically an implementation of the Earliest Deadline First (EDF) scheduling
  27. algorithm, augmented with a mechanism (called Constant Bandwidth Server, CBS)
  28. that makes it possible to isolate the behavior of tasks between each other.
  29. 2. Scheduling algorithm
  30. ==================
  31. SCHED_DEADLINE uses three parameters, named "runtime", "period", and
  32. "deadline", to schedule tasks. A SCHED_DEADLINE task should receive
  33. "runtime" microseconds of execution time every "period" microseconds, and
  34. these "runtime" microseconds are available within "deadline" microseconds
  35. from the beginning of the period. In order to implement this behaviour,
  36. every time the task wakes up, the scheduler computes a "scheduling deadline"
  37. consistent with the guarantee (using the CBS[2,3] algorithm). Tasks are then
  38. scheduled using EDF[1] on these scheduling deadlines (the task with the
  39. earliest scheduling deadline is selected for execution). Notice that the
  40. task actually receives "runtime" time units within "deadline" if a proper
  41. "admission control" strategy (see Section "4. Bandwidth management") is used
  42. (clearly, if the system is overloaded this guarantee cannot be respected).
  43. Summing up, the CBS[2,3] algorithms assigns scheduling deadlines to tasks so
  44. that each task runs for at most its runtime every period, avoiding any
  45. interference between different tasks (bandwidth isolation), while the EDF[1]
  46. algorithm selects the task with the earliest scheduling deadline as the one
  47. to be executed next. Thanks to this feature, tasks that do not strictly comply
  48. with the "traditional" real-time task model (see Section 3) can effectively
  49. use the new policy.
  50. In more details, the CBS algorithm assigns scheduling deadlines to
  51. tasks in the following way:
  52. - Each SCHED_DEADLINE task is characterised by the "runtime",
  53. "deadline", and "period" parameters;
  54. - The state of the task is described by a "scheduling deadline", and
  55. a "remaining runtime". These two parameters are initially set to 0;
  56. - When a SCHED_DEADLINE task wakes up (becomes ready for execution),
  57. the scheduler checks if
  58. remaining runtime runtime
  59. ---------------------------------- > ---------
  60. scheduling deadline - current time period
  61. then, if the scheduling deadline is smaller than the current time, or
  62. this condition is verified, the scheduling deadline and the
  63. remaining runtime are re-initialised as
  64. scheduling deadline = current time + deadline
  65. remaining runtime = runtime
  66. otherwise, the scheduling deadline and the remaining runtime are
  67. left unchanged;
  68. - When a SCHED_DEADLINE task executes for an amount of time t, its
  69. remaining runtime is decreased as
  70. remaining runtime = remaining runtime - t
  71. (technically, the runtime is decreased at every tick, or when the
  72. task is descheduled / preempted);
  73. - When the remaining runtime becomes less or equal than 0, the task is
  74. said to be "throttled" (also known as "depleted" in real-time literature)
  75. and cannot be scheduled until its scheduling deadline. The "replenishment
  76. time" for this task (see next item) is set to be equal to the current
  77. value of the scheduling deadline;
  78. - When the current time is equal to the replenishment time of a
  79. throttled task, the scheduling deadline and the remaining runtime are
  80. updated as
  81. scheduling deadline = scheduling deadline + period
  82. remaining runtime = remaining runtime + runtime
  83. 3. Scheduling Real-Time Tasks
  84. =============================
  85. * BIG FAT WARNING ******************************************************
  86. *
  87. * This section contains a (not-thorough) summary on classical deadline
  88. * scheduling theory, and how it applies to SCHED_DEADLINE.
  89. * The reader can "safely" skip to Section 4 if only interested in seeing
  90. * how the scheduling policy can be used. Anyway, we strongly recommend
  91. * to come back here and continue reading (once the urge for testing is
  92. * satisfied :P) to be sure of fully understanding all technical details.
  93. ************************************************************************
  94. There are no limitations on what kind of task can exploit this new
  95. scheduling discipline, even if it must be said that it is particularly
  96. suited for periodic or sporadic real-time tasks that need guarantees on their
  97. timing behavior, e.g., multimedia, streaming, control applications, etc.
  98. A typical real-time task is composed of a repetition of computation phases
  99. (task instances, or jobs) which are activated on a periodic or sporadic
  100. fashion.
  101. Each job J_j (where J_j is the j^th job of the task) is characterised by an
  102. arrival time r_j (the time when the job starts), an amount of computation
  103. time c_j needed to finish the job, and a job absolute deadline d_j, which
  104. is the time within which the job should be finished. The maximum execution
  105. time max_j{c_j} is called "Worst Case Execution Time" (WCET) for the task.
  106. A real-time task can be periodic with period P if r_{j+1} = r_j + P, or
  107. sporadic with minimum inter-arrival time P is r_{j+1} >= r_j + P. Finally,
  108. d_j = r_j + D, where D is the task's relative deadline.
  109. The utilisation of a real-time task is defined as the ratio between its
  110. WCET and its period (or minimum inter-arrival time), and represents
  111. the fraction of CPU time needed to execute the task.
  112. If the total utilisation sum_i(WCET_i/P_i) is larger than M (with M equal
  113. to the number of CPUs), then the scheduler is unable to respect all the
  114. deadlines.
  115. Note that total utilisation is defined as the sum of the utilisations
  116. WCET_i/P_i over all the real-time tasks in the system. When considering
  117. multiple real-time tasks, the parameters of the i-th task are indicated
  118. with the "_i" suffix.
  119. Moreover, if the total utilisation is larger than M, then we risk starving
  120. non- real-time tasks by real-time tasks.
  121. If, instead, the total utilisation is smaller than M, then non real-time
  122. tasks will not be starved and the system might be able to respect all the
  123. deadlines.
  124. As a matter of fact, in this case it is possible to provide an upper bound
  125. for tardiness (defined as the maximum between 0 and the difference
  126. between the finishing time of a job and its absolute deadline).
  127. More precisely, it can be proven that using a global EDF scheduler the
  128. maximum tardiness of each task is smaller or equal than
  129. ((M − 1) · WCET_max − WCET_min)/(M − (M − 2) · U_max) + WCET_max
  130. where WCET_max = max_i{WCET_i} is the maximum WCET, WCET_min=min_i{WCET_i}
  131. is the minimum WCET, and U_max = max_i{WCET_i/P_i} is the maximum utilisation.
  132. If M=1 (uniprocessor system), or in case of partitioned scheduling (each
  133. real-time task is statically assigned to one and only one CPU), it is
  134. possible to formally check if all the deadlines are respected.
  135. If D_i = P_i for all tasks, then EDF is able to respect all the deadlines
  136. of all the tasks executing on a CPU if and only if the total utilisation
  137. of the tasks running on such a CPU is smaller or equal than 1.
  138. If D_i != P_i for some task, then it is possible to define the density of
  139. a task as C_i/min{D_i,T_i}, and EDF is able to respect all the deadlines
  140. of all the tasks running on a CPU if the sum sum_i C_i/min{D_i,T_i} of the
  141. densities of the tasks running on such a CPU is smaller or equal than 1
  142. (notice that this condition is only sufficient, and not necessary).
  143. On multiprocessor systems with global EDF scheduling (non partitioned
  144. systems), a sufficient test for schedulability can not be based on the
  145. utilisations (it can be shown that task sets with utilisations slightly
  146. larger than 1 can miss deadlines regardless of the number of CPUs M).
  147. However, as previously stated, enforcing that the total utilisation is smaller
  148. than M is enough to guarantee that non real-time tasks are not starved and
  149. that the tardiness of real-time tasks has an upper bound.
  150. SCHED_DEADLINE can be used to schedule real-time tasks guaranteeing that
  151. the jobs' deadlines of a task are respected. In order to do this, a task
  152. must be scheduled by setting:
  153. - runtime >= WCET
  154. - deadline = D
  155. - period <= P
  156. IOW, if runtime >= WCET and if period is >= P, then the scheduling deadlines
  157. and the absolute deadlines (d_j) coincide, so a proper admission control
  158. allows to respect the jobs' absolute deadlines for this task (this is what is
  159. called "hard schedulability property" and is an extension of Lemma 1 of [2]).
  160. Notice that if runtime > deadline the admission control will surely reject
  161. this task, as it is not possible to respect its temporal constraints.
  162. References:
  163. 1 - C. L. Liu and J. W. Layland. Scheduling algorithms for multiprogram-
  164. ming in a hard-real-time environment. Journal of the Association for
  165. Computing Machinery, 20(1), 1973.
  166. 2 - L. Abeni , G. Buttazzo. Integrating Multimedia Applications in Hard
  167. Real-Time Systems. Proceedings of the 19th IEEE Real-time Systems
  168. Symposium, 1998. http://retis.sssup.it/~giorgio/paps/1998/rtss98-cbs.pdf
  169. 3 - L. Abeni. Server Mechanisms for Multimedia Applications. ReTiS Lab
  170. Technical Report. http://disi.unitn.it/~abeni/tr-98-01.pdf
  171. 4. Bandwidth management
  172. =======================
  173. As previously mentioned, in order for -deadline scheduling to be
  174. effective and useful (that is, to be able to provide "runtime" time units
  175. within "deadline"), it is important to have some method to keep the allocation
  176. of the available fractions of CPU time to the various tasks under control.
  177. This is usually called "admission control" and if it is not performed, then
  178. no guarantee can be given on the actual scheduling of the -deadline tasks.
  179. As already stated in Section 3, a necessary condition to be respected to
  180. correctly schedule a set of real-time tasks is that the total utilisation
  181. is smaller than M. When talking about -deadline tasks, this requires that
  182. the sum of the ratio between runtime and period for all tasks is smaller
  183. than M. Notice that the ratio runtime/period is equivalent to the utilisation
  184. of a "traditional" real-time task, and is also often referred to as
  185. "bandwidth".
  186. The interface used to control the CPU bandwidth that can be allocated
  187. to -deadline tasks is similar to the one already used for -rt
  188. tasks with real-time group scheduling (a.k.a. RT-throttling - see
  189. Documentation/scheduler/sched-rt-group.txt), and is based on readable/
  190. writable control files located in procfs (for system wide settings).
  191. Notice that per-group settings (controlled through cgroupfs) are still not
  192. defined for -deadline tasks, because more discussion is needed in order to
  193. figure out how we want to manage SCHED_DEADLINE bandwidth at the task group
  194. level.
  195. A main difference between deadline bandwidth management and RT-throttling
  196. is that -deadline tasks have bandwidth on their own (while -rt ones don't!),
  197. and thus we don't need a higher level throttling mechanism to enforce the
  198. desired bandwidth. In other words, this means that interface parameters are
  199. only used at admission control time (i.e., when the user calls
  200. sched_setattr()). Scheduling is then performed considering actual tasks'
  201. parameters, so that CPU bandwidth is allocated to SCHED_DEADLINE tasks
  202. respecting their needs in terms of granularity. Therefore, using this simple
  203. interface we can put a cap on total utilization of -deadline tasks (i.e.,
  204. \Sum (runtime_i / period_i) < global_dl_utilization_cap).
  205. 4.1 System wide settings
  206. ------------------------
  207. The system wide settings are configured under the /proc virtual file system.
  208. For now the -rt knobs are used for -deadline admission control and the
  209. -deadline runtime is accounted against the -rt runtime. We realise that this
  210. isn't entirely desirable; however, it is better to have a small interface for
  211. now, and be able to change it easily later. The ideal situation (see 5.) is to
  212. run -rt tasks from a -deadline server; in which case the -rt bandwidth is a
  213. direct subset of dl_bw.
  214. This means that, for a root_domain comprising M CPUs, -deadline tasks
  215. can be created while the sum of their bandwidths stays below:
  216. M * (sched_rt_runtime_us / sched_rt_period_us)
  217. It is also possible to disable this bandwidth management logic, and
  218. be thus free of oversubscribing the system up to any arbitrary level.
  219. This is done by writing -1 in /proc/sys/kernel/sched_rt_runtime_us.
  220. 4.2 Task interface
  221. ------------------
  222. Specifying a periodic/sporadic task that executes for a given amount of
  223. runtime at each instance, and that is scheduled according to the urgency of
  224. its own timing constraints needs, in general, a way of declaring:
  225. - a (maximum/typical) instance execution time,
  226. - a minimum interval between consecutive instances,
  227. - a time constraint by which each instance must be completed.
  228. Therefore:
  229. * a new struct sched_attr, containing all the necessary fields is
  230. provided;
  231. * the new scheduling related syscalls that manipulate it, i.e.,
  232. sched_setattr() and sched_getattr() are implemented.
  233. 4.3 Default behavior
  234. ---------------------
  235. The default value for SCHED_DEADLINE bandwidth is to have rt_runtime equal to
  236. 950000. With rt_period equal to 1000000, by default, it means that -deadline
  237. tasks can use at most 95%, multiplied by the number of CPUs that compose the
  238. root_domain, for each root_domain.
  239. This means that non -deadline tasks will receive at least 5% of the CPU time,
  240. and that -deadline tasks will receive their runtime with a guaranteed
  241. worst-case delay respect to the "deadline" parameter. If "deadline" = "period"
  242. and the cpuset mechanism is used to implement partitioned scheduling (see
  243. Section 5), then this simple setting of the bandwidth management is able to
  244. deterministically guarantee that -deadline tasks will receive their runtime
  245. in a period.
  246. Finally, notice that in order not to jeopardize the admission control a
  247. -deadline task cannot fork.
  248. 5. Tasks CPU affinity
  249. =====================
  250. -deadline tasks cannot have an affinity mask smaller that the entire
  251. root_domain they are created on. However, affinities can be specified
  252. through the cpuset facility (Documentation/cgroups/cpusets.txt).
  253. 5.1 SCHED_DEADLINE and cpusets HOWTO
  254. ------------------------------------
  255. An example of a simple configuration (pin a -deadline task to CPU0)
  256. follows (rt-app is used to create a -deadline task).
  257. mkdir /dev/cpuset
  258. mount -t cgroup -o cpuset cpuset /dev/cpuset
  259. cd /dev/cpuset
  260. mkdir cpu0
  261. echo 0 > cpu0/cpuset.cpus
  262. echo 0 > cpu0/cpuset.mems
  263. echo 1 > cpuset.cpu_exclusive
  264. echo 0 > cpuset.sched_load_balance
  265. echo 1 > cpu0/cpuset.cpu_exclusive
  266. echo 1 > cpu0/cpuset.mem_exclusive
  267. echo $$ > cpu0/tasks
  268. rt-app -t 100000:10000:d:0 -D5 (it is now actually superfluous to specify
  269. task affinity)
  270. 6. Future plans
  271. ===============
  272. Still missing:
  273. - refinements to deadline inheritance, especially regarding the possibility
  274. of retaining bandwidth isolation among non-interacting tasks. This is
  275. being studied from both theoretical and practical points of view, and
  276. hopefully we should be able to produce some demonstrative code soon;
  277. - (c)group based bandwidth management, and maybe scheduling;
  278. - access control for non-root users (and related security concerns to
  279. address), which is the best way to allow unprivileged use of the mechanisms
  280. and how to prevent non-root users "cheat" the system?
  281. As already discussed, we are planning also to merge this work with the EDF
  282. throttling patches [https://lkml.org/lkml/2010/2/23/239] but we still are in
  283. the preliminary phases of the merge and we really seek feedback that would
  284. help us decide on the direction it should take.
  285. Appendix A. Test suite
  286. ======================
  287. The SCHED_DEADLINE policy can be easily tested using two applications that
  288. are part of a wider Linux Scheduler validation suite. The suite is
  289. available as a GitHub repository: https://github.com/scheduler-tools.
  290. The first testing application is called rt-app and can be used to
  291. start multiple threads with specific parameters. rt-app supports
  292. SCHED_{OTHER,FIFO,RR,DEADLINE} scheduling policies and their related
  293. parameters (e.g., niceness, priority, runtime/deadline/period). rt-app
  294. is a valuable tool, as it can be used to synthetically recreate certain
  295. workloads (maybe mimicking real use-cases) and evaluate how the scheduler
  296. behaves under such workloads. In this way, results are easily reproducible.
  297. rt-app is available at: https://github.com/scheduler-tools/rt-app.
  298. Thread parameters can be specified from the command line, with something like
  299. this:
  300. # rt-app -t 100000:10000:d -t 150000:20000:f:10 -D5
  301. The above creates 2 threads. The first one, scheduled by SCHED_DEADLINE,
  302. executes for 10ms every 100ms. The second one, scheduled at SCHED_FIFO
  303. priority 10, executes for 20ms every 150ms. The test will run for a total
  304. of 5 seconds.
  305. More interestingly, configurations can be described with a json file that
  306. can be passed as input to rt-app with something like this:
  307. # rt-app my_config.json
  308. The parameters that can be specified with the second method are a superset
  309. of the command line options. Please refer to rt-app documentation for more
  310. details (<rt-app-sources>/doc/*.json).
  311. The second testing application is a modification of schedtool, called
  312. schedtool-dl, which can be used to setup SCHED_DEADLINE parameters for a
  313. certain pid/application. schedtool-dl is available at:
  314. https://github.com/scheduler-tools/schedtool-dl.git.
  315. The usage is straightforward:
  316. # schedtool -E -t 10000000:100000000 -e ./my_cpuhog_app
  317. With this, my_cpuhog_app is put to run inside a SCHED_DEADLINE reservation
  318. of 10ms every 100ms (note that parameters are expressed in microseconds).
  319. You can also use schedtool to create a reservation for an already running
  320. application, given that you know its pid:
  321. # schedtool -E -t 10000000:100000000 my_app_pid
  322. Appendix B. Minimal main()
  323. ==========================
  324. We provide in what follows a simple (ugly) self-contained code snippet
  325. showing how SCHED_DEADLINE reservations can be created by a real-time
  326. application developer.
  327. #define _GNU_SOURCE
  328. #include <unistd.h>
  329. #include <stdio.h>
  330. #include <stdlib.h>
  331. #include <string.h>
  332. #include <time.h>
  333. #include <linux/unistd.h>
  334. #include <linux/kernel.h>
  335. #include <linux/types.h>
  336. #include <sys/syscall.h>
  337. #include <pthread.h>
  338. #define gettid() syscall(__NR_gettid)
  339. #define SCHED_DEADLINE 6
  340. /* XXX use the proper syscall numbers */
  341. #ifdef __x86_64__
  342. #define __NR_sched_setattr 314
  343. #define __NR_sched_getattr 315
  344. #endif
  345. #ifdef __i386__
  346. #define __NR_sched_setattr 351
  347. #define __NR_sched_getattr 352
  348. #endif
  349. #ifdef __arm__
  350. #define __NR_sched_setattr 380
  351. #define __NR_sched_getattr 381
  352. #endif
  353. static volatile int done;
  354. struct sched_attr {
  355. __u32 size;
  356. __u32 sched_policy;
  357. __u64 sched_flags;
  358. /* SCHED_NORMAL, SCHED_BATCH */
  359. __s32 sched_nice;
  360. /* SCHED_FIFO, SCHED_RR */
  361. __u32 sched_priority;
  362. /* SCHED_DEADLINE (nsec) */
  363. __u64 sched_runtime;
  364. __u64 sched_deadline;
  365. __u64 sched_period;
  366. };
  367. int sched_setattr(pid_t pid,
  368. const struct sched_attr *attr,
  369. unsigned int flags)
  370. {
  371. return syscall(__NR_sched_setattr, pid, attr, flags);
  372. }
  373. int sched_getattr(pid_t pid,
  374. struct sched_attr *attr,
  375. unsigned int size,
  376. unsigned int flags)
  377. {
  378. return syscall(__NR_sched_getattr, pid, attr, size, flags);
  379. }
  380. void *run_deadline(void *data)
  381. {
  382. struct sched_attr attr;
  383. int x = 0;
  384. int ret;
  385. unsigned int flags = 0;
  386. printf("deadline thread started [%ld]\n", gettid());
  387. attr.size = sizeof(attr);
  388. attr.sched_flags = 0;
  389. attr.sched_nice = 0;
  390. attr.sched_priority = 0;
  391. /* This creates a 10ms/30ms reservation */
  392. attr.sched_policy = SCHED_DEADLINE;
  393. attr.sched_runtime = 10 * 1000 * 1000;
  394. attr.sched_period = attr.sched_deadline = 30 * 1000 * 1000;
  395. ret = sched_setattr(0, &attr, flags);
  396. if (ret < 0) {
  397. done = 0;
  398. perror("sched_setattr");
  399. exit(-1);
  400. }
  401. while (!done) {
  402. x++;
  403. }
  404. printf("deadline thread dies [%ld]\n", gettid());
  405. return NULL;
  406. }
  407. int main (int argc, char **argv)
  408. {
  409. pthread_t thread;
  410. printf("main thread [%ld]\n", gettid());
  411. pthread_create(&thread, NULL, run_deadline, NULL);
  412. sleep(10);
  413. done = 1;
  414. pthread_join(thread, NULL);
  415. printf("main dies [%ld]\n", gettid());
  416. return 0;
  417. }