890 lines · plain
1========================2Deadline Task Scheduling3========================4 5.. CONTENTS6 7 0. WARNING8 1. Overview9 2. Scheduling algorithm10 2.1 Main algorithm11 2.2 Bandwidth reclaiming12 3. Scheduling Real-Time Tasks13 3.1 Definitions14 3.2 Schedulability Analysis for Uniprocessor Systems15 3.3 Schedulability Analysis for Multiprocessor Systems16 3.4 Relationship with SCHED_DEADLINE Parameters17 4. Bandwidth management18 4.1 System-wide settings19 4.2 Task interface20 4.3 Default behavior21 4.4 Behavior of sched_yield()22 5. Tasks CPU affinity23 5.1 SCHED_DEADLINE and cpusets HOWTO24 6. Future plans25 A. Test suite26 B. Minimal main()27 28 290. WARNING30==========31 32 Fiddling with these settings can result in an unpredictable or even unstable33 system behavior. As for -rt (group) scheduling, it is assumed that root users34 know what they're doing.35 36 371. Overview38===========39 40 The SCHED_DEADLINE policy contained inside the sched_dl scheduling class is41 basically an implementation of the Earliest Deadline First (EDF) scheduling42 algorithm, augmented with a mechanism (called Constant Bandwidth Server, CBS)43 that makes it possible to isolate the behavior of tasks between each other.44 45 462. Scheduling algorithm47=======================48 492.1 Main algorithm50------------------51 52 SCHED_DEADLINE [18] uses three parameters, named "runtime", "period", and53 "deadline", to schedule tasks. A SCHED_DEADLINE task should receive54 "runtime" microseconds of execution time every "period" microseconds, and55 these "runtime" microseconds are available within "deadline" microseconds56 from the beginning of the period. In order to implement this behavior,57 every time the task wakes up, the scheduler computes a "scheduling deadline"58 consistent with the guarantee (using the CBS[2,3] algorithm). Tasks are then59 scheduled using EDF[1] on these scheduling deadlines (the task with the60 earliest scheduling deadline is selected for execution). Notice that the61 task actually receives "runtime" time units within "deadline" if a proper62 "admission control" strategy (see Section "4. Bandwidth management") is used63 (clearly, if the system is overloaded this guarantee cannot be respected).64 65 Summing up, the CBS[2,3] algorithm assigns scheduling deadlines to tasks so66 that each task runs for at most its runtime every period, avoiding any67 interference between different tasks (bandwidth isolation), while the EDF[1]68 algorithm selects the task with the earliest scheduling deadline as the one69 to be executed next. Thanks to this feature, tasks that do not strictly comply70 with the "traditional" real-time task model (see Section 3) can effectively71 use the new policy.72 73 In more details, the CBS algorithm assigns scheduling deadlines to74 tasks in the following way:75 76 - Each SCHED_DEADLINE task is characterized by the "runtime",77 "deadline", and "period" parameters;78 79 - The state of the task is described by a "scheduling deadline", and80 a "remaining runtime". These two parameters are initially set to 0;81 82 - When a SCHED_DEADLINE task wakes up (becomes ready for execution),83 the scheduler checks if::84 85 remaining runtime runtime86 ---------------------------------- > ---------87 scheduling deadline - current time period88 89 then, if the scheduling deadline is smaller than the current time, or90 this condition is verified, the scheduling deadline and the91 remaining runtime are re-initialized as92 93 scheduling deadline = current time + deadline94 remaining runtime = runtime95 96 otherwise, the scheduling deadline and the remaining runtime are97 left unchanged;98 99 - When a SCHED_DEADLINE task executes for an amount of time t, its100 remaining runtime is decreased as::101 102 remaining runtime = remaining runtime - t103 104 (technically, the runtime is decreased at every tick, or when the105 task is descheduled / preempted);106 107 - When the remaining runtime becomes less or equal than 0, the task is108 said to be "throttled" (also known as "depleted" in real-time literature)109 and cannot be scheduled until its scheduling deadline. The "replenishment110 time" for this task (see next item) is set to be equal to the current111 value of the scheduling deadline;112 113 - When the current time is equal to the replenishment time of a114 throttled task, the scheduling deadline and the remaining runtime are115 updated as::116 117 scheduling deadline = scheduling deadline + period118 remaining runtime = remaining runtime + runtime119 120 The SCHED_FLAG_DL_OVERRUN flag in sched_attr's sched_flags field allows a task121 to get informed about runtime overruns through the delivery of SIGXCPU122 signals.123 124 1252.2 Bandwidth reclaiming126------------------------127 128 Bandwidth reclaiming for deadline tasks is based on the GRUB (Greedy129 Reclamation of Unused Bandwidth) algorithm [15, 16, 17] and it is enabled130 when flag SCHED_FLAG_RECLAIM is set.131 132 The following diagram illustrates the state names for tasks handled by GRUB::133 134 ------------135 (d) | Active |136 ------------->| |137 | | Contending |138 | ------------139 | A |140 ---------- | |141 | | | |142 | Inactive | |(b) | (a)143 | | | |144 ---------- | |145 A | V146 | ------------147 | | Active |148 --------------| Non |149 (c) | Contending |150 ------------151 152 A task can be in one of the following states:153 154 - ActiveContending: if it is ready for execution (or executing);155 156 - ActiveNonContending: if it just blocked and has not yet surpassed the 0-lag157 time;158 159 - Inactive: if it is blocked and has surpassed the 0-lag time.160 161 State transitions:162 163 (a) When a task blocks, it does not become immediately inactive since its164 bandwidth cannot be immediately reclaimed without breaking the165 real-time guarantees. It therefore enters a transitional state called166 ActiveNonContending. The scheduler arms the "inactive timer" to fire at167 the 0-lag time, when the task's bandwidth can be reclaimed without168 breaking the real-time guarantees.169 170 The 0-lag time for a task entering the ActiveNonContending state is171 computed as::172 173 (runtime * dl_period)174 deadline - ---------------------175 dl_runtime176 177 where runtime is the remaining runtime, while dl_runtime and dl_period178 are the reservation parameters.179 180 (b) If the task wakes up before the inactive timer fires, the task re-enters181 the ActiveContending state and the "inactive timer" is canceled.182 In addition, if the task wakes up on a different runqueue, then183 the task's utilization must be removed from the previous runqueue's active184 utilization and must be added to the new runqueue's active utilization.185 In order to avoid races between a task waking up on a runqueue while the186 "inactive timer" is running on a different CPU, the "dl_non_contending"187 flag is used to indicate that a task is not on a runqueue but is active188 (so, the flag is set when the task blocks and is cleared when the189 "inactive timer" fires or when the task wakes up).190 191 (c) When the "inactive timer" fires, the task enters the Inactive state and192 its utilization is removed from the runqueue's active utilization.193 194 (d) When an inactive task wakes up, it enters the ActiveContending state and195 its utilization is added to the active utilization of the runqueue where196 it has been enqueued.197 198 For each runqueue, the algorithm GRUB keeps track of two different bandwidths:199 200 - Active bandwidth (running_bw): this is the sum of the bandwidths of all201 tasks in active state (i.e., ActiveContending or ActiveNonContending);202 203 - Total bandwidth (this_bw): this is the sum of all tasks "belonging" to the204 runqueue, including the tasks in Inactive state.205 206 - Maximum usable bandwidth (max_bw): This is the maximum bandwidth usable by207 deadline tasks and is currently set to the RT capacity.208 209 210 The algorithm reclaims the bandwidth of the tasks in Inactive state.211 It does so by decrementing the runtime of the executing task Ti at a pace equal212 to213 214 dq = -(max{ Ui, (Umax - Uinact - Uextra) } / Umax) dt215 216 where:217 218 - Ui is the bandwidth of task Ti;219 - Umax is the maximum reclaimable utilization (subjected to RT throttling220 limits);221 - Uinact is the (per runqueue) inactive utilization, computed as222 (this_bq - running_bw);223 - Uextra is the (per runqueue) extra reclaimable utilization224 (subjected to RT throttling limits).225 226 227 Let's now see a trivial example of two deadline tasks with runtime equal228 to 4 and period equal to 8 (i.e., bandwidth equal to 0.5)::229 230 A Task T1231 |232 | |233 | |234 |-------- |----235 | | V236 |---|---|---|---|---|---|---|---|--------->t237 0 1 2 3 4 5 6 7 8238 239 240 A Task T2241 |242 | |243 | |244 | ------------------------|245 | | V246 |---|---|---|---|---|---|---|---|--------->t247 0 1 2 3 4 5 6 7 8248 249 250 A running_bw251 |252 1 ----------------- ------253 | | |254 0.5- -----------------255 | |256 |---|---|---|---|---|---|---|---|--------->t257 0 1 2 3 4 5 6 7 8258 259 260 - Time t = 0:261 262 Both tasks are ready for execution and therefore in ActiveContending state.263 Suppose Task T1 is the first task to start execution.264 Since there are no inactive tasks, its runtime is decreased as dq = -1 dt.265 266 - Time t = 2:267 268 Suppose that task T1 blocks269 Task T1 therefore enters the ActiveNonContending state. Since its remaining270 runtime is equal to 2, its 0-lag time is equal to t = 4.271 Task T2 start execution, with runtime still decreased as dq = -1 dt since272 there are no inactive tasks.273 274 - Time t = 4:275 276 This is the 0-lag time for Task T1. Since it didn't woken up in the277 meantime, it enters the Inactive state. Its bandwidth is removed from278 running_bw.279 Task T2 continues its execution. However, its runtime is now decreased as280 dq = - 0.5 dt because Uinact = 0.5.281 Task T2 therefore reclaims the bandwidth unused by Task T1.282 283 - Time t = 8:284 285 Task T1 wakes up. It enters the ActiveContending state again, and the286 running_bw is incremented.287 288 2892.3 Energy-aware scheduling290---------------------------291 292 When cpufreq's schedutil governor is selected, SCHED_DEADLINE implements the293 GRUB-PA [19] algorithm, reducing the CPU operating frequency to the minimum294 value that still allows to meet the deadlines. This behavior is currently295 implemented only for ARM architectures.296 297 A particular care must be taken in case the time needed for changing frequency298 is of the same order of magnitude of the reservation period. In such cases,299 setting a fixed CPU frequency results in a lower amount of deadline misses.300 301 3023. Scheduling Real-Time Tasks303=============================304 305 306 307 .. BIG FAT WARNING ******************************************************308 309 .. warning::310 311 This section contains a (not-thorough) summary on classical deadline312 scheduling theory, and how it applies to SCHED_DEADLINE.313 The reader can "safely" skip to Section 4 if only interested in seeing314 how the scheduling policy can be used. Anyway, we strongly recommend315 to come back here and continue reading (once the urge for testing is316 satisfied :P) to be sure of fully understanding all technical details.317 318 .. ************************************************************************319 320 There are no limitations on what kind of task can exploit this new321 scheduling discipline, even if it must be said that it is particularly322 suited for periodic or sporadic real-time tasks that need guarantees on their323 timing behavior, e.g., multimedia, streaming, control applications, etc.324 3253.1 Definitions326------------------------327 328 A typical real-time task is composed of a repetition of computation phases329 (task instances, or jobs) which are activated on a periodic or sporadic330 fashion.331 Each job J_j (where J_j is the j^th job of the task) is characterized by an332 arrival time r_j (the time when the job starts), an amount of computation333 time c_j needed to finish the job, and a job absolute deadline d_j, which334 is the time within which the job should be finished. The maximum execution335 time max{c_j} is called "Worst Case Execution Time" (WCET) for the task.336 A real-time task can be periodic with period P if r_{j+1} = r_j + P, or337 sporadic with minimum inter-arrival time P is r_{j+1} >= r_j + P. Finally,338 d_j = r_j + D, where D is the task's relative deadline.339 Summing up, a real-time task can be described as340 341 Task = (WCET, D, P)342 343 The utilization of a real-time task is defined as the ratio between its344 WCET and its period (or minimum inter-arrival time), and represents345 the fraction of CPU time needed to execute the task.346 347 If the total utilization U=sum(WCET_i/P_i) is larger than M (with M equal348 to the number of CPUs), then the scheduler is unable to respect all the349 deadlines.350 Note that total utilization is defined as the sum of the utilizations351 WCET_i/P_i over all the real-time tasks in the system. When considering352 multiple real-time tasks, the parameters of the i-th task are indicated353 with the "_i" suffix.354 Moreover, if the total utilization is larger than M, then we risk starving355 non- real-time tasks by real-time tasks.356 If, instead, the total utilization is smaller than M, then non real-time357 tasks will not be starved and the system might be able to respect all the358 deadlines.359 As a matter of fact, in this case it is possible to provide an upper bound360 for tardiness (defined as the maximum between 0 and the difference361 between the finishing time of a job and its absolute deadline).362 More precisely, it can be proven that using a global EDF scheduler the363 maximum tardiness of each task is smaller or equal than364 365 ((M − 1) · WCET_max − WCET_min)/(M − (M − 2) · U_max) + WCET_max366 367 where WCET_max = max{WCET_i} is the maximum WCET, WCET_min=min{WCET_i}368 is the minimum WCET, and U_max = max{WCET_i/P_i} is the maximum369 utilization[12].370 3713.2 Schedulability Analysis for Uniprocessor Systems372----------------------------------------------------373 374 If M=1 (uniprocessor system), or in case of partitioned scheduling (each375 real-time task is statically assigned to one and only one CPU), it is376 possible to formally check if all the deadlines are respected.377 If D_i = P_i for all tasks, then EDF is able to respect all the deadlines378 of all the tasks executing on a CPU if and only if the total utilization379 of the tasks running on such a CPU is smaller or equal than 1.380 If D_i != P_i for some task, then it is possible to define the density of381 a task as WCET_i/min{D_i,P_i}, and EDF is able to respect all the deadlines382 of all the tasks running on a CPU if the sum of the densities of the tasks383 running on such a CPU is smaller or equal than 1:384 385 sum(WCET_i / min{D_i, P_i}) <= 1386 387 It is important to notice that this condition is only sufficient, and not388 necessary: there are task sets that are schedulable, but do not respect the389 condition. For example, consider the task set {Task_1,Task_2} composed by390 Task_1=(50ms,50ms,100ms) and Task_2=(10ms,100ms,100ms).391 EDF is clearly able to schedule the two tasks without missing any deadline392 (Task_1 is scheduled as soon as it is released, and finishes just in time393 to respect its deadline; Task_2 is scheduled immediately after Task_1, hence394 its response time cannot be larger than 50ms + 10ms = 60ms) even if395 396 50 / min{50,100} + 10 / min{100, 100} = 50 / 50 + 10 / 100 = 1.1397 398 Of course it is possible to test the exact schedulability of tasks with399 D_i != P_i (checking a condition that is both sufficient and necessary),400 but this cannot be done by comparing the total utilization or density with401 a constant. Instead, the so called "processor demand" approach can be used,402 computing the total amount of CPU time h(t) needed by all the tasks to403 respect all of their deadlines in a time interval of size t, and comparing404 such a time with the interval size t. If h(t) is smaller than t (that is,405 the amount of time needed by the tasks in a time interval of size t is406 smaller than the size of the interval) for all the possible values of t, then407 EDF is able to schedule the tasks respecting all of their deadlines. Since408 performing this check for all possible values of t is impossible, it has been409 proven[4,5,6] that it is sufficient to perform the test for values of t410 between 0 and a maximum value L. The cited papers contain all of the411 mathematical details and explain how to compute h(t) and L.412 In any case, this kind of analysis is too complex as well as too413 time-consuming to be performed on-line. Hence, as explained in Section414 4 Linux uses an admission test based on the tasks' utilizations.415 4163.3 Schedulability Analysis for Multiprocessor Systems417------------------------------------------------------418 419 On multiprocessor systems with global EDF scheduling (non partitioned420 systems), a sufficient test for schedulability can not be based on the421 utilizations or densities: it can be shown that even if D_i = P_i task422 sets with utilizations slightly larger than 1 can miss deadlines regardless423 of the number of CPUs.424 425 Consider a set {Task_1,...Task_{M+1}} of M+1 tasks on a system with M426 CPUs, with the first task Task_1=(P,P,P) having period, relative deadline427 and WCET equal to P. The remaining M tasks Task_i=(e,P-1,P-1) have an428 arbitrarily small worst case execution time (indicated as "e" here) and a429 period smaller than the one of the first task. Hence, if all the tasks430 activate at the same time t, global EDF schedules these M tasks first431 (because their absolute deadlines are equal to t + P - 1, hence they are432 smaller than the absolute deadline of Task_1, which is t + P). As a433 result, Task_1 can be scheduled only at time t + e, and will finish at434 time t + e + P, after its absolute deadline. The total utilization of the435 task set is U = M · e / (P - 1) + P / P = M · e / (P - 1) + 1, and for small436 values of e this can become very close to 1. This is known as "Dhall's437 effect"[7]. Note: the example in the original paper by Dhall has been438 slightly simplified here (for example, Dhall more correctly computed439 lim_{e->0}U).440 441 More complex schedulability tests for global EDF have been developed in442 real-time literature[8,9], but they are not based on a simple comparison443 between total utilization (or density) and a fixed constant. If all tasks444 have D_i = P_i, a sufficient schedulability condition can be expressed in445 a simple way:446 447 sum(WCET_i / P_i) <= M - (M - 1) · U_max448 449 where U_max = max{WCET_i / P_i}[10]. Notice that for U_max = 1,450 M - (M - 1) · U_max becomes M - M + 1 = 1 and this schedulability condition451 just confirms the Dhall's effect. A more complete survey of the literature452 about schedulability tests for multi-processor real-time scheduling can be453 found in [11].454 455 As seen, enforcing that the total utilization is smaller than M does not456 guarantee that global EDF schedules the tasks without missing any deadline457 (in other words, global EDF is not an optimal scheduling algorithm). However,458 a total utilization smaller than M is enough to guarantee that non real-time459 tasks are not starved and that the tardiness of real-time tasks has an upper460 bound[12] (as previously noted). Different bounds on the maximum tardiness461 experienced by real-time tasks have been developed in various papers[13,14],462 but the theoretical result that is important for SCHED_DEADLINE is that if463 the total utilization is smaller or equal than M then the response times of464 the tasks are limited.465 4663.4 Relationship with SCHED_DEADLINE Parameters467-----------------------------------------------468 469 Finally, it is important to understand the relationship between the470 SCHED_DEADLINE scheduling parameters described in Section 2 (runtime,471 deadline and period) and the real-time task parameters (WCET, D, P)472 described in this section. Note that the tasks' temporal constraints are473 represented by its absolute deadlines d_j = r_j + D described above, while474 SCHED_DEADLINE schedules the tasks according to scheduling deadlines (see475 Section 2).476 If an admission test is used to guarantee that the scheduling deadlines477 are respected, then SCHED_DEADLINE can be used to schedule real-time tasks478 guaranteeing that all the jobs' deadlines of a task are respected.479 In order to do this, a task must be scheduled by setting:480 481 - runtime >= WCET482 - deadline = D483 - period <= P484 485 IOW, if runtime >= WCET and if period is <= P, then the scheduling deadlines486 and the absolute deadlines (d_j) coincide, so a proper admission control487 allows to respect the jobs' absolute deadlines for this task (this is what is488 called "hard schedulability property" and is an extension of Lemma 1 of [2]).489 Notice that if runtime > deadline the admission control will surely reject490 this task, as it is not possible to respect its temporal constraints.491 492 References:493 494 1 - C. L. Liu and J. W. Layland. Scheduling algorithms for multiprogram-495 ming in a hard-real-time environment. Journal of the Association for496 Computing Machinery, 20(1), 1973.497 2 - L. Abeni , G. Buttazzo. Integrating Multimedia Applications in Hard498 Real-Time Systems. Proceedings of the 19th IEEE Real-time Systems499 Symposium, 1998. http://retis.sssup.it/~giorgio/paps/1998/rtss98-cbs.pdf500 3 - L. Abeni. Server Mechanisms for Multimedia Applications. ReTiS Lab501 Technical Report. http://disi.unitn.it/~abeni/tr-98-01.pdf502 4 - J. Y. Leung and M.L. Merril. A Note on Preemptive Scheduling of503 Periodic, Real-Time Tasks. Information Processing Letters, vol. 11,504 no. 3, pp. 115-118, 1980.505 5 - S. K. Baruah, A. K. Mok and L. E. Rosier. Preemptively Scheduling506 Hard-Real-Time Sporadic Tasks on One Processor. Proceedings of the507 11th IEEE Real-time Systems Symposium, 1990.508 6 - S. K. Baruah, L. E. Rosier and R. R. Howell. Algorithms and Complexity509 Concerning the Preemptive Scheduling of Periodic Real-Time tasks on510 One Processor. Real-Time Systems Journal, vol. 4, no. 2, pp 301-324,511 1990.512 7 - S. J. Dhall and C. L. Liu. On a real-time scheduling problem. Operations513 research, vol. 26, no. 1, pp 127-140, 1978.514 8 - T. Baker. Multiprocessor EDF and Deadline Monotonic Schedulability515 Analysis. Proceedings of the 24th IEEE Real-Time Systems Symposium, 2003.516 9 - T. Baker. An Analysis of EDF Schedulability on a Multiprocessor.517 IEEE Transactions on Parallel and Distributed Systems, vol. 16, no. 8,518 pp 760-768, 2005.519 10 - J. Goossens, S. Funk and S. Baruah, Priority-Driven Scheduling of520 Periodic Task Systems on Multiprocessors. Real-Time Systems Journal,521 vol. 25, no. 2–3, pp. 187–205, 2003.522 11 - R. Davis and A. Burns. A Survey of Hard Real-Time Scheduling for523 Multiprocessor Systems. ACM Computing Surveys, vol. 43, no. 4, 2011.524 http://www-users.cs.york.ac.uk/~robdavis/papers/MPSurveyv5.0.pdf525 12 - U. C. Devi and J. H. Anderson. Tardiness Bounds under Global EDF526 Scheduling on a Multiprocessor. Real-Time Systems Journal, vol. 32,527 no. 2, pp 133-189, 2008.528 13 - P. Valente and G. Lipari. An Upper Bound to the Lateness of Soft529 Real-Time Tasks Scheduled by EDF on Multiprocessors. Proceedings of530 the 26th IEEE Real-Time Systems Symposium, 2005.531 14 - J. Erickson, U. Devi and S. Baruah. Improved tardiness bounds for532 Global EDF. Proceedings of the 22nd Euromicro Conference on533 Real-Time Systems, 2010.534 15 - G. Lipari, S. Baruah, Greedy reclamation of unused bandwidth in535 constant-bandwidth servers, 12th IEEE Euromicro Conference on Real-Time536 Systems, 2000.537 16 - L. Abeni, J. Lelli, C. Scordino, L. Palopoli, Greedy CPU reclaiming for538 SCHED DEADLINE. In Proceedings of the Real-Time Linux Workshop (RTLWS),539 Dusseldorf, Germany, 2014.540 17 - L. Abeni, G. Lipari, A. Parri, Y. Sun, Multicore CPU reclaiming: parallel541 or sequential?. In Proceedings of the 31st Annual ACM Symposium on Applied542 Computing, 2016.543 18 - J. Lelli, C. Scordino, L. Abeni, D. Faggioli, Deadline scheduling in the544 Linux kernel, Software: Practice and Experience, 46(6): 821-839, June545 2016.546 19 - C. Scordino, L. Abeni, J. Lelli, Energy-Aware Real-Time Scheduling in547 the Linux Kernel, 33rd ACM/SIGAPP Symposium On Applied Computing (SAC548 2018), Pau, France, April 2018.549 550 5514. Bandwidth management552=======================553 554 As previously mentioned, in order for -deadline scheduling to be555 effective and useful (that is, to be able to provide "runtime" time units556 within "deadline"), it is important to have some method to keep the allocation557 of the available fractions of CPU time to the various tasks under control.558 This is usually called "admission control" and if it is not performed, then559 no guarantee can be given on the actual scheduling of the -deadline tasks.560 561 As already stated in Section 3, a necessary condition to be respected to562 correctly schedule a set of real-time tasks is that the total utilization563 is smaller than M. When talking about -deadline tasks, this requires that564 the sum of the ratio between runtime and period for all tasks is smaller565 than M. Notice that the ratio runtime/period is equivalent to the utilization566 of a "traditional" real-time task, and is also often referred to as567 "bandwidth".568 The interface used to control the CPU bandwidth that can be allocated569 to -deadline tasks is similar to the one already used for -rt570 tasks with real-time group scheduling (a.k.a. RT-throttling - see571 Documentation/scheduler/sched-rt-group.rst), and is based on readable/572 writable control files located in procfs (for system wide settings).573 Notice that per-group settings (controlled through cgroupfs) are still not574 defined for -deadline tasks, because more discussion is needed in order to575 figure out how we want to manage SCHED_DEADLINE bandwidth at the task group576 level.577 578 A main difference between deadline bandwidth management and RT-throttling579 is that -deadline tasks have bandwidth on their own (while -rt ones don't!),580 and thus we don't need a higher level throttling mechanism to enforce the581 desired bandwidth. In other words, this means that interface parameters are582 only used at admission control time (i.e., when the user calls583 sched_setattr()). Scheduling is then performed considering actual tasks'584 parameters, so that CPU bandwidth is allocated to SCHED_DEADLINE tasks585 respecting their needs in terms of granularity. Therefore, using this simple586 interface we can put a cap on total utilization of -deadline tasks (i.e.,587 \Sum (runtime_i / period_i) < global_dl_utilization_cap).588 5894.1 System wide settings590------------------------591 592 The system wide settings are configured under the /proc virtual file system.593 594 For now the -rt knobs are used for -deadline admission control and the595 -deadline runtime is accounted against the -rt runtime. We realize that this596 isn't entirely desirable; however, it is better to have a small interface for597 now, and be able to change it easily later. The ideal situation (see 5.) is to598 run -rt tasks from a -deadline server; in which case the -rt bandwidth is a599 direct subset of dl_bw.600 601 This means that, for a root_domain comprising M CPUs, -deadline tasks602 can be created while the sum of their bandwidths stays below:603 604 M * (sched_rt_runtime_us / sched_rt_period_us)605 606 It is also possible to disable this bandwidth management logic, and607 be thus free of oversubscribing the system up to any arbitrary level.608 This is done by writing -1 in /proc/sys/kernel/sched_rt_runtime_us.609 610 6114.2 Task interface612------------------613 614 Specifying a periodic/sporadic task that executes for a given amount of615 runtime at each instance, and that is scheduled according to the urgency of616 its own timing constraints needs, in general, a way of declaring:617 618 - a (maximum/typical) instance execution time,619 - a minimum interval between consecutive instances,620 - a time constraint by which each instance must be completed.621 622 Therefore:623 624 * a new struct sched_attr, containing all the necessary fields is625 provided;626 * the new scheduling related syscalls that manipulate it, i.e.,627 sched_setattr() and sched_getattr() are implemented.628 629 For debugging purposes, the leftover runtime and absolute deadline of a630 SCHED_DEADLINE task can be retrieved through /proc/<pid>/sched (entries631 dl.runtime and dl.deadline, both values in ns). A programmatic way to632 retrieve these values from production code is under discussion.633 634 6354.3 Default behavior636---------------------637 638 The default value for SCHED_DEADLINE bandwidth is to have rt_runtime equal to639 950000. With rt_period equal to 1000000, by default, it means that -deadline640 tasks can use at most 95%, multiplied by the number of CPUs that compose the641 root_domain, for each root_domain.642 This means that non -deadline tasks will receive at least 5% of the CPU time,643 and that -deadline tasks will receive their runtime with a guaranteed644 worst-case delay respect to the "deadline" parameter. If "deadline" = "period"645 and the cpuset mechanism is used to implement partitioned scheduling (see646 Section 5), then this simple setting of the bandwidth management is able to647 deterministically guarantee that -deadline tasks will receive their runtime648 in a period.649 650 Finally, notice that in order not to jeopardize the admission control a651 -deadline task cannot fork.652 653 6544.4 Behavior of sched_yield()655-----------------------------656 657 When a SCHED_DEADLINE task calls sched_yield(), it gives up its658 remaining runtime and is immediately throttled, until the next659 period, when its runtime will be replenished (a special flag660 dl_yielded is set and used to handle correctly throttling and runtime661 replenishment after a call to sched_yield()).662 663 This behavior of sched_yield() allows the task to wake-up exactly at664 the beginning of the next period. Also, this may be useful in the665 future with bandwidth reclaiming mechanisms, where sched_yield() will666 make the leftoever runtime available for reclamation by other667 SCHED_DEADLINE tasks.668 669 6705. Tasks CPU affinity671=====================672 673 -deadline tasks cannot have an affinity mask smaller that the entire674 root_domain they are created on. However, affinities can be specified675 through the cpuset facility (Documentation/admin-guide/cgroup-v1/cpusets.rst).676 6775.1 SCHED_DEADLINE and cpusets HOWTO678------------------------------------679 680 An example of a simple configuration (pin a -deadline task to CPU0)681 follows (rt-app is used to create a -deadline task)::682 683 mkdir /dev/cpuset684 mount -t cgroup -o cpuset cpuset /dev/cpuset685 cd /dev/cpuset686 mkdir cpu0687 echo 0 > cpu0/cpuset.cpus688 echo 0 > cpu0/cpuset.mems689 echo 1 > cpuset.cpu_exclusive690 echo 0 > cpuset.sched_load_balance691 echo 1 > cpu0/cpuset.cpu_exclusive692 echo 1 > cpu0/cpuset.mem_exclusive693 echo $$ > cpu0/tasks694 rt-app -t 100000:10000:d:0 -D5 # it is now actually superfluous to specify695 # task affinity696 6976. Future plans698===============699 700 Still missing:701 702 - programmatic way to retrieve current runtime and absolute deadline703 - refinements to deadline inheritance, especially regarding the possibility704 of retaining bandwidth isolation among non-interacting tasks. This is705 being studied from both theoretical and practical points of view, and706 hopefully we should be able to produce some demonstrative code soon;707 - (c)group based bandwidth management, and maybe scheduling;708 - access control for non-root users (and related security concerns to709 address), which is the best way to allow unprivileged use of the mechanisms710 and how to prevent non-root users "cheat" the system?711 712 As already discussed, we are planning also to merge this work with the EDF713 throttling patches [https://lore.kernel.org/r/cover.1266931410.git.fabio@helm.retis] but we still are in714 the preliminary phases of the merge and we really seek feedback that would715 help us decide on the direction it should take.716 717Appendix A. Test suite718======================719 720 The SCHED_DEADLINE policy can be easily tested using two applications that721 are part of a wider Linux Scheduler validation suite. The suite is722 available as a GitHub repository: https://github.com/scheduler-tools.723 724 The first testing application is called rt-app and can be used to725 start multiple threads with specific parameters. rt-app supports726 SCHED_{OTHER,FIFO,RR,DEADLINE} scheduling policies and their related727 parameters (e.g., niceness, priority, runtime/deadline/period). rt-app728 is a valuable tool, as it can be used to synthetically recreate certain729 workloads (maybe mimicking real use-cases) and evaluate how the scheduler730 behaves under such workloads. In this way, results are easily reproducible.731 rt-app is available at: https://github.com/scheduler-tools/rt-app.732 733 Thread parameters can be specified from the command line, with something like734 this::735 736 # rt-app -t 100000:10000:d -t 150000:20000:f:10 -D5737 738 The above creates 2 threads. The first one, scheduled by SCHED_DEADLINE,739 executes for 10ms every 100ms. The second one, scheduled at SCHED_FIFO740 priority 10, executes for 20ms every 150ms. The test will run for a total741 of 5 seconds.742 743 More interestingly, configurations can be described with a json file that744 can be passed as input to rt-app with something like this::745 746 # rt-app my_config.json747 748 The parameters that can be specified with the second method are a superset749 of the command line options. Please refer to rt-app documentation for more750 details (`<rt-app-sources>/doc/*.json`).751 752 The second testing application is done using chrt which has support753 for SCHED_DEADLINE.754 755 The usage is straightforward::756 757 # chrt -d -T 10000000 -D 100000000 0 ./my_cpuhog_app758 759 With this, my_cpuhog_app is put to run inside a SCHED_DEADLINE reservation760 of 10ms every 100ms (note that parameters are expressed in nanoseconds).761 You can also use chrt to create a reservation for an already running762 application, given that you know its pid::763 764 # chrt -d -T 10000000 -D 100000000 -p 0 my_app_pid765 766Appendix B. Minimal main()767==========================768 769 We provide in what follows a simple (ugly) self-contained code snippet770 showing how SCHED_DEADLINE reservations can be created by a real-time771 application developer::772 773 #define _GNU_SOURCE774 #include <unistd.h>775 #include <stdio.h>776 #include <stdlib.h>777 #include <string.h>778 #include <time.h>779 #include <linux/unistd.h>780 #include <linux/kernel.h>781 #include <linux/types.h>782 #include <sys/syscall.h>783 #include <pthread.h>784 785 #define gettid() syscall(__NR_gettid)786 787 #define SCHED_DEADLINE 6788 789 /* XXX use the proper syscall numbers */790 #ifdef __x86_64__791 #define __NR_sched_setattr 314792 #define __NR_sched_getattr 315793 #endif794 795 #ifdef __i386__796 #define __NR_sched_setattr 351797 #define __NR_sched_getattr 352798 #endif799 800 #ifdef __arm__801 #define __NR_sched_setattr 380802 #define __NR_sched_getattr 381803 #endif804 805 static volatile int done;806 807 struct sched_attr {808 __u32 size;809 810 __u32 sched_policy;811 __u64 sched_flags;812 813 /* SCHED_NORMAL, SCHED_BATCH */814 __s32 sched_nice;815 816 /* SCHED_FIFO, SCHED_RR */817 __u32 sched_priority;818 819 /* SCHED_DEADLINE (nsec) */820 __u64 sched_runtime;821 __u64 sched_deadline;822 __u64 sched_period;823 };824 825 int sched_setattr(pid_t pid,826 const struct sched_attr *attr,827 unsigned int flags)828 {829 return syscall(__NR_sched_setattr, pid, attr, flags);830 }831 832 int sched_getattr(pid_t pid,833 struct sched_attr *attr,834 unsigned int size,835 unsigned int flags)836 {837 return syscall(__NR_sched_getattr, pid, attr, size, flags);838 }839 840 void *run_deadline(void *data)841 {842 struct sched_attr attr;843 int x = 0;844 int ret;845 unsigned int flags = 0;846 847 printf("deadline thread started [%ld]\n", gettid());848 849 attr.size = sizeof(attr);850 attr.sched_flags = 0;851 attr.sched_nice = 0;852 attr.sched_priority = 0;853 854 /* This creates a 10ms/30ms reservation */855 attr.sched_policy = SCHED_DEADLINE;856 attr.sched_runtime = 10 * 1000 * 1000;857 attr.sched_period = attr.sched_deadline = 30 * 1000 * 1000;858 859 ret = sched_setattr(0, &attr, flags);860 if (ret < 0) {861 done = 0;862 perror("sched_setattr");863 exit(-1);864 }865 866 while (!done) {867 x++;868 }869 870 printf("deadline thread dies [%ld]\n", gettid());871 return NULL;872 }873 874 int main (int argc, char **argv)875 {876 pthread_t thread;877 878 printf("main thread [%ld]\n", gettid());879 880 pthread_create(&thread, NULL, run_deadline, NULL);881 882 sleep(10);883 884 done = 1;885 pthread_join(thread, NULL);886 887 printf("main dies [%ld]\n", gettid());888 return 0;889 }890