Skip to contentSkip to conversation

Add utilization clamping to the CPU controller

RFC In review Patrick Bellasi 2 participants 9 messages Aug 24, 2017 – Sep 4, 2017

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v4 cover Add utilization clamping to the CPU controller

Was:
- RFCv3: Add capacity capping support to the CPU controller
- RFCv2: SchedTune: central, scheduler-driven, power-performance control

This is a respin of the series implementing the support for per-task boosting and capping of CPU frequency. This new version addresses most of the comments collected since last posting on LKML [1] and from the discussions at the OSPM Summit [2].

Hereafter a short description of the main changes since the previous posting [1].

.:: Concept: "capacity clamping" replaced by "utilization clamping"

The previous implementation was expressed in terms of "capacity clamping", which generated some confusion mainly due to the fact that in mainline the capacity is currently defined as a "constant property" of a CPU. Here is a email [3] which resumes the confusion generated by the previous proposal.

As Peter pointed out, the goal of this proposal is to "affect" the util_avg metric, i.e. the CPU utilization, and the way that signal is used for example by schedutil. Thus, both from a conceptual and implementation standpoint, it actually makes a lot more sense to talk about "utilization clamping".

In this new proposal, the couple of new attributes added to the CPU controller allow to define the minimum and maximum utilization which should be considered for the set of tasks in a group.
These utilization clamp values can be used, for example, to either "boost" or "cap" the actual frequency selected by schedutil when one of these tasks is RUNNABLE on a CPU.
A proper aggregation mechanism is also provided to handle the cases where tasks with different utilization clamp values are co-scheduled on the same CPU.

.:: Implementation: rb-trees replaced by reference counting

The previous implementation used a couple of rb-trees to aggregate the different clamp values of tasks co-scheduled on the same CPU. Although being a simple solution, from the coding standpoint, Peter pointed out that it was definitively adding not negligible overheads in the fast path (i.e. tasks enqueue/dequeue) especially on highly loaded systems.

This new implementation is based on a much more lightweight mechanism using reference counting. The new solution requires just to {in,de}crement an integer counter each time a task is {en,de}eueued. The most expensive operation is now a sequential scan of a small and per-CPU array of integers, which is also defined to easily fit into a single cache line.

Scheduler performance overheads have been measured using the performance governor to run 20 iterations of:

   perf bench sched messaging --pipe --thread --group 2 --loop 5000

on a Juno R2 board (4xA53, 2xA72).
With this new implementation we cannot see any sensible impact when comparing with the same benchmark running on tip/sched/core (as in 9c8783201). For the records, the previous implementation showed ~1.5% overhead using the same test.

.:: Other comments: use-cases description

People had concerns about use-cases, in a previous posting [4] I've resumed the main use cases we are targeting with this proposal. Further discussion went on at OSPM, outside of the official tracks, and I've got the feeling that people (at least Peter and Raphael) seem to recognize the interest in having a support to both boosting or clamping of the CPU frequencies, based on currently active tasks.

Main discussed use cases was (refer to [4] further details):

- boosting: better interactive response for small tasks which are affecting the user experience. Consider for example the case of a small control thread for an external accelerator (e.g. GPU, DSP, other devices). In this case the scheduler does not have a complete view of what are the task bandwidth requirements and if, it's a small task, schedutil will keep selecting a lower frequency thus affecting the overall time required to complete its activations.

- clamping: increase energy efficiency for background tasks not directly affecting the user experience. Since running at a lower frequency is in general more energy efficient, when the completion time is not a main goal then clamping the maximum frequency to use for certain (maybe big) tasks can have positive effects, both on power dissipation and energy consumption.
Moreover, this last support allows also to make RT tasks more energy friendly on mobile systems, whenever running them at the maximum frequency is not strictly required.

.:: Other comments: usage of CGroups as a main interface

The current implementation is based on CGroups but does not strictly depend on that API. We do not propose a different main interface just because, so far, all the use-cases we have on hand can take advantage from a CGroups API (notably the Android run-time).

In case there should be the need for a different API, the current implementation can be easily extended to hook its internals to a different API. However, we believe it's not worth adding the maintenance burden for an additional API until there is not a real demand.

.:: Patches organization

The first three patches of this series introduce util_{min,max} tracking in the core scheduler, as an extension of the CPU controller. The fourth patch is dedicated to the synchronization between the cgroup interface (slow-path) and the core scheduler (fast-path). The last two patches integrate the utilization clamping support with schedutil for FAIR tasks and RT/DL tasks too.

A detailed validation and analysis of the proposed features is available in this notebook:
https://gist.github.com/7f9170e613dea25fe248e14157e6cb23

Cheers Patrick

.:: References
[1] https://lkml.org/lkml/2017/2/28/355
[2] slides: http://retis.sssup.it/ospm-summit/Downloads/OSPM_PELT_DecayClampingVsUtilEst.pdf
video: http://youtu.be/6MC1jbYbQTo
[3] https://lkml.org/lkml/2017/4/11/670
[4] https://lkml.org/lkml/2017/3/20/688

Patrick Bellasi (6):
sched/core: add utilization clamping to CPU controller sched/core: map cpu's task groups to clamp groups sched/core: reference count active tasks's clamp groups sched/core: sync task_group's with CPU's clamp groups
cpufreq: schedutil: add util clamp for FAIR tasks
cpufreq: schedutil: add util clamp for RT/DL tasks

 include/linux/sched.h            |  12 +
 init/Kconfig                     |  36 ++
 kernel/sched/core.c              | 706 +++++++++++++++++++++++++++++++++++++++
 kernel/sched/cpufreq_schedutil.c |  49 ++-
 kernel/sched/sched.h             | 199 +++++++++++
 5 files changed, 998 insertions(+), 4 deletions(-)
Signature · 1 line
2.14.1
#1 lore raw

RFC v4 1/6 sched/core: add utilization clamping to CPU controller

The cgroup's CPU controller allows to assign a specified (maximum) bandwidth to the tasks of a group. However this bandwidth is defined and enforced only on a temporal base, without considering the actual frequency a CPU is running on. Thus, the amount of computation completed by a task within an allocated bandwidth can be very different depending on the actual frequency the CPU is running that task.

With the availability of schedutil, the scheduler is now able to drive frequency selections based on the actual tasks utilization. Thus, it is now possible to extend the cpu controller to specify what is the minimum (or maximum) utilization which a task is allowed to generate. By adding new constraints on minimum and maximum utilization allowed for tasks in a cpu control group it will be possible to better control the actual amount of CPU bandwidth consumed by these tasks.

The ultimate goal of this new pair of constraints is to enable:

- boosting: by selecting a higher execution frequency for small tasks which are affecting the user interactive experience

- capping: by enforcing lower execution frequency (which usually improves energy efficiency) for big tasks which are mainly related to background activities without a direct impact on the user experience.

This patch extends the CPU controller by adding a couple of new attributes, util_min and util_max, which can be used to enforce frequency boosting and capping. Specifically:

- util_min: defines the minimum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run at least at a minimum frequency which
corresponds to the min_util utilization

- util_max: defines the maximum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run up to a maximum frequency which
corresponds to the max_util utilization

These attributes:
a) are tunable at all hierarchy levels, i.e. at root group level too, thus allowing to defined minimum and maximum frequency constraints for all otherwise non-classified tasks (e.g. autogroups)
b) allow to create subgroups of tasks which are not violating the utilization constraints defined by the parent group.

Tasks on a subgroup can only be more boosted and/or capped, which is matching with the "limits" schema proposed by the "Resource Distribution Model (RDM)" suggested by the CGroups v2 documentation:
Documentation/cgroup-v2.txt

This patch provides the basic support to expose the two new attributes and to validate their run-time update based on the "limits" of the aforementioned RDM schema.

---
 include/linux/sched.h |   7 ++
 init/Kconfig          |  17 +++++
 kernel/sched/core.c   | 180 ++++++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h  |  22 ++++++
 4 files changed, 226 insertions(+)
include/linux/sched.h +7 -0
index c28b182c9833..265ac0898f9e 100644
@@ -241,6 +241,13 @@ struct vtime {
 	u64			gtime;
 };
 
+enum uclamp_id {
+	UCLAMP_MIN = 0, /* Minimum utilization */
+	UCLAMP_MAX,     /* Maximum utilization */
+	/* Utilization clamping constraints count */
+	UCLAMP_CNT
+};
+
 struct sched_info {
 #ifdef CONFIG_SCHED_INFO
 	/* Cumulative counters: */
init/Kconfig +17 -0
index 8514b25db21c..db736529f08b 100644
@@ -754,6 +754,23 @@ config RT_GROUP_SCHED
 
 endif #CGROUP_SCHED
 
+config UTIL_CLAMP
+	bool "Utilization clamping per group of tasks"
+	depends on CPU_FREQ_GOV_SCHEDUTIL
+	depends on CGROUP_SCHED
+	default n
+	help
+	  This feature enables the scheduler to track the clamped utilization
+	  of each CPU based on RUNNABLE tasks currently scheduled on that CPU.
+
+	  When this option is enabled, the user can specify a min and max
+	  CPU bandwidth which is allowed for each single task in a group.
+	  The max bandwidth allows to clamp the maximum frequency a task
+	  can use, while the min bandwidth allows to define a minimum
+	  frequency a task will alwasy use.
+
+	  If in doubt, say N.
+
 config CGROUP_PIDS
 	bool "PIDs controller"
 	help
kernel/sched/core.c +180 -0

210 lines not on this page · raw message

kernel/sched/sched.h +22 -0
index eeef1a3086d1..982340b8870b 100644
@@ -330,6 +330,10 @@ struct task_group {
 #endif
 
 	struct cfs_bandwidth cfs_bandwidth;
+
+#ifdef CONFIG_UTIL_CLAMP
+	unsigned int uclamp[UCLAMP_CNT];
+#endif
 };
 
 #ifdef CONFIG_FAIR_GROUP_SCHED
@@ -365,6 +369,24 @@ static inline int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
 
 extern int tg_nop(struct task_group *tg, void *data);
 
+#ifdef CONFIG_UTIL_CLAMP
+/**
+ * uclamp_none: default value for a clamp
+ *
+ * This returns the default value for each clamp
+ * - 0 for a min utilization clamp
+ * - SCHED_CAPACITY_SCALE for a max utilization clamp
+ *
+ * Return: the default value for a given utilization clamp
+ */
+static inline unsigned int uclamp_none(int clamp_id)
+{
+	if (clamp_id == UCLAMP_MIN)
+		return 0;
+	return SCHED_CAPACITY_SCALE;
+}
+#endif /* CONFIG_UTIL_CLAMP */
+
 extern void free_fair_sched_group(struct task_group *tg);
 extern int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent);
 extern void online_fair_sched_group(struct task_group *tg);
Signature · 1 line
2.14.1
#2 lore raw

Re: [RFCv4 1/6] sched/core: add utilization clamping to CPU controller

Hello,

No idea whether this makes sense overall. I'll just comment on the cgroup interface part.

Quoted 10 lines · Patrick Bellasi

This patch extends the CPU controller by adding a couple of new attributes, util_min and util_max, which can be used to enforce frequency boosting and capping. Specifically:

- util_min: defines the minimum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run at least at a minimum frequency which
corresponds to the min_util utilization

Quoted 5 lines

- util_max: defines the maximum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run up to a maximum frequency which
corresponds to the max_util utilization

I'm not sure min/max are the right names here. min/low/high/max are used to designate guarantees and limits on resources and the above is more restricting the range of an attribute. I'll think more about what'd be better names here.

Quoted 4 lines

These attributes:
a) are tunable at all hierarchy levels, i.e. at root group level too, thus allowing to defined minimum and maximum frequency constraints for all otherwise non-classified tasks (e.g. autogroups)

The problem with doing the above is two-fold.

1. The feature becomes inaccessible without cgroup even though it doesn't have much to do with cgroup at system level.

2. For the above and other historical reasons, most other features have a separate way to configure at the system level.

I think it'd be better to keep the root level control outside cgorup.

Quoted 2 lines

b) allow to create subgroups of tasks which are not violating the utilization constraints defined by the parent group.

The problem with doing the above is that it ties the configs of a cgroup with its ancestors and that gets weird across delegation boundaries. Other resource knobs don't behave this way - a descendant cgroup can have any memory.low/high/max values and an ancestor changing config doesn't destory its descendants' configs. Please follow the same convention.

Quoted 4 lines

Tasks on a subgroup can only be more boosted and/or capped, which is matching with the "limits" schema proposed by the "Resource Distribution Model (RDM)" suggested by the CGroups v2 documentation:
Documentation/cgroup-v2.txt

So, the guarantee side (min / low) shouldn't allow the descendants to have more. ie. if memory.low is 512M at the parent, its children can never have more than 512M of low protection. Given that "boosting" means more CPU consumption, I think it'd make more sense to follow such semantics - ie. a descendant cannot have higher boosting than the lowest of its ancestors.

Thanks.

Signature · 1 line
tejun
#3 lore raw

Re: [RFCv4 1/6] sched/core: add utilization clamping to CPU controller

Quoted 1 line · Tejun Heo

Hello,

Hi Teo,

Quoted 2 lines

No idea whether this makes sense overall. I'll just comment on the cgroup interface part.

Thanks for the feedback, some comments follow inline...

Quoted 17 lines · Patrick Bellasi
Quoted 10 lines

This patch extends the CPU controller by adding a couple of new attributes, util_min and util_max, which can be used to enforce frequency boosting and capping. Specifically:

- util_min: defines the minimum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run at least at a minimum frequency which
corresponds to the min_util utilization

Quoted 5 lines

- util_max: defines the maximum CPU utilization which should be considered, e.g. when schedutil selects the frequency for a CPU while a task in this group is RUNNABLE.
i.e. the task will run up to a maximum frequency which
corresponds to the max_util utilization

Quoted 4 lines

I'm not sure min/max are the right names here. min/low/high/max are used to designate guarantees and limits on resources and the above is more restricting the range of an attribute. I'll think more about what'd be better names here.

You right, these are used mainly for range restrictions, but still:
- utilization is the measure of a resource, i.e. the CPU bandwidth
- to a certain extend we are still using them to designate a guarantee i.e. util_min guarantee that tasks will not run below a minimum frequency, while util_max guarantee that a task will never run (when alone on a CPU) above a certain frequency.

If this is still considered a too wake definition of guarantees, what about something like util_{lower,upper}_bound?

Quoted 9 lines
Quoted 4 lines

These attributes:
a) are tunable at all hierarchy levels, i.e. at root group level too, thus allowing to defined minimum and maximum frequency constraints for all otherwise non-classified tasks (e.g. autogroups)

The problem with doing the above is two-fold.

1. The feature becomes inaccessible without cgroup even though it doesn't have much to do with cgroup at system level.

As I commented in the cover letter, we currently use CGroups as the only interface just because so fare we identified sensible use-cases where cgroups are required.

Android needs to classify tasks depending on their role in the system to allocate them different resources depending on the run-time scenario. Thus, cgroups is just the most natural interface to extend to get the frequency boosting/capping support.

Not to speak about the, at least incomplete, cpu bandwidth controller interface, which is currently defined based just on "elapsed time" without accounting for the actual amount of computation performed on systems where the frequency can be changed dynamically.

Nevertheless, the internal implementation allows for a different (primary) interface whenever that should be required.

Quoted 4 lines

2. For the above and other historical reasons, most other features have a separate way to configure at the system level.

I think it'd be better to keep the root level control outside cgorup.

For this specific feature, the system level configuration using the root control group allows to define the "default" behavior for tasks not otherwise classified.

Considering also my comment on point 1 above, having a different API for the system tuning would make the implementation more complex without real benefits.

Quoted 9 lines
Quoted 2 lines

b) allow to create subgroups of tasks which are not violating the utilization constraints defined by the parent group.

The problem with doing the above is that it ties the configs of a cgroup with its ancestors and that gets weird across delegation boundaries. Other resource knobs don't behave this way - a descendant cgroup can have any memory.low/high/max values and an ancestor changing config doesn't destory its descendants' configs. Please follow the same convention.

Also in this implementation an ancestor config change cannot destroy its descendants' config.

For example, if we have:

group1/util_min = 10
group1/child1/util_min = 20

we cannot set:

group1/util_min = 30

Right now we just fails, since this will produce an inversion in the parent/child constraints relationships (see below).

The right operations would be:

group1/child1/util_min = 30, or more, and only after:
group1/util_min = 30

Quoted 8 lines
Quoted 4 lines

Tasks on a subgroup can only be more boosted and/or capped, which is matching with the "limits" schema proposed by the "Resource Distribution Model (RDM)" suggested by the CGroups v2 documentation:
Documentation/cgroup-v2.txt

So, the guarantee side (min / low) shouldn't allow the descendants to have more. ie. if memory.low is 512M at the parent, its children can never have more than 512M of low protection.

Does that not means, more generically, that children are not allowed to have "more relaxed" constraints then their parents?
IOW children can only be more constrained.

Here we are applying exactly the same rule, what change is just the definition of "more relaxed" constraint.

For example, for frequency boosting: if a parent is 10% boosted, then its children are not allowed to have a lower boost value because this will relax their parent's boost constraint (see below).

Quoted 6 lines

Given that "boosting"
means more CPU consumption, I think it'd make more sense to follow such semantics - ie. a descendant cannot have higher boosting than the lowest of its ancestors.

From a functional standpoint, what we want to avoid is that by

lowering the boost value of children we can (indirectly) affect the "performance" of their ancestors.

That's why a more restrictive constraint implies that we allow only higher boost value than the highest of its ancestors.

For frequency capping instead the logic is the opposite. In that case the optimization goal is to constraint the maximum frequency, for example to save energy. Thus, children are allowed only to set lower util_max values.

Quoted 4 lines

Thanks.

--
tejun

Cheers Patrick

Signature · 3 lines
#include <best/regards.h>

Patrick Bellasi
#4 lore raw

RFC v4 2/6 sched/core: map cpu's task groups to clamp groups

In reply to Patrick Bellasi

To properly support per-task utilization clamping, each CPU needs to know which clamp values are required by tasks currently RUNNABLE on that CPU. However, multiple task groups can define the same clamp value for a given clamp index (i.e. util_{min,max}).
Thus, a mechanism is required to map clamp values to a properly defined data structure which is suitable for fast and efficient aggregation of clamp values coming from tasks belonging to different task_groups.

Such a data structure can be an array of reference counters, where each slot is used to account how many tasks requiring a certain clamp value are currently enqueued. Thus each clamp value can be mapped into a "clamp index" which identifies the position within the reference counters array.

                                 :
                                 :
             SLOW PATH           :             FAST PATH
         task_group::write       :     sched/core::enqueue/dequeue
                                 :         cpufreq_schedutil
                                 :
  +----------------+    +--------------------+     +-------------------+
  |   TASK GROUP   |    |     CLAMP GROUP    |     |    CPU CLAMPS     |
  +----------------+    +--------------------+     +-------------------+
  |                |    |   clamp_{min,max}  |     |  clamp_{min,max}  |
  | util_{min,max} |    |      tg_count      |     |    tasks count    |
  +----------------+    +--------------------+     +-------------------+
                                 :
           +------------------>  :  +------------------->
  map(clamp_value, clamp_group)  :  ref_count(clamp_group)
                                 :
                                 :
                                 :

This patch introduces the support to map task groups on "clamp groups". Specifically it introduces the required functions to translate a clamp value into a clamp group index.

Only a limited number of (different) clamp values are supported since:
1. there are usually only few classes of workloads for which it makes sense to boost/cap to different frequencies
e.g. background vs foreground, interactive vs low-priority
2. it allows a simpler and more memory/time efficient tracking of the per-CPU clamp values in the fast path

The number of possible different clamp values is currently defined at compile time. It's worth to notice that this does not impose a limitation on the number of task groups that can be generated. Indeed, each new task group always maps to the clamp groups of its parent.
Instead, changing the clamp value for a TG can result into a -ENOSPC error in case this will exceed the number of maximum different clamp values supported.

---
 init/Kconfig         |  19 +++
 kernel/sched/core.c  | 348 +++++++++++++++++++++++++++++++++++++++++++++++----
 kernel/sched/sched.h |  21 +++-
 3 files changed, 363 insertions(+), 25 deletions(-)
init/Kconfig +19 -0
index db736529f08b..5f0c246f2a3a 100644
@@ -771,6 +771,25 @@ config UTIL_CLAMP
 
 	  If in doubt, say N.
 
+config UCLAMP_GROUPS_COUNT
+	int "Number of utilization clamp values supported"
+	range 1 127
+	depends on UTIL_CLAMP
+	default 3
+	help
+	  This defines the maximum number of different utilization clamp
+	  values which can be concurrently enforced for each utilization
+	  clamp index (i.e. minimum and maximum).
+
+	  Only a limited number of clamp values are supported because:
+	    1. there are usually only few classes of workloads for which is
+	       makese sense to boost/cap for different frequencies
+	       e.g. background vs foreground, interactive vs low-priority
+	    2. it allows a simpler and more memory/time efficient tracking of
+	       the per-CPU clamp values.
+
+	  If in doubt, use the default value.
+
 config CGROUP_PIDS
 	bool "PIDs controller"
 	help
kernel/sched/core.c +324 -24

451 lines not on this page · raw message

kernel/sched/sched.h +20 -1
index 982340b8870b..869344de0396 100644
@@ -290,6 +290,24 @@ struct cfs_bandwidth {
 #endif
 };
 
+/**
+ * Utilization's clamp group
+ *
+ * A utilization clamp group maps a "clamp value" (value), i.e.
+ * util_{min,max}, to a "clamp group index" (group_id).
+ *
+ * Thus, the same "group_id" is used by all the TG's which enforce the same
+ * clamp "value" for a given clamp index.
+ */
+struct uclamp_tg {
+	/* Utilization constraint for tasks in this group */
+	unsigned int value;
+	/* Utilization clamp group for this constraint */
+	unsigned int group_id;
+	/* No utilization clamp group assigned */
+#define UCLAMP_NONE	-1
+};
+
 /* task group related information */
 struct task_group {
 	struct cgroup_subsys_state css;
@@ -332,8 +350,9 @@ struct task_group {
 	struct cfs_bandwidth cfs_bandwidth;
 
 #ifdef CONFIG_UTIL_CLAMP
-	unsigned int uclamp[UCLAMP_CNT];
+	struct uclamp_tg uclamp[UCLAMP_CNT];
 #endif
+
 };
 
 #ifdef CONFIG_FAIR_GROUP_SCHED
Signature · 1 line
2.14.1
#5 lore raw

RFC v4 3/6 sched/core: reference count active tasks's clamp groups

In reply to Patrick Bellasi

When tasks are enqueued/dequeued on/from a CPU, the set of clamp groups active on that CPU can change. Indeed, the clamp value mapped by a clamp group applies to a CPU only when there is at least one task active in that clamp group.
Since each clamp group enforces a different utilization clamp value, once the set of these groups changes it can be required to re-compute what is the new "aggregated" clamp value to apply for that CPU.

Clamp values are always MAX aggregated for both util_min and util_max. This is to ensure that no tasks can affect the performances of other co-scheduled tasks which are either more boosted (i.e. with higher util_min clamp) or less capped (i.e. with higher util_max clamp).

This patch introduces the required support to properly reference count clamp groups at each task enqueue/dequeue time. The MAX aggregation of the currently active clamp groups is implemented to minimizes the number of times we need to scan the complete (unordered) clamp group array to figure out the new max value.
This operation happens only when we dequeue last task of the clamp group defining the current max clamp, and thus the CPU is either entering IDLE or going to schedule a less boosted or more clamped task.

---
 include/linux/sched.h |   5 ++
 kernel/sched/core.c   | 160 ++++++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h  |  77 ++++++++++++++++++++++++
 3 files changed, 242 insertions(+)
include/linux/sched.h +5 -0
index 265ac0898f9e..5cf0ee6a1aee 100644
@@ -574,6 +574,11 @@ struct task_struct {
 #endif
 	struct sched_dl_entity		dl;
 
+#ifdef CONFIG_UTIL_CLAMP
+	/* Index of clamp group the task has been accounted into */
+	int				uclamp_group_id[UCLAMP_CNT];
+#endif
+
 #ifdef CONFIG_PREEMPT_NOTIFIERS
 	/* List of struct preempt_notifier: */
 	struct hlist_head		preempt_notifiers;
kernel/sched/core.c +160 -0

221 lines not on this page · raw message

kernel/sched/sched.h +77 -0

95 lines not on this page · raw message

Signature · 1 line
2.14.1
#6 lore raw

RFC v4 4/6 sched/core: sync task_group's with CPU's clamp groups

In reply to Patrick Bellasi

The util_{min,max} clamp values for a task group are usually updated from a user-space process (slow-path) but they require a synchronization with the scheduler's (fast-path) maintained clamp group reference couters.

Indeed, each time the clamp value of a task group is changed, the old and new clamp groups have to be updated for each CPU containing a RUNNABLE task belonging to this tasks group. Non RUNNABLE tasks are not updated since they will be enqueued with the proper clamp group index at their next activation.

To properly update clamp group's reference counter of runnable tasks we use the same locking schema use by __set_cpus_allowed_ptr(). This might lock the (previous) RQ of a !RUNNABLE task, but that's the price to pay to safely serialize util_{min,max} updates with RQ's enqueues, dequeues and migration operations.

---
 kernel/sched/core.c  | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h | 21 +++++++++++++++++
 2 files changed, 87 insertions(+)
kernel/sched/core.c +66 -0
index ba31bb4e14c7..e4ce25dbad6f 100644
@@ -754,6 +754,12 @@ static void set_load_weight(struct task_struct *p)
 #ifdef CONFIG_UTIL_CLAMP
 /**
  * uclamp_mutex: serialize updates of TG's utilization clamp values
+ *
+ * A task groups's utilization clamp value update is usually triggered from a
+ * user-space process (slow-path) but it requires a synchronization with the
+ * scheduler's (fast-path) enqueue/dequeue operations.
+ * While the fast-path synchronization is protected by RQs spinlock, this
+ * mutex ensure that we sequentially serve user-space requests.
  */
 static DEFINE_MUTEX(uclamp_mutex);
 
@@ -1022,6 +1028,52 @@ static inline void uclamp_cpu_put(struct task_struct *p, int cpu, int clamp_id)
 		uclamp_cpu_update(cpu, clamp_id);
 }
 
+/**
+ * uclamp_task_update_active: update the clamp group of a RUNNABLE task
+ * @p: the task which clamp groups must be updated
+ * @clamp_id: the clamp index to consider
+ * @group_id: the clamp group to update
+ *
+ * Each time the clamp value of a task group is changed, the old and new clamp
+ * groups have to be updated for each CPU containing a RUNNABLE task belonging
+ * to this tasks group. Sleeping tasks are not updated since they will be
+ * enqueued with the proper clamp group index at their next activation.
+ */
+static inline void
+uclamp_task_update_active(struct task_struct *p, int clamp_id, int group_id)
+{
+	struct rq_flags rf;
+	struct rq *rq;
+
+	/*
+	 * Lock the task and the CPU where the task is (or was) queued.
+	 *
+	 * We might lock the (previous) RQ of a !RUNNABLE task, but that's the
+	 * price to pay to safely serialize util_{min,max} updates with
+	 * enqueues, dequeues and migration operations.
+	 * This is the same locking schema used by __set_cpus_allowed_ptr().
+	 */
+	rq = task_rq_lock(p, &rf);
+
+	/*
+	 * The setting of the clamp group is serialized by task_rq_lock().
+	 * Thus, if the task's task_struct is not referencing a valid group
+	 * index, then that task is not yet RUNNABLE or it's going to be
+	 * enqueued with the proper clamp group value.
+	 */
+	if (!uclamp_task_active(p))
+		goto done;
+
+	/* Release p's currently referenced clamp group */
+	uclamp_cpu_put(p, task_cpu(p), clamp_id);
+
+	/* Get p's new clamp group */
+	uclamp_cpu_get(p, task_cpu(p), clamp_id);
+
+done:
+	task_rq_unlock(rq, p, &rf);
+}
+
 /**
  * uclamp_group_put: decrease the reference count for a clamp group
  * @clamp_id: the clamp index which was affected by a task group
@@ -1070,6 +1122,8 @@ static inline int uclamp_group_get(struct cgroup_subsys_state *css,
 	struct uclamp_map *uc_map = &uclamp_maps[clamp_id][0];
 	int prev_group_id = uc_tg->group_id;
 	int next_group_id = UCLAMP_NONE;
+	struct css_task_iter it;
+	struct task_struct *p;
 	unsigned long flags;
 
 	/* Lookup for a usable utilization clamp group */
@@ -1091,6 +1145,18 @@ static inline int uclamp_group_get(struct cgroup_subsys_state *css,
 	uc_map[next_group_id].tg_count += 1;
 	raw_spin_unlock_irqrestore(&uc_map[next_group_id].tg_lock, flags);
 
+	/* Newly created TG don't have tasks assigned */
+	if (!css)
+		goto release;
+
+	/* Update clamp groups for RUNNABLE tasks in this TG */
+	css_task_iter_start(css, &it);
+	while ((p = css_task_iter_next(&it)))
+		uclamp_task_update_active(p, clamp_id, next_group_id);
+	css_task_iter_end(&it);
+
+release:
+
 	/* Release the previous clamp group */
 	uclamp_group_put(clamp_id, prev_group_id);
 
kernel/sched/sched.h +21 -0
index b0f17c19c0f6..164a8ac152b3 100644
@@ -462,6 +462,27 @@ static inline bool uclamp_task_affects(struct task_struct *p, int clamp_id)
 	return (task_group_id != UCLAMP_NONE);
 }
 
+/**
+ * uclamp_task_active: check if a task is currently clamping a CPU
+ * @p: the task to check
+ *
+ * A task affects the utilization clamp of a CPU if it references a valid
+ * clamp group index for at least one clamp index.
+ *
+ * Return: true if p is currently clamping the utilization of its CPU.
+ */
+static inline bool uclamp_task_active(struct task_struct *p)
+{
+	int clamp_id;
+
+	for (clamp_id = 0; clamp_id < UCLAMP_CNT; ++clamp_id) {
+		if (uclamp_task_affects(p, clamp_id))
+			return true;
+	}
+
+	return false;
+}
+
 /**
  * uclamp_group_active: check if a clamp group is active on a CPU
  * @uc_cpu: the array of clamp groups for a CPU
Signature · 1 line
2.14.1
#7 lore raw

RFC v4 5/6 cpufreq: schedutil: add util clamp for FAIR tasks

In reply to Patrick Bellasi

Each time a frequency update is required via schedutil, we must grant the util_{min,max} constraints enforced in the current CPU by its set of currently RUNNABLE tasks.

This patch adds the required support to clamp the utilization generated by FAIR tasks within the boundaries defined by their aggregated utilization clamp constraints.
The clamped utilization is then used to select the frequency thus allowing, for example, to:
- boost tasks which are directly affecting the user experience by running them at least at a minimum "required" frequency
- cap low priority tasks not directly affecting the user experience by running them only up to a maximum "allowed" frequency

The default values for boosting and capping are defined to be:
- util_min: 0
- util_max: SCHED_CAPACITY_SCALE
which means that by default no boosting/capping is enforced.

---
 kernel/sched/cpufreq_schedutil.c | 33 ++++++++++++++++++++++
 kernel/sched/sched.h             | 60 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 93 insertions(+)
kernel/sched/cpufreq_schedutil.c +33 -0
index 29a397067ffa..f67c26bbade4 100644
@@ -231,6 +231,7 @@ static void sugov_update_single(struct update_util_data *hook, u64 time,
 	} else {
 		sugov_get_util(&util, &max);
 		sugov_iowait_boost(sg_cpu, &util, &max);
+		util = uclamp_util(smp_processor_id(), util);
 		next_f = get_next_freq(sg_policy, util, max);
 		/*
 		 * Do not reduce the frequency if the CPU has not been idle
@@ -246,9 +247,18 @@ static unsigned int sugov_next_freq_shared(struct sugov_cpu *sg_cpu, u64 time)
 {
 	struct sugov_policy *sg_policy = sg_cpu->sg_policy;
 	struct cpufreq_policy *policy = sg_policy->policy;
+	unsigned long max_util, min_util;
 	unsigned long util = 0, max = 1;
 	unsigned int j;
 
+	/* Initialize clamp values based on caller CPU constraints */
+	if (uclamp_enabled) {
+		int cpu = smp_processor_id();
+
+		max_util = uclamp_value(cpu, UCLAMP_MAX);
+		min_util = uclamp_value(cpu, UCLAMP_MIN);
+	}
+
 	for_each_cpu(j, policy->cpus) {
 		struct sugov_cpu *j_sg_cpu = &per_cpu(sugov_cpu, j);
 		unsigned long j_util, j_max;
@@ -277,8 +287,31 @@ static unsigned int sugov_next_freq_shared(struct sugov_cpu *sg_cpu, u64 time)
 		}
 
 		sugov_iowait_boost(j_sg_cpu, &util, &max);
+
+		/*
+		 * Update clamping range based on j-CPUs constraints, but only
+		 * if active. Idle CPUs do not enforce constraints in a shared
+		 * frequency domain.
+		 */
+		if (uclamp_enabled && !idle_cpu(j)) {
+			unsigned long j_max_util, j_min_util;
+
+			j_max_util = uclamp_value(j, UCLAMP_MAX);
+			j_min_util = uclamp_value(j, UCLAMP_MIN);
+
+			/*
+			 * Clamp values are MAX aggregated among all the
+			 * different CPUs in the shared frequency domain.
+			 */
+			max_util = max(max_util, j_max_util);
+			min_util = max(min_util, j_min_util);
+		}
 	}
 
+	/* Clamp utilization based on aggregated uclamp constraints */
+	if (uclamp_enabled)
+		util = clamp(util, min_util, max_util);
+
 	return get_next_freq(sg_policy, util, max);
 }
 
kernel/sched/sched.h +60 -0

66 lines not on this page · raw message

Signature · 1 line
2.14.1
#8 lore raw

RFC v4 6/6 cpufreq: schedutil: add util clamp for RT/DL tasks

In reply to Patrick Bellasi

Currently schedutil enforces a maximum frequency when RT/DL tasks are RUNNABLE. Such a mandatory policy can be made more tunable from userspace thus allowing for example to define a max frequency which is still reasonable for the execution of a specific RT/DL workload. This will contribute to make the RT class more friendly for power/energy sensitive use-cases.

This patch extends the usage of util_{min,max} to the RT/DL classes. Whenever a task in these classes is RUNNABLE, the util required is defined by the constraints of the CPU control group the task belongs to.

---
 kernel/sched/cpufreq_schedutil.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
kernel/sched/cpufreq_schedutil.c +12 -4
index f67c26bbade4..feca60c107bc 100644
@@ -227,7 +227,10 @@ static void sugov_update_single(struct update_util_data *hook, u64 time,
 	busy = sugov_cpu_is_busy(sg_cpu);
 
 	if (flags & SCHED_CPUFREQ_RT_DL) {
-		next_f = policy->cpuinfo.max_freq;
+		util = uclamp_util(smp_processor_id(), SCHED_CAPACITY_SCALE);
+		next_f = (uclamp_enabled && util < SCHED_CAPACITY_SCALE)
+			? get_next_freq(sg_policy, util, policy->cpuinfo.max_freq)
+			: policy->cpuinfo.max_freq;
 	} else {
 		sugov_get_util(&util, &max);
 		sugov_iowait_boost(sg_cpu, &util, &max);
@@ -276,10 +279,15 @@ static unsigned int sugov_next_freq_shared(struct sugov_cpu *sg_cpu, u64 time)
 			j_sg_cpu->iowait_boost = 0;
 			continue;
 		}
-		if (j_sg_cpu->flags & SCHED_CPUFREQ_RT_DL)
-			return policy->cpuinfo.max_freq;
 
-		j_util = j_sg_cpu->util;
+		if (j_sg_cpu->flags & SCHED_CPUFREQ_RT_DL) {
+			if (!uclamp_enabled)
+				return policy->cpuinfo.max_freq;
+			j_util = uclamp_util(j, SCHED_CAPACITY_SCALE);
+		} else {
+			j_util = j_sg_cpu->util;
+		}
+
 		j_max = j_sg_cpu->max;
 		if (j_util * max > j_max * util) {
 			util = j_util;
Signature · 1 line
2.14.1