| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/11/13 14:16 | flow | patch-triage |
11mArgs:null Results: {
"EnableConfigs": [
"CFS_BANDWIDTH",
"CGROUP_SCHED",
"FAIR_GROUP_SCHED",
"SCHED_CLASS_EXT"
],
"FocusSymbols": [
"cfs_bandwidth_set_runtime",
"cfs_bandwidth_get_runtime",
"cfs_bandwidth_refill_idle_periods",
"cfs_bandwidth_charge_task",
"cfs_bandwidth_return_task",
"cfs_bandwidth_task_runtime",
"scx_group_set_runtime",
"scx_bpf_task_cpu_max_runtime",
"cpu_runtime_write_u64"
],
"KMSANReasoning": "The patch series updates CFS bandwidth control (relaxing the burst limit cap to allow bursts exceeding quota and accumulating unused runtime during idle periods) and introduces the `cpu.max.runtime` cgroup v2 interface along with BPF sched_ext integration (`SCX_OPS_CHARGE_CPU_MAX`, `cgroup_set_runtime`, and `scx_bpf_task_cpu_max_runtime`).\n\nKMSAN vs KASAN/LOCKDEP applicability:\n1. No uninitialized memory or info-leak risk:\n - The newly introduced cgroup file `cpu.max.runtime` interacts with user space solely via scalar `u64` read/write handlers (`cpu_runtime_read_u64` and `cpu_runtime_write_u64`), which seq_printf/parse textual numbers without copying raw kernel memory, buffers, or structs with padding to user space.\n - The new field `debt` in `struct cfs_bandwidth` is embedded in `struct task_group`, which is allocated using `__GFP_ZERO` (`kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO)`), ensuring zero-initialization.\n - All stack variables added in the new/modified functions in `kernel/sched/fair.c`, `kernel/sched/core.c`, and `kernel/sched/ext/ext.c` (such as `throttled`, `snap`, `held`, `idle_periods`, `floor`, etc.) are explicitly initialized before any read.\n - The sched_ext BPF kfunc returns a scalar `u64` value, and the struct_ops callback passes standard pointers and scalar values.\n\n2. Bug surface:\n - The risks in this changeset primarily involve synchronization/locking ordering (`tg_bandwidth_mutex`, `cfs_b-\u003elock`, runqueue locks), arithmetic/underflow/overflow in bandwidth and debt tracking, or task reference lifecycles. These classes of bugs are already addressed by LOCKDEP, UBSAN, and KASAN.\n\nTherefore, dedicated KMSAN fuzzing is not warranted.",
"NeedsKMSAN": false,
"Reasoning": "The patch introduces the cpu.max.runtime cgroup interface to allow reading and setting accumulated CPU runtime, changes burst bandwidth constraints, and integrates CFS bandwidth tracking with the sched_ext extensible scheduler class (including quota sharing, runtime debt tracking, and BPF kfuncs). These modifications affect core scheduler logic and cgroup control interfaces reachable from userspace in standard virtualized environments.",
"WorthFuzzing": true
} |
| 1/1 | 2026/11/13 14:16 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit d396475ecb337400ea2d7b99b7b993e3680b5228\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Fri Nov 13 14:16:07 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst\nindex 9e3c67b02ae2e1..db9fa6e6dbd49e 100644\n--- a/Documentation/admin-guide/cgroup-v2.rst\n+++ b/Documentation/admin-guide/cgroup-v2.rst\n@@ -1231,12 +1231,37 @@ will be referred to. All time durations are in microseconds.\n \tA read-write single value file which exists on non-root\n \tcgroups. The default is \"0\".\n \n-\tThe burst in the range [0, $MAX].\n+\tThe burst. The cgroup can accumulate the runtime it does not\n+\tuse, up to $MAX + cpu.max.burst, also in the periods in which it\n+\tdoes not run. The burst may exceed $MAX, as long as $MAX +\n+\tcpu.max.burst is at most 2^44 - 1 (about 203 days).\n \n \tThis file affects only processes under the fair-class scheduler and a BPF\n \tscheduler with the ``cgroup_set_bandwidth`` callback depending on what\n \tthe callback actually does.\n \n+ cpu.max.runtime\n+\tA read-write single value file which exists on non-root\n+\tcgroups if the kernel is built with CONFIG_CFS_BANDWIDTH.\n+\n+\tThe runtime the cgroup has accumulated and not used yet, in\n+\tmicroseconds. Each period refills it by $MAX, up to $MAX +\n+\tcpu.max.burst, whether the cgroup runs in it or not. A read\n+\treturns at most $MAX + cpu.max.burst. A write sets it, up to\n+\t$MAX + cpu.max.burst, and lets a cgroup that ran out of runtime\n+\trun again at once. A write fails with EINVAL while $MAX is\n+\t\"max\".\n+\n+\tThe runtime does not include what the cgroup's CPUs already took\n+\tfrom it, at most a slice each (sched_cfs_bandwidth_slice_us).\n+\tA write leaves that with the CPUs.\n+\n+\tThis file affects only processes under the fair-class scheduler and a BPF\n+\tscheduler with the ``cgroup_set_runtime`` callback depending on what\n+\tthe callback actually does. A BPF scheduler with the\n+\t``SCX_OPS_CHARGE_CPU_MAX`` flag draws what its processes run from\n+\tthe same runtime, so the cgroup's processes in both share it.\n+\n cpu.pressure\n \tA read-write nested-keyed file.\n \ndiff --git a/Documentation/scheduler/sched-bwc.rst b/Documentation/scheduler/sched-bwc.rst\nindex e881a945c1888e..ccf7434ca73f0a 100644\n--- a/Documentation/scheduler/sched-bwc.rst\n+++ b/Documentation/scheduler/sched-bwc.rst\n@@ -90,8 +90,8 @@ bandwidth restriction in place, such a group is described as an unconstrained\n bandwidth group. This represents the traditional work-conserving behavior for\n CFS.\n \n-Writing any (valid) positive value(s) no smaller than cpu.cfs_burst_us will\n-enact the specified bandwidth limit. The minimum quota allowed for the quota or\n+Writing any (valid) positive value(s) will enact the specified bandwidth\n+limit. The minimum quota allowed for the quota or\n period is 1ms. There is also an upper bound on the period length of 1s.\n Additional restrictions exist when bandwidth limits are used in a hierarchical\n fashion, these are explained in more detail below.\n@@ -101,9 +101,11 @@ and return the group to an unconstrained state once more.\n \n A value of 0 for cpu.cfs_burst_us indicates that the group can not accumulate\n any unused bandwidth. It makes the traditional bandwidth control behavior for\n-CFS unchanged. Writing any (valid) positive value(s) no larger than\n-cpu.cfs_quota_us into cpu.cfs_burst_us will enact the cap on unused bandwidth\n-accumulation.\n+CFS unchanged. Writing any (valid) positive value(s) into cpu.cfs_burst_us\n+will enact the cap on unused bandwidth accumulation: the group can accumulate\n+up to cpu.cfs_quota_us + cpu.cfs_burst_us, also over periods in which it does\n+not run. The burst may be larger than the quota, as long as their sum is at\n+most 2^44 - 1 microseconds (about 203 days).\n \n Any updates to a group's bandwidth specification will result in it becoming\n unthrottled if it is in a constrained state.\n@@ -243,4 +245,4 @@ Examples\n \t# echo 50000 \u003e cpu.cfs_period_us /* period = 50ms */\n \t# echo 10000 \u003e cpu.cfs_burst_us /* burst = 10ms */\n \n- Larger buffer setting (no larger than quota) allows greater burst capacity.\n+ Larger buffer setting allows greater burst capacity.\ndiff --git a/kernel/sched/core.c b/kernel/sched/core.c\nindex 175b52a7ea7938..25a4acb72106c7 100644\n--- a/kernel/sched/core.c\n+++ b/kernel/sched/core.c\n@@ -9856,6 +9856,12 @@ static int tg_set_cfs_bandwidth(struct task_group *tg,\n \t\tcfs_bandwidth_usage_inc();\n \n \tscoped_guard (raw_spinlock_irq, \u0026cfs_b-\u003elock) {\n+\t\t/*\n+\t\t * The new bandwidth applies from now on. The group keeps what\n+\t\t * it earned while idle under the old one.\n+\t\t */\n+\t\tcfs_bandwidth_refill_idle_periods(cfs_b);\n+\n \t\tcfs_b-\u003eperiod = ns_to_ktime(period);\n \t\tcfs_b-\u003equota = quota;\n \t\tcfs_b-\u003eburst = burst;\n@@ -10093,6 +10099,14 @@ static u64 cpu_period_read_u64(struct cgroup_subsys_state *css,\n \treturn period_us;\n }\n \n+/*\n+ * Held across a bandwidth or runtime write and the sched_ext callback that\n+ * follows it, so that the BPF scheduler gets the writes in the order the fair\n+ * class applied them. The callback runs after the fair class's update has\n+ * dropped cpus_read_lock() and cfs_constraints_mutex.\n+ */\n+static DEFINE_MUTEX(tg_bandwidth_mutex);\n+\n static int tg_set_bandwidth(struct task_group *tg,\n \t\t\t u64 period_us, u64 quota_us, u64 burst_us)\n {\n@@ -10131,10 +10145,11 @@ static int tg_set_bandwidth(struct task_group *tg,\n \tif (quota_us != RUNTIME_INF \u0026\u0026 quota_us \u003e max_bw_runtime_us)\n \t\treturn -EINVAL;\n \n-\tif (quota_us != RUNTIME_INF \u0026\u0026 (burst_us \u003e quota_us ||\n-\t\t\t\t\tburst_us + quota_us \u003e max_bw_runtime_us))\n+\tif (quota_us != RUNTIME_INF \u0026\u0026 burst_us \u003e max_bw_runtime_us - quota_us)\n \t\treturn -EINVAL;\n \n+\tguard(mutex)(\u0026tg_bandwidth_mutex);\n+\n #ifdef CONFIG_CFS_BANDWIDTH\n \tret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us);\n #endif /* CONFIG_CFS_BANDWIDTH */\n@@ -10193,6 +10208,40 @@ static int cpu_burst_write_u64(struct cgroup_subsys_state *css,\n \ttg_bandwidth(tg, \u0026period_us, \u0026quota_us, NULL);\n \treturn tg_set_bandwidth(tg, period_us, quota_us, burst_us);\n }\n+\n+#ifdef CONFIG_CFS_BANDWIDTH\n+static int cpu_runtime_write_u64(struct cgroup_subsys_state *css,\n+\t\t\t\t struct cftype *cftype, u64 runtime_us)\n+{\n+\tstruct task_group *tg = css_tg(css);\n+\tint ret;\n+\n+\tif (runtime_us \u003e max_bw_runtime_us)\n+\t\treturn -EINVAL;\n+\n+\t/*\n+\t * Serialize against tg_set_bandwidth(), so that the BPF scheduler gets\n+\t * the runtime checked against the current quota + burst, and this and\n+\t * cpu.max writes reach it in the order the fair class took them.\n+\t */\n+\tguard(mutex)(\u0026tg_bandwidth_mutex);\n+\n+\tret = cfs_bandwidth_set_runtime(\u0026tg-\u003ecfs_bandwidth,\n+\t\t\t\t\truntime_us * NSEC_PER_USEC);\n+\tif (!ret)\n+\t\tscx_group_set_runtime(tg, runtime_us);\n+\treturn ret;\n+}\n+\n+static u64 cpu_runtime_read_u64(struct cgroup_subsys_state *css,\n+\t\t\t\tstruct cftype *cftype)\n+{\n+\tstruct task_group *tg = css_tg(css);\n+\n+\treturn div_u64(cfs_bandwidth_get_runtime(\u0026tg-\u003ecfs_bandwidth),\n+\t\t NSEC_PER_USEC);\n+}\n+#endif /* CONFIG_CFS_BANDWIDTH */\n #endif /* CONFIG_GROUP_SCHED_BANDWIDTH */\n \n #ifdef CONFIG_RT_GROUP_SCHED\n@@ -10544,7 +10593,15 @@ static struct cftype cpu_files[] = {\n \t\t.read_u64 = cpu_burst_read_u64,\n \t\t.write_u64 = cpu_burst_write_u64,\n \t},\n+#ifdef CONFIG_CFS_BANDWIDTH\n+\t{\n+\t\t.name = \"max.runtime\",\n+\t\t.flags = CFTYPE_NOT_ON_ROOT,\n+\t\t.read_u64 = cpu_runtime_read_u64,\n+\t\t.write_u64 = cpu_runtime_write_u64,\n+\t},\n #endif /* CONFIG_CFS_BANDWIDTH */\n+#endif /* CONFIG_GROUP_SCHED_BANDWIDTH */\n #ifdef CONFIG_UCLAMP_TASK_GROUP\n \t{\n \t\t.name = \"uclamp.min\",\ndiff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c\nindex ebdf7b91f9d370..6ffc9ca2c5c9f1 100644\n--- a/kernel/sched/ext/ext.c\n+++ b/kernel/sched/ext/ext.c\n@@ -1625,6 +1625,11 @@ static void expire_task_slice(struct task_struct *p)\n \t\tscx_set_task_slice(p, 0);\n }\n \n+static bool scx_task_charges_cpu_max(const struct task_struct *p)\n+{\n+\treturn scx_task_sched(p)-\u003eops.flags \u0026 SCX_OPS_CHARGE_CPU_MAX;\n+}\n+\n static void update_curr_scx(struct rq *rq)\n {\n \tstruct task_struct *donor;\n@@ -1650,6 +1655,9 @@ static void update_curr_scx(struct rq *rq)\n \tif (unlikely(donor == scx_rescuee(rq)))\n \t\tscx_rescue_charge(rq, delta_exec);\n \n+\tif (scx_task_charges_cpu_max(donor))\n+\t\tcfs_bandwidth_charge_task(rq, donor, delta_exec);\n+\n \tdl_server_update(\u0026rq-\u003eext_server, delta_exec);\n }\n \n@@ -2605,6 +2613,13 @@ static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_\n \n \tops_dequeue(rq, p, deq_flags);\n \n+\t/* charge what @p ran, then return what @rq holds for its cgroups */\n+\tif (scx_task_charges_cpu_max(p)) {\n+\t\tif (task_current_donor(rq, p))\n+\t\t\tupdate_curr_scx(rq);\n+\t\tcfs_bandwidth_return_task(rq, p);\n+\t}\n+\n \t/*\n \t * A current scheduling context which is going off @rq first gets\n \t * dequeued and then stops running. As we want running \u003c-\u003e stopping\n@@ -5817,6 +5832,19 @@ void scx_group_set_bandwidth(struct task_group *tg,\n \n \tpercpu_up_read(\u0026scx_cgroup_ops_rwsem);\n }\n+\n+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us)\n+{\n+\tstruct scx_sched *sch;\n+\n+\tpercpu_down_read(\u0026scx_cgroup_ops_rwsem);\n+\tsch = scx_tg_knob_sched(tg);\n+\n+\tif (scx_cgroup_enabled \u0026\u0026 sch \u0026\u0026 SCX_HAS_OP(sch, cgroup_set_runtime))\n+\t\tSCX_CALL_OP(sch, cgroup_set_runtime, NULL, tg_cgrp(tg), runtime_us);\n+\n+\tpercpu_up_read(\u0026scx_cgroup_ops_rwsem);\n+}\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n \n #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)\n@@ -9230,6 +9258,7 @@ static int bpf_scx_check_member(const struct btf_type *t,\n \tcase offsetof(struct sched_ext_ops, cgroup_exit):\n \tcase offsetof(struct sched_ext_ops, cgroup_prep_move):\n \tcase offsetof(struct sched_ext_ops, cgroup_set_bandwidth):\n+\tcase offsetof(struct sched_ext_ops, cgroup_set_runtime):\n #endif\n \tcase offsetof(struct sched_ext_ops, cpu_online):\n \tcase offsetof(struct sched_ext_ops, cpu_offline):\n@@ -9392,6 +9421,7 @@ static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgro\n static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}\n static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}\n static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}\n+static void sched_ext_ops__cgroup_set_runtime(struct cgroup *cgrp, u64 runtime_us) {}\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }\n static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}\n@@ -9434,6 +9464,7 @@ static struct sched_ext_ops __bpf_ops_sched_ext_ops = {\n \t.cgroup_set_weight\t= sched_ext_ops__cgroup_set_weight,\n \t.cgroup_set_bandwidth\t= sched_ext_ops__cgroup_set_bandwidth,\n \t.cgroup_set_idle\t= sched_ext_ops__cgroup_set_idle,\n+\t.cgroup_set_runtime\t= sched_ext_ops__cgroup_set_runtime,\n #endif\n \t.sub_attach\t\t= sched_ext_ops__sub_attach,\n \t.sub_detach\t\t= sched_ext_ops__sub_detach,\n@@ -9502,6 +9533,7 @@ static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {\n \t.cpuctl_set_weight\t= sched_ext_ops__cgroup_set_weight,\n \t.cpuctl_set_bandwidth\t= sched_ext_ops__cgroup_set_bandwidth,\n \t.cpuctl_set_idle\t= sched_ext_ops__cgroup_set_idle,\n+\t.cpuctl_set_runtime\t= sched_ext_ops__cgroup_set_runtime,\n #endif\n \t.sub_attach\t\t= sched_ext_ops__sub_attach,\n \t.sub_detach\t\t= sched_ext_ops__sub_detach,\n@@ -11776,6 +11808,24 @@ __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)\n \treturn task_cpu(p);\n }\n \n+/**\n+ * scx_bpf_task_cpu_max_runtime - Runtime a task has left under cpu.max\n+ * @p: task of interest\n+ *\n+ * Return the runtime in nsecs that @p's cgroup and its ancestors have left\n+ * under their cpu.max quotas for @p on its current CPU, the least over those\n+ * with a quota: the cgroup's cpu.max.runtime plus what the CPU holds for\n+ * the cgroup, less what it owes. U64_MAX if none limits it. Read without\n+ * locks.\n+ *\n+ * With %SCX_OPS_CHARGE_CPU_MAX, the scheduler should run @p only while this\n+ * returns more than 0. The runtime grows when a period refills it.\n+ */\n+__bpf_kfunc u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p)\n+{\n+\treturn cfs_bandwidth_task_runtime(p);\n+}\n+\n /**\n * scx_bpf_task_cid - cid a task is currently associated with\n * @p: task of interest\n@@ -12102,6 +12152,7 @@ BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)\n BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)\n BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)\n BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)\n+BTF_ID_FLAGS(func, scx_bpf_task_cpu_max_runtime, KF_RCU)\n BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)\n BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)\n BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)\n@@ -12226,6 +12277,7 @@ static const u32 scx_kf_allow_flags[] = {\n \t[SCX_OP_IDX(cgroup_set_weight)]\t= SCX_KF_ALLOW_UNLOCKED,\n \t[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,\n \t[SCX_OP_IDX(cgroup_set_idle)]\t= SCX_KF_ALLOW_UNLOCKED,\n+\t[SCX_OP_IDX(cgroup_set_runtime)] = SCX_KF_ALLOW_UNLOCKED,\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n \t[SCX_OP_IDX(sub_attach)]\t= SCX_KF_ALLOW_UNLOCKED,\n \t[SCX_OP_IDX(sub_detach)]\t= SCX_KF_ALLOW_UNLOCKED,\n@@ -12395,6 +12447,7 @@ static int __init scx_init(void)\n \tCID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight);\n \tCID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth);\n \tCID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle);\n+\tCID_OFFSET_MATCH(cgroup_set_runtime, cpuctl_set_runtime);\n #endif\n \t/* @priv tail must align since both share the same data block */\n \tCID_OFFSET_MATCH(priv, priv);\ndiff --git a/kernel/sched/ext/ext.h b/kernel/sched/ext/ext.h\nindex d32bc01071b01a..6d1ce582bf7240 100644\n--- a/kernel/sched/ext/ext.h\n+++ b/kernel/sched/ext/ext.h\n@@ -94,6 +94,7 @@ void scx_cgroup_cancel_attach(struct cgroup_taskset *tset);\n void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight);\n void scx_group_set_idle(struct task_group *tg, bool idle);\n void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us);\n+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us);\n #else\t/* CONFIG_EXT_GROUP_SCHED */\n static inline void scx_tg_init(struct task_group *tg) {}\n static inline int scx_tg_online(struct task_group *tg) { return 0; }\n@@ -104,5 +105,6 @@ static inline void scx_cgroup_cancel_attach(struct cgroup_taskset *tset) {}\n static inline void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight) {}\n static inline void scx_group_set_idle(struct task_group *tg, bool idle) {}\n static inline void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us) {}\n+static inline void scx_group_set_runtime(struct task_group *tg, u64 runtime_us) {}\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n #endif\t/* CONFIG_CGROUP_SCHED */\ndiff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h\nindex ff0a3d508533f0..e8c0b573d0a434 100644\n--- a/kernel/sched/ext/internal.h\n+++ b/kernel/sched/ext/internal.h\n@@ -243,6 +243,27 @@ enum scx_ops_flags {\n \t */\n \tSCX_OPS_ENQ_BLOCKED\t\t= 1LLU \u003c\u003c 10,\n \n+\t/*\n+\t * If set, what the scheduler's tasks run is charged to the cpu.max\n+\t * bandwidth of their cgroups, the runtime the fair class keeps and\n+\t * cpu.max.runtime reads, as what fair tasks run is. The tasks of a\n+\t * cgroup in both classes then share one quota, also with\n+\t * %SCX_OPS_SWITCH_PARTIAL, and nothing is handed over when tasks\n+\t * switch class.\n+\t *\n+\t * The kernel never throttles the scheduler's tasks. The scheduler\n+\t * enforces the quota by running a task only while\n+\t * scx_bpf_task_cpu_max_runtime() returns more than 0. What a task runs\n+\t * beyond that is charged: up to a slice (sched_cfs_bandwidth_slice_us)\n+\t * per CPU as a debt the cgroup's fair tasks on that CPU pay back, and up\n+\t * to a quota more from the cgroup's next period. The scheduler does not\n+\t * need ops.cgroup_set_runtime(), as a write of cpu.max.runtime sets that\n+\t * runtime.\n+\t *\n+\t * Without CONFIG_CFS_BANDWIDTH, this flag has no effect.\n+\t */\n+\tSCX_OPS_CHARGE_CPU_MAX\t\t= 1LLU \u003c\u003c 11,\n+\n \tSCX_OPS_ALL_FLAGS\t\t= SCX_OPS_KEEP_BUILTIN_IDLE |\n \t\t\t\t\t SCX_OPS_ENQ_LAST |\n \t\t\t\t\t SCX_OPS_ENQ_EXITING |\n@@ -253,7 +274,8 @@ enum scx_ops_flags {\n \t\t\t\t\t SCX_OPS_ALWAYS_ENQ_IMMED |\n \t\t\t\t\t SCX_OPS_TID_TO_TASK |\n \t\t\t\t\t SCX_OPS_LAZY_RESCHED |\n-\t\t\t\t\t SCX_OPS_ENQ_BLOCKED,\n+\t\t\t\t\t SCX_OPS_ENQ_BLOCKED |\n+\t\t\t\t\t SCX_OPS_CHARGE_CPU_MAX,\n \n \t/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */\n \t__SCX_OPS_INTERNAL_MASK\t\t= 0xffLLU \u003c\u003c 56,\n@@ -863,6 +885,26 @@ struct sched_ext_ops {\n \t */\n \tvoid (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);\n \n+\t/**\n+\t * @cgroup_set_runtime: A cgroup's runtime is being set\n+\t * @cgrp: cgroup whose runtime is being set\n+\t * @runtime_us: runtime in microseconds\n+\t *\n+\t * Set the runtime @cgrp has accumulated and not used yet to\n+\t * @runtime_us. This is from the cpu.max.runtime cgroup interface,\n+\t * which exists with CONFIG_CFS_BANDWIDTH only. It is called on every\n+\t * write, also of an unchanged value. The runtime goes down as @cgrp\n+\t * runs, so a write of the same value is a top-up.\n+\t *\n+\t * @cgrp has a quota, and @runtime_us is at most the quota + burst the\n+\t * scheduler was last given, by @cgroup_init or @cgroup_set_bandwidth:\n+\t * cpu.max and cpu.max.runtime writes reach the scheduler in the order\n+\t * the fair class applied them.\n+\t *\n+\t * Delivery follows the same rule as cgroup_set_weight().\n+\t */\n+\tvoid (*cgroup_set_runtime)(struct cgroup *cgrp, u64 runtime_us);\n+\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n \n \t/**\n@@ -1239,6 +1281,7 @@ struct sched_ext_ops_cid {\n \tvoid (*cpuctl_set_bandwidth)(struct cgroup *cgrp, u64 period_us, u64 quota_us,\n \t\t\t\t u64 burst_us);\n \tvoid (*cpuctl_set_idle)(struct cgroup *cgrp, bool idle);\n+\tvoid (*cpuctl_set_runtime)(struct cgroup *cgrp, u64 runtime_us);\n #endif\t/* CONFIG_EXT_GROUP_SCHED */\n \ts32 (*sub_attach)(struct scx_sub_attach_args *args);\n \tvoid (*sub_detach)(struct scx_sub_detach_args *args);\ndiff --git a/kernel/sched/fair.c b/kernel/sched/fair.c\nindex d4cc0caee6265d..9ff239f122bdaa 100644\n--- a/kernel/sched/fair.c\n+++ b/kernel/sched/fair.c\n@@ -6875,6 +6875,11 @@ void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)\n \t}\n \n \tcfs_b-\u003eruntime = min(cfs_b-\u003eruntime, cfs_b-\u003equota + cfs_b-\u003eburst);\n+\n+\t/* pay the debt cfs_bandwidth_charge_task() left */\n+\truntime = min(cfs_b-\u003eruntime, cfs_b-\u003edebt);\n+\tcfs_b-\u003eruntime -= runtime;\n+\tcfs_b-\u003edebt -= runtime;\n \tcfs_b-\u003eruntime_snap = cfs_b-\u003eruntime;\n }\n \n@@ -7421,6 +7426,8 @@ static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)\n \tstruct cfs_rq *cfs_rq;\n \tstruct rq *rq;\n \n+\tlockdep_assert_irqs_disabled();\n+\n \tguard(rcu)();\n \n \tlist_for_each_entry_rcu(cfs_rq, \u0026cfs_b-\u003ethrottled_cfs_rq,\n@@ -7811,6 +7818,140 @@ static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)\n \tINIT_LIST_HEAD(\u0026cfs_rq-\u003ethrottled_limbo_list);\n }\n \n+/*\n+ * Runtime after @periods refills of quota, capped at quota + burst as each\n+ * refill in __refill_cfs_bandwidth_runtime() caps it. The runtime can be above\n+ * the cap (__return_cfs_rq_runtime() does not cap it), and a refill then cuts\n+ * it to the cap.\n+ */\n+static u64 cfs_bandwidth_refilled(struct cfs_bandwidth *cfs_b, u64 periods)\n+{\n+\tu64 cap = cfs_b-\u003equota + cfs_b-\u003eburst;\n+\tu64 runtime = cfs_b-\u003eruntime;\n+\n+\tif (!periods || cfs_b-\u003equota == RUNTIME_INF)\n+\t\treturn runtime;\n+\tif (runtime \u003e= cap ||\n+\t periods \u003e= div64_u64(cap - runtime, cfs_b-\u003equota) + 1)\n+\t\treturn cap;\n+\treturn runtime + periods * cfs_b-\u003equota;\n+}\n+\n+/*\n+ * The period timer stops after a period in which the group took no runtime\n+ * (do_sched_cfs_period_timer()), and start_cfs_bandwidth() restarts it on\n+ * the next demand. The periods it slept through refill quota too: unused\n+ * quota accumulates up to quota + burst whether or not the group ran. While\n+ * the timer is stopped its expiry is the first period boundary it missed,\n+ * so the boundaries passed since then are the refills still owed.\n+ *\n+ * Without burst the cap is quota. The timer stops right after a refill that\n+ * nothing drew from, so the runtime is at quota then, and this changes nothing\n+ * for groups without a burst.\n+ *\n+ * This is the overrun that hrtimer_forward_now() returns, without moving the\n+ * expiry: one for the expiry itself, plus one for each full period since.\n+ */\n+static u64 cfs_bandwidth_idle_periods(struct cfs_bandwidth *cfs_b)\n+{\n+\tktime_t now = ktime_get();\n+\ts64 delta;\n+\n+\tif (cfs_b-\u003eperiod_active)\n+\t\treturn 0;\n+\n+\tdelta = ktime_to_ns(ktime_sub(now, hrtimer_get_expires(\u0026cfs_b-\u003eperiod_timer)));\n+\tif (delta \u003c 0)\n+\t\treturn 0;\n+\treturn div64_u64(delta, ktime_to_ns(cfs_b-\u003eperiod)) + 1;\n+}\n+\n+/*\n+ * Refill the periods a stopped timer slept through, at the bandwidth they\n+ * were earned under, and move its expiry past them so that they are not\n+ * counted again. A change of the bandwidth or a cpu.max.runtime write calls\n+ * this first, so that the change applies from then on and the group keeps\n+ * what it earned before. A group without a quota earned nothing.\n+ */\n+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b)\n+{\n+\tu64 idle_periods;\n+\n+\tlockdep_assert_held(\u0026cfs_b-\u003elock);\n+\n+\tif (cfs_b-\u003eperiod_active)\n+\t\treturn;\n+\n+\tidle_periods = hrtimer_forward_now(\u0026cfs_b-\u003eperiod_timer, cfs_b-\u003eperiod);\n+\tcfs_b-\u003eruntime = cfs_bandwidth_refilled(cfs_b, idle_periods);\n+\tcfs_b-\u003eruntime_snap = cfs_b-\u003eruntime;\n+}\n+\n+/*\n+ * The runtime of @cfs_b, as cpu.max.runtime reads it.\n+ *\n+ * __return_cfs_rq_runtime() returns slack without capping it, so the runtime\n+ * can exceed quota + burst until the next refill caps it. Report it capped,\n+ * so that a value read can always be written back.\n+ */\n+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b)\n+{\n+\tu64 runtime;\n+\n+\tguard(raw_spinlock_irq)(\u0026cfs_b-\u003elock);\n+\n+\truntime = cfs_bandwidth_refilled(cfs_b, cfs_bandwidth_idle_periods(cfs_b));\n+\tif (cfs_b-\u003equota != RUNTIME_INF)\n+\t\truntime = min(runtime, cfs_b-\u003equota + cfs_b-\u003eburst);\n+\n+\treturn runtime;\n+}\n+\n+/*\n+ * Set the runtime of @cfs_b, as a cpu.max.runtime write does, and hand it to\n+ * the throttled cfs_rqs at once rather than at the next period.\n+ */\n+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime)\n+{\n+\tbool throttled;\n+\ts64 snap;\n+\n+\tguard(irq)();\n+\n+\tscoped_guard (raw_spinlock, \u0026cfs_b-\u003elock) {\n+\t\tif (cfs_b-\u003equota == RUNTIME_INF ||\n+\t\t runtime \u003e cfs_b-\u003equota + cfs_b-\u003eburst)\n+\t\t\treturn -EINVAL;\n+\n+\t\t/*\n+\t\t * Refill the periods that passed before the write, so that the\n+\t\t * write replaces them and only the periods after it refill.\n+\t\t */\n+\t\tcfs_bandwidth_refill_idle_periods(cfs_b);\n+\n+\t\t/*\n+\t\t * The next refill counts runtime_snap - runtime as burst usage.\n+\t\t * Move runtime_snap by what the write adds or takes away, so\n+\t\t * that the write itself is not counted as burst usage but what\n+\t\t * the group ran since the last refill still is.\n+\t\t */\n+\t\tsnap = cfs_b-\u003eruntime_snap + runtime - cfs_b-\u003eruntime;\n+\t\tcfs_b-\u003eruntime_snap = max(snap, 0);\n+\t\tcfs_b-\u003eruntime = runtime;\n+\n+\t\tthrottled = !list_empty(\u0026cfs_b-\u003ethrottled_cfs_rq) \u0026\u0026 runtime;\n+\t}\n+\n+\t/*\n+\t * distribute_cfs_runtime() takes the rq locks, so it runs without\n+\t * cfs_b-\u003elock and with interrupts disabled, as from the slack timer.\n+\t */\n+\tif (throttled)\n+\t\tdistribute_cfs_runtime(cfs_b);\n+\n+\treturn 0;\n+}\n+\n void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)\n {\n \tlockdep_assert_held(\u0026cfs_b-\u003elock);\n@@ -7818,8 +7959,8 @@ void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)\n \tif (cfs_b-\u003eperiod_active)\n \t\treturn;\n \n+\tcfs_bandwidth_refill_idle_periods(cfs_b);\n \tcfs_b-\u003eperiod_active = 1;\n-\thrtimer_forward_now(\u0026cfs_b-\u003eperiod_timer, cfs_b-\u003eperiod);\n \thrtimer_start_expires(\u0026cfs_b-\u003eperiod_timer, HRTIMER_MODE_ABS_PINNED);\n }\n \n@@ -7940,6 +8081,123 @@ bool cfs_task_bw_constrained(struct task_struct *p)\n \treturn false;\n }\n \n+/*\n+ * Charge @delta_exec, which @p ran on @rq outside the fair class, to the\n+ * bandwidth of its task group and of each ancestor with a quota, as\n+ * account_cfs_rq_runtime() charges a fair task. A cfs_rq that runs out takes\n+ * another slice from cfs_b, but @p is never throttled: the BPF scheduler that\n+ * runs it stops it, and the group's fair tasks are throttled when they run.\n+ *\n+ * Debt below -slice that cfs_b cannot cover moves to cfs_b, up to a quota,\n+ * and the next refill pays it, so that a scheduler which keeps running @p\n+ * cannot put the group's fair tasks on @rq in more debt than a slice.\n+ */\n+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,\n+\t\t\t u64 delta_exec)\n+{\n+\ts64 floor = -(s64)sched_cfs_bandwidth_slice();\n+\tstruct task_group *tg;\n+\n+\tlockdep_assert_rq_held(rq);\n+\n+\tif (!cfs_bandwidth_used())\n+\t\treturn;\n+\n+\tfor (tg = task_group(p); tg; tg = tg-\u003eparent) {\n+\t\tstruct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);\n+\t\tstruct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));\n+\n+\t\tif (!cfs_rq-\u003eruntime_enabled)\n+\t\t\tcontinue;\n+\n+\t\tcfs_rq-\u003eruntime_remaining -= delta_exec;\n+\n+\t\t/*\n+\t\t * A throttled cfs_rq gets runtime from distribute_cfs_runtime().\n+\t\t * Without runtime, an active period timer refills it, so skip\n+\t\t * the lock. A stopped one is restarted by the assign.\n+\t\t */\n+\t\tif (cfs_rq-\u003eruntime_remaining \u003c= 0 \u0026\u0026 !cfs_rq-\u003ethrottled \u0026\u0026\n+\t\t (READ_ONCE(cfs_b-\u003eruntime) || !READ_ONCE(cfs_b-\u003eperiod_active))) {\n+\t\t\tscoped_guard (raw_spinlock, \u0026cfs_b-\u003elock)\n+\t\t\t\t__assign_cfs_rq_runtime(cfs_b, cfs_rq,\n+\t\t\t\t\t\t\tsched_cfs_bandwidth_slice());\n+\t\t}\n+\n+\t\tif (cfs_rq-\u003eruntime_remaining \u003c floor) {\n+\t\t\tscoped_guard (raw_spinlock, \u0026cfs_b-\u003elock)\n+\t\t\t\tcfs_b-\u003edebt = min_t(u64, cfs_b-\u003edebt + floor -\n+\t\t\t\t\t\t cfs_rq-\u003eruntime_remaining, cfs_b-\u003equota);\n+\t\t\tcfs_rq-\u003eruntime_remaining = floor;\n+\t\t}\n+\t}\n+}\n+\n+/*\n+ * @p leaves @rq: give the runtime @rq holds for its groups back, less\n+ * min_cfs_rq_runtime, as a fair dequeue does when a cfs_rq empties. Pay\n+ * what @rq owes from cfs_b, as @p may not run on @rq again.\n+ */\n+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p)\n+{\n+\tstruct task_group *tg;\n+\n+\tlockdep_assert_rq_held(rq);\n+\n+\tif (!cfs_bandwidth_used())\n+\t\treturn;\n+\n+\tfor (tg = task_group(p); tg; tg = tg-\u003eparent) {\n+\t\tstruct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);\n+\t\tstruct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));\n+\n+\t\treturn_cfs_rq_runtime(cfs_rq);\n+\n+\t\tif (cfs_rq-\u003eruntime_enabled \u0026\u0026 cfs_rq-\u003eruntime_remaining \u003c 0 \u0026\u0026\n+\t\t !cfs_rq-\u003ethrottled \u0026\u0026 READ_ONCE(cfs_b-\u003eruntime)) {\n+\t\t\tscoped_guard (raw_spinlock, \u0026cfs_b-\u003elock)\n+\t\t\t\t__assign_cfs_rq_runtime(cfs_b, cfs_rq, 0);\n+\t\t}\n+\t}\n+}\n+\n+/*\n+ * The runtime @p's groups have left for it on its CPU, without locks: the\n+ * least, over the groups with a quota, of what the CPU holds or owes and\n+ * cfs_b's runtime. Debt counts up to a quota less 1ns, so that a full period\n+ * lets @p run and pay the rest. A group whose period timer is stopped does\n+ * not count, as the next charge restarts the timer and refills what it owes.\n+ * RUNTIME_INF if no group counts.\n+ */\n+u64 cfs_bandwidth_task_runtime(struct task_struct *p)\n+{\n+\tu64 runtime = RUNTIME_INF;\n+\tstruct task_group *tg;\n+\tint cpu = task_cpu(p);\n+\n+\tif (!cfs_bandwidth_used())\n+\t\treturn runtime;\n+\n+\tguard(rcu)();\n+\n+\tfor (tg = task_group(p); tg; tg = tg-\u003eparent) {\n+\t\tstruct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);\n+\t\tstruct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);\n+\t\ts64 held;\n+\n+\t\tif (!READ_ONCE(cfs_rq-\u003eruntime_enabled) ||\n+\t\t !READ_ONCE(cfs_b-\u003eperiod_active))\n+\t\t\tcontinue;\n+\n+\t\theld = max_t(s64, READ_ONCE(cfs_rq-\u003eruntime_remaining),\n+\t\t\t 1 - (s64)READ_ONCE(cfs_b-\u003equota));\n+\t\theld += READ_ONCE(cfs_b-\u003eruntime);\n+\t\truntime = min_t(u64, runtime, max_t(s64, held, 0));\n+\t}\n+\n+\treturn runtime;\n+}\n+\n #ifdef CONFIG_NO_HZ_FULL\n /* called from pick_next_task_fair() */\n static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)\ndiff --git a/kernel/sched/sched.h b/kernel/sched/sched.h\nindex a4df59c9c9b601..fd98000ffd7449 100644\n--- a/kernel/sched/sched.h\n+++ b/kernel/sched/sched.h\n@@ -456,6 +456,7 @@ struct cfs_bandwidth {\n \tu64\t\t\truntime;\n \tu64\t\t\tburst;\n \tu64\t\t\truntime_snap;\n+\tu64\t\t\tdebt;\n \ts64\t\t\thierarchical_quota;\n \n \tu8\t\t\tidle;\n@@ -578,6 +579,9 @@ extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth\n \n extern void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b);\n extern void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b);\n+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b);\n+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime);\n+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b);\n extern void unthrottle_cfs_rq(struct cfs_rq *cfs_rq);\n extern bool cfs_task_bw_constrained(struct task_struct *p);\n \n@@ -618,6 +622,17 @@ static inline bool cfs_task_bw_constrained(struct task_struct *p) { return false\n \n #endif /* !CONFIG_CGROUP_SCHED */\n \n+#ifdef CONFIG_CFS_BANDWIDTH\n+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p, u64 delta_exec);\n+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p);\n+u64 cfs_bandwidth_task_runtime(struct task_struct *p);\n+#else\n+static inline void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,\n+\t\t\t\t\t u64 delta_exec) { }\n+static inline void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p) { }\n+static inline u64 cfs_bandwidth_task_runtime(struct task_struct *p) { return RUNTIME_INF; }\n+#endif\n+\n /*\n * A weight of 0 or 1 can cause arithmetics problems.\n * A weight of a cfs_rq is the sum of weights of which entities\ndiff --git a/tools/sched_ext/include/scx/common.bpf.h b/tools/sched_ext/include/scx/common.bpf.h\nindex 6194484d4d9a99..cfb7f1b70665fc 100644\n--- a/tools/sched_ext/include/scx/common.bpf.h\n+++ b/tools/sched_ext/include/scx/common.bpf.h\n@@ -98,6 +98,7 @@ s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags\n s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;\n bool scx_bpf_task_running(const struct task_struct *p) __ksym;\n s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;\n+u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p) __ksym __weak;\n struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym __weak;\n struct rq *scx_bpf_locked_rq(void) __ksym;\n struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;\ndiff --git a/tools/sched_ext/include/scx/compat.h b/tools/sched_ext/include/scx/compat.h\nindex 07fb55e63c57c5..60b9972f1a5dc2 100644\n--- a/tools/sched_ext/include/scx/compat.h\n+++ b/tools/sched_ext/include/scx/compat.h\n@@ -215,6 +215,7 @@ static inline bool __COMPAT_struct_has_field(const char *type, const char *field\n #define SCX_OPS_BUILTIN_IDLE_PER_NODE SCX_OPS_FLAG(SCX_OPS_BUILTIN_IDLE_PER_NODE)\n #define SCX_OPS_ALWAYS_ENQ_IMMED SCX_OPS_FLAG(SCX_OPS_ALWAYS_ENQ_IMMED)\n #define SCX_OPS_ENQ_BLOCKED SCX_OPS_FLAG(SCX_OPS_ENQ_BLOCKED)\n+#define SCX_OPS_CHARGE_CPU_MAX SCX_OPS_FLAG(SCX_OPS_CHARGE_CPU_MAX)\n \n #define SCX_PICK_IDLE_FLAG(name) __COMPAT_ENUM_OR_ZERO(\"scx_pick_idle_cpu_flags\", #name)\n \ndiff --git a/tools/testing/selftests/cgroup/test_cpu.c b/tools/testing/selftests/cgroup/test_cpu.c\nindex 3456e3e988c68a..04a061da514cec 100644\n--- a/tools/testing/selftests/cgroup/test_cpu.c\n+++ b/tools/testing/selftests/cgroup/test_cpu.c\n@@ -809,6 +809,517 @@ static int test_cpucg_max_nested(const char *root)\n \treturn ret;\n }\n \n+/* Wait until the period timer of @cgroup starts a new period. */\n+static int wait_period_start(const char *cgroup)\n+{\n+\tlong nr_periods = cg_read_key_long(cgroup, \"cpu.stat\", \"nr_periods\");\n+\tint i;\n+\n+\tfor (i = 0; i \u003c 3000; i++) {\n+\t\tusleep(1000);\n+\t\tif (cg_read_key_long(cgroup, \"cpu.stat\", \"nr_periods\") != nr_periods)\n+\t\t\treturn 0;\n+\t}\n+\treturn -1;\n+}\n+\n+static long long monotonic_ns(void)\n+{\n+\tstruct timespec ts;\n+\n+\tclock_gettime(CLOCK_MONOTONIC, \u0026ts);\n+\treturn ts.tv_sec * 1000000000LL + ts.tv_nsec;\n+}\n+\n+/* For (long)arg seconds, run for 1ms and then sleep for 10ms. */\n+static int run_and_sleep(const char *cgroup, void *arg)\n+{\n+\tlong long end = monotonic_ns() + (long)arg * 1000000000LL;\n+\tlong long start;\n+\n+\twhile ((start = monotonic_ns()) \u003c end) {\n+\t\twhile (monotonic_ns() - start \u003c 1000000)\n+\t\t\t;\n+\t\tusleep(10000);\n+\t}\n+\treturn 0;\n+}\n+\n+static int test_cpucg_max_runtime(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong quota_usec = 1000;\t\t/* 1ms (minimum) */\n+\tlong period_usec = 100000;\t/* 100ms */\n+\tlong burst_usec = 5000000;\t/* 5s, so cap = 5001ms */\n+\tlong runtime_usec = 2500000;\t/* 2500ms, half of the 5s run */\n+\tlong duration_sec = 5;\n+\t/* The injected runtime plus the quota refilled each period of the run */\n+\tlong expected_usec = runtime_usec +\n+\t\t\t duration_sec * USEC_PER_SEC / period_usec * quota_usec;\n+\tlong usage_usec;\n+\tchar *cpucg;\n+\tchar buf[64];\n+\tint pid;\n+\n+\tcpucg = cg_name(root, \"cpucg_runtime_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\t/* Without a quota there is no runtime to set. */\n+\tif (!cg_write_numeric(cpucg, \"cpu.max.runtime\", runtime_usec))\n+\t\tgoto cleanup;\n+\n+\tsnprintf(buf, sizeof(buf), \"%ld %ld\", quota_usec, period_usec);\n+\tif (cg_write(cpucg, \"cpu.max\", buf))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", burst_usec))\n+\t\tgoto cleanup;\n+\n+\t/* Start burner, let it settle, then inject credits */\n+\tstruct cpu_hog_func_param param = {\n+\t\t.nprocs = 1,\n+\t\t.ts = { .tv_sec = duration_sec, .tv_nsec = 0 },\n+\t\t.clock_type = CPU_HOG_CLOCK_WALL,\n+\t};\n+\tpid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)\u0026param);\n+\tif (pid \u003c 0)\n+\t\tgoto cleanup;\n+\n+\tusleep(100000);\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", runtime_usec)) {\n+\t\tkill(pid, SIGKILL);\n+\t\twaitpid(pid, NULL, 0);\n+\t\tgoto cleanup;\n+\t}\n+\n+\twaitpid(pid, NULL, 0);\n+\n+\tusage_usec = cg_read_key_long(cpucg, \"cpu.stat\", \"usage_usec\");\n+\tif (usage_usec \u003c= 0)\n+\t\tgoto cleanup;\n+\n+\t/* At least the injected runtime, at most 5% above the expected usage. */\n+\tif (usage_usec \u003c runtime_usec ||\n+\t usage_usec \u003e expected_usec + expected_usec / 20)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * A cpu.max.runtime write is not burst usage: writing a runtime below the\n+ * current one leaves cpu.stat's nr_bursts and burst_usec where they were.\n+ */\n+static int test_cpucg_max_runtime_burst_stats(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong nr_bursts, burst_usec;\n+\tchar *cpucg;\n+\n+\tcpucg = cg_name(root, \"cpucg_runtime_burst_stats_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\t/* A long period, so the write lands before the timer's first refill. */\n+\tif (cg_write(cpucg, \"cpu.max\", \"10000 1000000\"))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 190000))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", 0))\n+\t\tgoto cleanup;\n+\n+\t/* The idle group refills for a few periods. */\n+\tsleep(3);\n+\tnr_bursts = cg_read_key_long(cpucg, \"cpu.stat\", \"nr_bursts\");\n+\tburst_usec = cg_read_key_long(cpucg, \"cpu.stat\", \"burst_usec\");\n+\tif (nr_bursts != 0 || burst_usec != 0)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * A cpu.max.runtime write hands the runtime to a throttled group at once,\n+ * rather than at the next period: with a 1s period, the group runs again\n+ * within 100ms of the write, before the next period starts.\n+ */\n+static int test_cpucg_max_runtime_unthrottle(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong usage_before, usage_after, nr_periods;\n+\tchar *cpucg;\n+\tint pid;\n+\n+\tcpucg = cg_name(root, \"cpucg_runtime_unthrottle_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\t/* 1ms per 1s period, with room for a runtime of up to 1s. */\n+\tif (cg_write(cpucg, \"cpu.max\", \"1000 1000000\"))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 999000))\n+\t\tgoto cleanup;\n+\n+\tstruct cpu_hog_func_param param = {\n+\t\t.nprocs = 1,\n+\t\t.ts = { .tv_sec = 2, .tv_nsec = 0 },\n+\t\t.clock_type = CPU_HOG_CLOCK_WALL,\n+\t};\n+\tpid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)\u0026param);\n+\tif (pid \u003c 0)\n+\t\tgoto cleanup;\n+\n+\t/*\n+\t * The period timer's phase is random: start right after a boundary,\n+\t * so that the next one is some 900ms away. The hog uses up its runtime\n+\t * and is throttled for the period.\n+\t */\n+\tif (wait_period_start(cpucg))\n+\t\tgoto cleanup_hog;\n+\tnr_periods = cg_read_key_long(cpucg, \"cpu.stat\", \"nr_periods\");\n+\tusleep(50000);\n+\tusage_before = cg_read_key_long(cpucg, \"cpu.stat\", \"usage_usec\");\n+\tif (usage_before \u003c 0 || usage_before \u003e 20000)\n+\t\tgoto cleanup_hog;\n+\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", 500000))\n+\t\tgoto cleanup_hog;\n+\n+\t/* No period started meanwhile: only the write lets the hog run. */\n+\tusleep(100000);\n+\tusage_after = cg_read_key_long(cpucg, \"cpu.stat\", \"usage_usec\");\n+\tif (cg_read_key_long(cpucg, \"cpu.stat\", \"nr_periods\") != nr_periods)\n+\t\tgoto cleanup_hog;\n+\tif (usage_after - usage_before \u003c 50000)\n+\t\tgoto cleanup_hog;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup_hog:\n+\tkill(pid, SIGKILL);\n+\twaitpid(pid, NULL, 0);\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * What a group ran beyond its quota before a cpu.max.runtime write is still\n+ * burst usage: a write of the runtime the group has left does not hide it.\n+ */\n+static int test_cpucg_max_runtime_burst_kept(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong burst_before, burst_after, runtime_usec;\n+\tchar *cpucg;\n+\tint pid;\n+\n+\tcpucg = cg_name(root, \"cpucg_runtime_burst_kept_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\t/* 10ms per 1s period, and a runtime of 1s to run on. */\n+\tif (cg_write(cpucg, \"cpu.max\", \"10000 1000000\"))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 990000))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", 1000000))\n+\t\tgoto cleanup;\n+\n+\tstruct cpu_hog_func_param param = {\n+\t\t.nprocs = 1,\n+\t\t.ts = { .tv_sec = 10, .tv_nsec = 0 },\n+\t\t.clock_type = CPU_HOG_CLOCK_WALL,\n+\t};\n+\tpid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)\u0026param);\n+\tif (pid \u003c 0)\n+\t\tgoto cleanup;\n+\n+\t/* Run some 300ms, all in one period, and stop. */\n+\tif (wait_period_start(cpucg)) {\n+\t\tkill(pid, SIGKILL);\n+\t\twaitpid(pid, NULL, 0);\n+\t\tgoto cleanup;\n+\t}\n+\tburst_before = cg_read_key_long(cpucg, \"cpu.stat\", \"burst_usec\");\n+\tusleep(300000);\n+\tkill(pid, SIGKILL);\n+\twaitpid(pid, NULL, 0);\n+\n+\t/* Write back what is left: the next refill counts the 300ms run. */\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", runtime_usec))\n+\t\tgoto cleanup;\n+\tsleep(1);\n+\tburst_after = cg_read_key_long(cpucg, \"cpu.stat\", \"burst_usec\");\n+\tif (burst_before \u003c 0 || burst_after - burst_before \u003c 250000)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * cpu.max.runtime reads at most quota + burst, so that a value read can be\n+ * written back. A cfs_rq that dequeues returns its unused runtime, which can\n+ * take the runtime above quota + burst until the next refill caps it: run\n+ * tasks that keep doing that, and read and write back the runtime meanwhile.\n+ */\n+static int test_cpucg_max_runtime_read_capped(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong cap_usec = 100000;\t\t/* quota 100ms, no burst */\n+\tlong long end;\n+\tlong runtime_usec;\n+\tchar *cpucg;\n+\tint pids[2];\n+\tint i, n = 0;\n+\n+\tcpucg = cg_name(root, \"cpucg_runtime_read_capped_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\tif (cg_write(cpucg, \"cpu.max\", \"100000 100000\"))\n+\t\tgoto cleanup;\n+\n+\tfor (n = 0; n \u003c 2; n++) {\n+\t\tpids[n] = cg_run_nowait(cpucg, run_and_sleep, (void *)4L);\n+\t\tif (pids[n] \u003c 0)\n+\t\t\tgoto cleanup_tasks;\n+\t}\n+\n+\tend = monotonic_ns() + 3000000000LL;\n+\twhile (monotonic_ns() \u003c end) {\n+\t\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\t\tif (runtime_usec \u003c 0 || runtime_usec \u003e cap_usec)\n+\t\t\tgoto cleanup_tasks;\n+\t\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", runtime_usec))\n+\t\t\tgoto cleanup_tasks;\n+\t}\n+\n+\tret = KSFT_PASS;\n+\n+cleanup_tasks:\n+\tfor (i = 0; i \u003c n; i++) {\n+\t\tkill(pids[i], SIGKILL);\n+\t\twaitpid(pids[i], NULL, 0);\n+\t}\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * A group with a burst keeps earning quota while it is idle, up to\n+ * quota + burst, and cpu.max.runtime reads what it has earned. Without a\n+ * burst the runtime stays at quota.\n+ */\n+static int test_cpucg_max_idle_refill(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong quota_usec = 10000;\t/* 10ms */\n+\tlong period_usec = 100000;\t/* 100ms */\n+\tlong burst_usec = 990000;\t/* cap 1s */\n+\tlong runtime_usec;\n+\tchar *cpucg;\n+\tchar buf[64];\n+\n+\tcpucg = cg_name(root, \"cpucg_idle_refill_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\tsnprintf(buf, sizeof(buf), \"%ld %ld\", quota_usec, period_usec);\n+\tif (cg_write(cpucg, \"cpu.max\", buf))\n+\t\tgoto cleanup;\n+\n+\t/* No burst: the runtime stays at quota while idle. */\n+\tsleep(1);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != quota_usec)\n+\t\tgoto cleanup;\n+\n+\t/* Burst: the write refills once (20ms), then 1s idle earns 10 more. */\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", burst_usec))\n+\t\tgoto cleanup;\n+\tsleep(1);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec \u003c 110000 || runtime_usec \u003e 130000)\n+\t\tgoto cleanup;\n+\n+\t/* Capped at quota + burst. */\n+\tsleep(10);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != quota_usec + burst_usec)\n+\t\tgoto cleanup;\n+\n+\t/*\n+\t * A write sets the runtime from now on: 500ms later, five refills, or\n+\t * six if the sleep overruns into the next period.\n+\t */\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", 0))\n+\t\tgoto cleanup;\n+\tusleep(500000);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec \u003c 50000 || runtime_usec \u003e 60000)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * A cpu.max or cpu.max.burst write applies from then on: what a group with\n+ * a quota earned while idle is kept, capped at the new quota + burst, and a\n+ * group that had no quota has earned nothing while it had none.\n+ */\n+static int test_cpucg_max_idle_refill_write(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong quota_usec = 10000;\t/* 10ms */\n+\tlong period_usec = 100000;\t/* 100ms */\n+\tlong runtime_usec;\n+\tchar *cpucg = NULL, *fresh = NULL;\n+\tchar buf[64];\n+\n+\tcpucg = cg_name(root, \"cpucg_idle_refill_write_test\");\n+\tfresh = cg_name(root, \"cpucg_idle_refill_fresh_test\");\n+\tif (!cpucg || !fresh)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg) || cg_create(fresh))\n+\t\tgoto cleanup;\n+\n+\tsnprintf(buf, sizeof(buf), \"%ld %ld\", quota_usec, period_usec);\n+\tif (cg_write(cpucg, \"cpu.max\", buf))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 190000))\n+\t\tgoto cleanup;\n+\n+\t/* 3s idle fills the group to quota + burst. */\n+\tsleep(3);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != 200000)\n+\t\tgoto cleanup;\n+\n+\t/* Writing the same cpu.max keeps what the group earned. */\n+\tif (cg_write(cpucg, \"cpu.max\", buf))\n+\t\tgoto cleanup;\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != 200000)\n+\t\tgoto cleanup;\n+\n+\t/* A lower burst keeps it too, capped at the new quota + burst. */\n+\tsleep(2);\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 90000))\n+\t\tgoto cleanup;\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != 100000)\n+\t\tgoto cleanup;\n+\n+\t/* A group given a quota after idling without one starts with a refill. */\n+\tif (cg_write_numeric(fresh, \"cpu.max.burst\", 190000))\n+\t\tgoto cleanup;\n+\tsleep(2);\n+\tif (cg_write(fresh, \"cpu.max\", buf))\n+\t\tgoto cleanup;\n+\truntime_usec = cg_read_long(fresh, \"cpu.max.runtime\");\n+\tif (runtime_usec != quota_usec)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tif (fresh)\n+\t\tcg_destroy(fresh);\n+\tif (cpucg)\n+\t\tcg_destroy(cpucg);\n+\tfree(fresh);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n+/*\n+ * A cpu.max.runtime write sets the runtime exactly, and only the periods\n+ * after it refill.\n+ */\n+static int test_cpucg_max_idle_refill_runtime_write(const char *root)\n+{\n+\tint ret = KSFT_FAIL;\n+\tlong runtime_usec;\n+\tchar *cpucg;\n+\n+\tcpucg = cg_name(root, \"cpucg_idle_refill_runtime_test\");\n+\tif (!cpucg)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(cpucg))\n+\t\tgoto cleanup;\n+\n+\tif (cg_write(cpucg, \"cpu.max\", \"10000 100000\"))\n+\t\tgoto cleanup;\n+\tif (cg_write_numeric(cpucg, \"cpu.max.burst\", 190000))\n+\t\tgoto cleanup;\n+\n+\tsleep(3);\n+\tif (cg_write_numeric(cpucg, \"cpu.max.runtime\", 30000))\n+\t\tgoto cleanup;\n+\t/* One refill if a period boundary passes before the read. */\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec != 30000 \u0026\u0026 runtime_usec != 40000)\n+\t\tgoto cleanup;\n+\n+\t/* 250ms after the write: two or three refills, by the boundaries. */\n+\tusleep(250000);\n+\truntime_usec = cg_read_long(cpucg, \"cpu.max.runtime\");\n+\tif (runtime_usec \u003c 50000 || runtime_usec \u003e 60000)\n+\t\tgoto cleanup;\n+\n+\tret = KSFT_PASS;\n+\n+cleanup:\n+\tcg_destroy(cpucg);\n+\tfree(cpucg);\n+\treturn ret;\n+}\n+\n #define T(x) { x, #x }\n struct cpucg_test {\n \tint (*fn)(const char *root);\n@@ -823,6 +1334,14 @@ struct cpucg_test {\n \tT(test_cpucg_nested_weight_underprovisioned),\n \tT(test_cpucg_max),\n \tT(test_cpucg_max_nested),\n+\tT(test_cpucg_max_runtime),\n+\tT(test_cpucg_max_runtime_burst_stats),\n+\tT(test_cpucg_max_runtime_unthrottle),\n+\tT(test_cpucg_max_runtime_burst_kept),\n+\tT(test_cpucg_max_runtime_read_capped),\n+\tT(test_cpucg_max_idle_refill),\n+\tT(test_cpucg_max_idle_refill_write),\n+\tT(test_cpucg_max_idle_refill_runtime_write),\n };\n #undef T\n \ndiff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile\nindex c5d3a2eaea7da2..4a727b8dc7aabc 100644\n--- a/tools/testing/selftests/sched_ext/Makefile\n+++ b/tools/testing/selftests/sched_ext/Makefile\n@@ -165,6 +165,7 @@ all_test_bpfprogs := $(foreach prog,$(wildcard *.bpf.c),$(INCLUDE_DIR)/$(patsubs\n \n auto-test-targets :=\t\t\t\\\n \tcgroup_nr_cpus\t\t\t\\\n+\tcgroup_runtime\t\t\t\\\n \tcreate_dsq\t\t\t\\\n \tdequeue\t\t\t\t\\\n \tdequeue_iter\t\t\t\\\ndiff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c\nnew file mode 100644\nindex 00000000000000..ec98a25d19c291\n--- /dev/null\n+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c\n@@ -0,0 +1,195 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * A scheduler with SCX_OPS_CHARGE_CPU_MAX, for the cgroup_runtime tests. It\n+ * runs a task only while scx_bpf_task_cpu_max_runtime() says it has runtime\n+ * left, unless @ignore_runtime is set. A task that has none waits in HELD_DSQ,\n+ * and a timer kicks the idle CPUs every millisecond, so that they take it\n+ * once a period refills the runtime.\n+ *\n+ * partial_ops sets SCX_OPS_SWITCH_PARTIAL and full_ops does not. Both pass\n+ * the cpu.max and cpu.max.runtime writes of @cgid on to the test.\n+ */\n+\n+#include \u003cscx/common.bpf.h\u003e\n+\n+char _license[] SEC(\"license\") = \"GPL\";\n+\n+#define HELD_DSQ\t0\n+#define KICK_NS\t\t1000000\n+\n+UEI_DEFINE(uei);\n+\n+/* the cgroup under test, set before attaching */\n+u64 cgid;\n+\n+/* run tasks whether or not they have runtime left */\n+bool ignore_runtime;\n+\n+/* tasks held for lack of runtime */\n+u64 nr_held;\n+\n+/* the cpu.max and cpu.max.runtime writes of @cgid */\n+u64 nr_set_bw;\n+u64 quota_us;\n+u64 burst_us;\n+u64 nr_set_runtime;\n+/* cgroup_set_runtime() calls above the quota + burst last given */\n+u64 nr_bad_order;\n+\n+struct kick_timer {\n+\tstruct bpf_timer timer;\n+};\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_ARRAY);\n+\t__uint(max_entries, 1);\n+\t__type(key, u32);\n+\t__type(value, struct kick_timer);\n+} kick_timer SEC(\".maps\");\n+\n+static bool runnable(struct task_struct *p)\n+{\n+\treturn ignore_runtime || scx_bpf_task_cpu_max_runtime(p);\n+}\n+\n+s32 BPF_STRUCT_OPS(cgroup_runtime_select_cpu, struct task_struct *p,\n+\t\t s32 prev_cpu, u64 wake_flags)\n+{\n+\treturn prev_cpu;\n+}\n+\n+void BPF_STRUCT_OPS(cgroup_runtime_enqueue, struct task_struct *p,\n+\t\t u64 enq_flags)\n+{\n+\tif (!runnable(p)) {\n+\t\t__sync_fetch_and_add(\u0026nr_held, 1);\n+\t\tscx_bpf_dsq_insert(p, HELD_DSQ, SCX_SLICE_DFL, enq_flags);\n+\t\treturn;\n+\t}\n+\t/* the last task of a CPU going idle must go to its local DSQ */\n+\tif (enq_flags \u0026 SCX_ENQ_LAST)\n+\t\tscx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, enq_flags);\n+\telse\n+\t\tscx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);\n+}\n+\n+void BPF_STRUCT_OPS(cgroup_runtime_dispatch, s32 cpu, struct task_struct *prev)\n+{\n+\tstruct task_struct *p = __COMPAT_scx_bpf_dsq_peek(HELD_DSQ);\n+\n+\tif (p \u0026\u0026 runnable(p))\n+\t\tscx_bpf_dsq_move_to_local(HELD_DSQ, 0);\n+}\n+\n+/*\n+ * Stop a task that ran out, so that it goes through enqueue again.\n+ * SCX_OPS_ENQ_LAST makes that so also when it is alone on its CPU.\n+ */\n+void BPF_STRUCT_OPS(cgroup_runtime_tick, struct task_struct *p)\n+{\n+\tif (!runnable(p))\n+\t\tscx_bpf_task_set_slice(p, 0);\n+}\n+\n+static int kick_timerfn(void *map, int *key, struct bpf_timer *timer)\n+{\n+\ts32 cpu;\n+\n+\tif (scx_bpf_dsq_nr_queued(HELD_DSQ))\n+\t\tbpf_for(cpu, 0, scx_bpf_nr_cpu_ids())\n+\t\t\tscx_bpf_kick_cpu(cpu, SCX_KICK_IDLE);\n+\n+\tbpf_timer_start(timer, KICK_NS, 0);\n+\treturn 0;\n+}\n+\n+s32 BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_init)\n+{\n+\tstruct bpf_timer *timer;\n+\tu32 key = 0;\n+\ts32 ret;\n+\n+\tret = scx_bpf_create_dsq(HELD_DSQ, -1);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\ttimer = bpf_map_lookup_elem(\u0026kick_timer, \u0026key);\n+\tif (!timer)\n+\t\treturn -ESRCH;\n+\tbpf_timer_init(timer, \u0026kick_timer, CLOCK_MONOTONIC);\n+\tbpf_timer_set_callback(timer, kick_timerfn);\n+\treturn bpf_timer_start(timer, KICK_NS, 0);\n+}\n+\n+static bool is_target(struct cgroup *cgrp)\n+{\n+\treturn cgid \u0026\u0026 cgrp-\u003ekn-\u003eid == cgid;\n+}\n+\n+/* sleepable: cpu.max writes call it in process context */\n+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_bandwidth,\n+\t\t\t struct cgroup *cgrp, u64 period_us, u64 quota,\n+\t\t\t u64 burst)\n+{\n+\tif (!is_target(cgrp))\n+\t\treturn;\n+\n+\t__sync_fetch_and_add(\u0026nr_set_bw, 1);\n+\tquota_us = quota;\n+\tburst_us = burst;\n+}\n+\n+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_runtime,\n+\t\t\t struct cgroup *cgrp, u64 runtime_us)\n+{\n+\tif (!is_target(cgrp))\n+\t\treturn;\n+\n+\t__sync_fetch_and_add(\u0026nr_set_runtime, 1);\n+\tif (runtime_us \u003e quota_us + burst_us)\n+\t\t__sync_fetch_and_add(\u0026nr_bad_order, 1);\n+}\n+\n+s32 BPF_STRUCT_OPS(cgroup_runtime_cgroup_init, struct cgroup *cgrp,\n+\t\t struct scx_cgroup_init_args *args)\n+{\n+\tif (is_target(cgrp)) {\n+\t\tquota_us = args-\u003ebw_quota_us;\n+\t\tburst_us = args-\u003ebw_burst_us;\n+\t}\n+\treturn 0;\n+}\n+\n+void BPF_STRUCT_OPS(cgroup_runtime_exit, struct scx_exit_info *ei)\n+{\n+\tUEI_RECORD(uei, ei);\n+}\n+\n+SCX_OPS_DEFINE(partial_ops,\n+\t .select_cpu\t\t= (void *)cgroup_runtime_select_cpu,\n+\t .enqueue\t\t\t= (void *)cgroup_runtime_enqueue,\n+\t .dispatch\t\t= (void *)cgroup_runtime_dispatch,\n+\t .tick\t\t\t= (void *)cgroup_runtime_tick,\n+\t .init\t\t\t= (void *)cgroup_runtime_init,\n+\t .cgroup_init\t\t= (void *)cgroup_runtime_cgroup_init,\n+\t .cgroup_set_bandwidth\t= (void *)cgroup_runtime_cgroup_set_bandwidth,\n+\t .cgroup_set_runtime\t= (void *)cgroup_runtime_cgroup_set_runtime,\n+\t .exit\t\t\t= (void *)cgroup_runtime_exit,\n+\t .flags\t\t\t= SCX_OPS_SWITCH_PARTIAL |\n+\t\t\t\t\t SCX_OPS_ENQ_LAST |\n+\t\t\t\t\t SCX_OPS_CHARGE_CPU_MAX,\n+\t .name\t\t\t= \"cgroup_runtime\");\n+\n+SCX_OPS_DEFINE(full_ops,\n+\t .select_cpu\t\t= (void *)cgroup_runtime_select_cpu,\n+\t .enqueue\t\t\t= (void *)cgroup_runtime_enqueue,\n+\t .dispatch\t\t= (void *)cgroup_runtime_dispatch,\n+\t .tick\t\t\t= (void *)cgroup_runtime_tick,\n+\t .init\t\t\t= (void *)cgroup_runtime_init,\n+\t .cgroup_init\t\t= (void *)cgroup_runtime_cgroup_init,\n+\t .cgroup_set_bandwidth\t= (void *)cgroup_runtime_cgroup_set_bandwidth,\n+\t .cgroup_set_runtime\t= (void *)cgroup_runtime_cgroup_set_runtime,\n+\t .exit\t\t\t= (void *)cgroup_runtime_exit,\n+\t .flags\t\t\t= SCX_OPS_ENQ_LAST |\n+\t\t\t\t\t SCX_OPS_CHARGE_CPU_MAX,\n+\t .name\t\t\t= \"cgroup_runtime_full\");\ndiff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.c b/tools/testing/selftests/sched_ext/cgroup_runtime.c\nnew file mode 100644\nindex 00000000000000..86d50a63a6e738\n--- /dev/null\n+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.c\n@@ -0,0 +1,652 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Verify that a BPF scheduler with SCX_OPS_CHARGE_CPU_MAX shares a cgroup's\n+ * cpu.max quota with the fair class: what the cgroup's tasks run in both\n+ * classes, with and without SCX_OPS_SWITCH_PARTIAL and while tasks switch\n+ * class, stays within the quota; nothing is gained or lost when the\n+ * scheduler loads and unloads; and a scheduler that ignores\n+ * scx_bpf_task_cpu_max_runtime() leaves the fair tasks at most a quota of\n+ * debt and a slice per CPU, while one that stops tasks late pays the overrun\n+ * back.\n+ * Also verify that cpu.max and cpu.max.runtime writes reach the scheduler\n+ * in the order the fair class applied them.\n+ *\n+ * Usage is cpu.stat's usage_usec. A window of n periods may hold n + 1\n+ * refills and start or end with up to a quota, and each CPU may hold up to\n+ * a slice (sched_cfs_bandwidth_slice_us), so the checks allow that.\n+ */\n+\n+#define _GNU_SOURCE\n+#include \u003cbpf/bpf.h\u003e\n+#include \u003cerrno.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003climits.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003cpthread.h\u003e\n+#include \u003csched.h\u003e\n+#include \u003cscx/common.h\u003e\n+#include \u003csignal.h\u003e\n+#include \u003cstdarg.h\u003e\n+#include \u003cstdbool.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003csys/wait.h\u003e\n+#include \u003ctime.h\u003e\n+#include \u003cunistd.h\u003e\n+\n+#include \"cgroup_runtime.bpf.skel.h\"\n+#include \"cgroup_util.h\"\n+#include \"scx_test.h\"\n+\n+#ifndef SCHED_EXT\n+#define SCHED_EXT\t7\n+#endif\n+\n+#define PERIOD_US\t100000LL\n+#define QUOTA_US\t20000LL\n+#define NR_PERIODS\t10\n+#define NR_BURNERS\t2\n+\n+struct ctx {\n+\tstruct cgroup_runtime *skel;\n+\tstruct bpf_link *link;\n+\tchar root[PATH_MAX];\n+\tchar parent[PATH_MAX];\n+\tchar cg[PATH_MAX];\n+\tbool parent_created;\n+\tbool cg_created;\n+\tpid_t burner[NR_BURNERS];\n+\tlong long slice_us;\n+\tlong long saved_slice_us;\n+};\n+\n+static int join_path(char *dst, size_t dst_size, const char *parent, const char *name)\n+{\n+\tint ret;\n+\n+\tret = snprintf(dst, dst_size, \"%s/%s\", parent, name);\n+\tif (ret \u003c 0 || (size_t)ret \u003e= dst_size)\n+\t\treturn -ENAMETOOLONG;\n+\treturn 0;\n+}\n+\n+static u64 now_us(void)\n+{\n+\tstruct timespec ts;\n+\n+\tclock_gettime(CLOCK_MONOTONIC, \u0026ts);\n+\treturn ts.tv_sec * 1000000ULL + ts.tv_nsec / 1000;\n+}\n+\n+static u64 cgroup_id(const char *path)\n+{\n+\tunion {\n+\t\tu64 id;\n+\t\tunsigned char bytes[8];\n+\t} id = {};\n+\tstruct file_handle *handle;\n+\tint mount_id, ret;\n+\n+\thandle = calloc(1, sizeof(*handle) + sizeof(id));\n+\tif (!handle)\n+\t\treturn 0;\n+\thandle-\u003ehandle_bytes = sizeof(id);\n+\tret = name_to_handle_at(AT_FDCWD, path, handle, \u0026mount_id, 0);\n+\tif (!ret \u0026\u0026 handle-\u003ehandle_bytes == sizeof(id))\n+\t\tmemcpy(id.bytes, handle-\u003ef_handle, sizeof(id));\n+\tfree(handle);\n+\n+\treturn ret ? 0 : id.id;\n+}\n+\n+static long long read_runtime(struct ctx *ctx)\n+{\n+\treturn cg_read_long(ctx-\u003ecg, \"cpu.max.runtime\");\n+}\n+\n+static long long read_usage(struct ctx *ctx)\n+{\n+\treturn cg_read_key_long(ctx-\u003ecg, \"cpu.stat\", \"usage_usec\");\n+}\n+\n+static int write_str(const char *cgroup, const char *file, const char *fmt, ...)\n+{\n+\tchar buf[64];\n+\tva_list ap;\n+\n+\tva_start(ap, fmt);\n+\tvsnprintf(buf, sizeof(buf), fmt, ap);\n+\tva_end(ap);\n+\treturn cg_write(cgroup, file, buf);\n+}\n+\n+static bool controller_enabled(const char *cgroup, const char *file, const char *controller)\n+{\n+\tchar buf[4096], *saveptr, *token;\n+\n+\tif (cg_read(cgroup, file, buf, sizeof(buf)))\n+\t\treturn false;\n+\tfor (token = strtok_r(buf, \"\\n \", \u0026saveptr); token;\n+\t token = strtok_r(NULL, \"\\n \", \u0026saveptr))\n+\t\tif (!strcmp(token, controller))\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+static int set_policy(pid_t pid, int policy)\n+{\n+\tstruct sched_param param = {};\n+\n+\treturn sched_setscheduler(pid, policy, \u0026param);\n+}\n+\n+static void stop_burners(struct ctx *ctx)\n+{\n+\tint i;\n+\n+\tfor (i = 0; i \u003c NR_BURNERS; i++) {\n+\t\tif (ctx-\u003eburner[i] \u003c= 0)\n+\t\t\tcontinue;\n+\t\tkill(ctx-\u003eburner[i], SIGKILL);\n+\t\twaitpid(ctx-\u003eburner[i], NULL, 0);\n+\t\tctx-\u003eburner[i] = 0;\n+\t}\n+}\n+\n+/* a task in @ctx-\u003ecg that spins on CPU @i + 1 under @policy */\n+static int start_burner(struct ctx *ctx, int i, int policy)\n+{\n+\tcpu_set_t set;\n+\tpid_t pid;\n+\n+\tpid = fork();\n+\tif (pid \u003c 0)\n+\t\treturn -errno;\n+\tif (!pid)\n+\t\tfor (;;)\n+\t\t\t;\n+\n+\tctx-\u003eburner[i] = pid;\n+\tCPU_ZERO(\u0026set);\n+\tCPU_SET((i + 1) % libbpf_num_possible_cpus(), \u0026set);\n+\tif (sched_setaffinity(pid, sizeof(set), \u0026set) ||\n+\t cg_enter(ctx-\u003ecg, pid) || set_policy(pid, policy))\n+\t\treturn -1;\n+\treturn 0;\n+}\n+\n+static void cleanup(void *arg)\n+{\n+\tstruct ctx *ctx = arg;\n+\n+\tif (!ctx)\n+\t\treturn;\n+\tstop_burners(ctx);\n+\tbpf_link__destroy(ctx-\u003elink);\n+\tcgroup_runtime__destroy(ctx-\u003eskel);\n+\tif (ctx-\u003esaved_slice_us)\n+\t\twrite_str(\"/proc/sys/kernel\", \"sched_cfs_bandwidth_slice_us\", \"%lld\",\n+\t\t\t ctx-\u003esaved_slice_us);\n+\tif (ctx-\u003ecg_created)\n+\t\tcg_destroy(ctx-\u003ecg);\n+\tif (ctx-\u003eparent_created)\n+\t\tcg_destroy(ctx-\u003eparent);\n+\tfree(ctx);\n+}\n+\n+/*\n+ * Open the skeleton and make parent/cg under the cgroup2 root, with a quota\n+ * of @quota us per @period us, a burst of @burst us and a runtime of\n+ * @runtime us on cg.\n+ */\n+static enum scx_test_status setup_ctx(void **ctxp, long long quota,\n+\t\t\t\t long long period, long long burst,\n+\t\t\t\t long long runtime)\n+{\n+\tstruct ctx *ctx;\n+\tchar name[64];\n+\n+\tctx = calloc(1, sizeof(*ctx));\n+\tif (!ctx)\n+\t\treturn SCX_TEST_FAIL;\n+\t*ctxp = ctx;\n+\n+\t/* SCX_ENUM_INIT() exits if vmlinux BTF can't be loaded: before cgroups */\n+\tctx-\u003eskel = cgroup_runtime__open();\n+\tif (!ctx-\u003eskel) {\n+\t\tSCX_ERR(\"Failed to open skel\");\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\tSCX_ENUM_INIT(ctx-\u003eskel);\n+\n+\tctx-\u003eslice_us = 5000;\n+\tif (!access(\"/proc/sys/kernel/sched_cfs_bandwidth_slice_us\", R_OK))\n+\t\tctx-\u003eslice_us = cg_read_long(\"/proc/sys/kernel\",\n+\t\t\t\t\t \"sched_cfs_bandwidth_slice_us\");\n+\n+\tif (cg_find_unified_root(ctx-\u003eroot, sizeof(ctx-\u003eroot), NULL))\n+\t\treturn SCX_TEST_SKIP;\n+\tif (!controller_enabled(ctx-\u003eroot, \"cgroup.subtree_control\", \"cpu\") \u0026\u0026\n+\t cg_write(ctx-\u003eroot, \"cgroup.subtree_control\", \"+cpu\"))\n+\t\treturn SCX_TEST_SKIP;\n+\n+\tsnprintf(name, sizeof(name), \"scx_cgroup_runtime_%d\", getpid());\n+\tif (join_path(ctx-\u003eparent, sizeof(ctx-\u003eparent), ctx-\u003eroot, name) ||\n+\t join_path(ctx-\u003ecg, sizeof(ctx-\u003ecg), ctx-\u003eparent, \"cg\")) {\n+\t\tSCX_ERR(\"Cgroup path is too long\");\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\n+\tif (cg_create(ctx-\u003eparent)) {\n+\t\tSCX_ERR(\"Failed to create %s\", ctx-\u003eparent);\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\tctx-\u003eparent_created = true;\n+\tif (cg_write(ctx-\u003eparent, \"cgroup.subtree_control\", \"+cpu\")) {\n+\t\tSCX_ERR(\"Failed to enable cpu in %s\", ctx-\u003eparent);\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\tif (cg_create(ctx-\u003ecg)) {\n+\t\tSCX_ERR(\"Failed to create %s\", ctx-\u003ecg);\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\tctx-\u003ecg_created = true;\n+\n+\tif (access(cg_control(ctx-\u003ecg, \"cpu.max.runtime\"), F_OK))\n+\t\treturn SCX_TEST_SKIP;\n+\n+\tif (write_str(ctx-\u003ecg, \"cpu.max\", \"%lld %lld\", quota, period) ||\n+\t write_str(ctx-\u003ecg, \"cpu.max.burst\", \"%lld\", burst) ||\n+\t write_str(ctx-\u003ecg, \"cpu.max.runtime\", \"%lld\", runtime)) {\n+\t\tSCX_ERR(\"Failed to configure %s\", ctx-\u003ecg);\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\n+\tctx-\u003eskel-\u003ebss-\u003ecgid = cgroup_id(ctx-\u003ecg);\n+\tif (!ctx-\u003eskel-\u003ebss-\u003ecgid) {\n+\t\tSCX_ERR(\"Failed to read the cgroup ID of %s\", ctx-\u003ecg);\n+\t\treturn SCX_TEST_FAIL;\n+\t}\n+\tif (libbpf_num_possible_cpus() \u003c NR_BURNERS + 1)\n+\t\treturn SCX_TEST_SKIP;\n+\treturn SCX_TEST_PASS;\n+}\n+\n+static enum scx_test_status setup_rate(void **ctxp)\n+{\n+\treturn setup_ctx(ctxp, QUOTA_US, PERIOD_US, 0, QUOTA_US);\n+}\n+\n+static enum scx_test_status attach_ops(struct ctx *ctx, bool partial)\n+{\n+\tctx-\u003elink = bpf_map__attach_struct_ops(partial ? ctx-\u003eskel-\u003emaps.partial_ops :\n+\t\t\t\t\t\t ctx-\u003eskel-\u003emaps.full_ops);\n+\tSCX_FAIL_IF(!ctx-\u003elink, \"Failed to attach scheduler\");\n+\treturn SCX_TEST_PASS;\n+}\n+\n+static enum scx_test_status load_ops(struct ctx *ctx, bool partial)\n+{\n+\tbpf_map__set_autoattach(ctx-\u003eskel-\u003emaps.partial_ops, false);\n+\tbpf_map__set_autoattach(ctx-\u003eskel-\u003emaps.full_ops, false);\n+\tSCX_FAIL_IF(cgroup_runtime__load(ctx-\u003eskel), \"Failed to load skel\");\n+\treturn attach_ops(ctx, partial);\n+}\n+\n+static void detach(struct ctx *ctx)\n+{\n+\tbpf_link__destroy(ctx-\u003elink);\n+\tctx-\u003elink = NULL;\n+}\n+\n+/*\n+ * Run two burners in cg under @policy[], the first switching class every\n+ * 7 ms if @toggle, and check that cg runs its quota per period, no more and\n+ * not much less.\n+ */\n+static enum scx_test_status run_rate(struct ctx *ctx, bool partial,\n+\t\t\t\t const int *policy, bool toggle)\n+{\n+\tlong long tol = NR_BURNERS * ctx-\u003eslice_us + QUOTA_US;\n+\tlong long used, u0;\n+\tbool ext = false;\n+\tu64 end;\n+\tint i;\n+\n+\tif (load_ops(ctx, partial))\n+\t\treturn SCX_TEST_FAIL;\n+\tfor (i = 0; i \u003c NR_BURNERS; i++)\n+\t\tSCX_EQ(start_burner(ctx, i, policy[i]), 0);\n+\n+\tusleep(3 * PERIOD_US);\n+\tu0 = read_usage(ctx);\n+\tend = now_us() + NR_PERIODS * PERIOD_US;\n+\twhile (now_us() \u003c end) {\n+\t\tif (toggle) {\n+\t\t\text = !ext;\n+\t\t\tSCX_EQ(set_policy(ctx-\u003eburner[0], ext ? SCHED_EXT : SCHED_OTHER), 0);\n+\t\t}\n+\t\tusleep(7000);\n+\t}\n+\tused = read_usage(ctx) - u0;\n+\tstop_burners(ctx);\n+\n+\tprintf(\"ran %lld us in %d periods of quota %lld us, %lu held\\n\",\n+\t used, NR_PERIODS, QUOTA_US, (unsigned long)ctx-\u003eskel-\u003ebss-\u003enr_held);\n+\tSCX_GE(used, QUOTA_US * NR_PERIODS - tol);\n+\tSCX_LE(used, QUOTA_US * NR_PERIODS + tol);\n+\tSCX_ASSERT_ALIVE(ctx-\u003eskel, uei);\n+\treturn SCX_TEST_PASS;\n+}\n+\n+static enum scx_test_status run_full(void *arg)\n+{\n+\tstatic const int policy[] = { SCHED_OTHER, SCHED_OTHER };\n+\n+\treturn run_rate(arg, false, policy, false);\n+}\n+\n+static enum scx_test_status run_partial_ext(void *arg)\n+{\n+\tstatic const int policy[] = { SCHED_EXT, SCHED_EXT };\n+\n+\treturn run_rate(arg, true, policy, false);\n+}\n+\n+static enum scx_test_status run_partial_fair(void *arg)\n+{\n+\tstatic const int policy[] = { SCHED_OTHER, SCHED_OTHER };\n+\n+\treturn run_rate(arg, true, policy, false);\n+}\n+\n+static enum scx_test_status run_partial_mixed(void *arg)\n+{\n+\tstatic const int policy[] = { SCHED_EXT, SCHED_OTHER };\n+\n+\treturn run_rate(arg, true, policy, false);\n+}\n+\n+static enum scx_test_status run_switch(void *arg)\n+{\n+\tstatic const int policy[] = { SCHED_OTHER, SCHED_EXT };\n+\n+\treturn run_rate(arg, true, policy, true);\n+}\n+\n+/*\n+ * With a quota of 1 ms per second and a runtime of 3 s, what cg runs while\n+ * the scheduler loads, runs and unloads is what its runtime loses, up to a\n+ * slice per CPU and the few refills.\n+ */\n+#define LU_QUOTA_US\t1000LL\n+#define LU_PERIOD_US\t1000000LL\n+\n+static enum scx_test_status setup_load_unload(void **ctxp)\n+{\n+\treturn setup_ctx(ctxp, LU_QUOTA_US, LU_PERIOD_US, 4000000, 3000000);\n+}\n+\n+static enum scx_test_status run_load_unload(void *arg)\n+{\n+\tstruct ctx *ctx = arg;\n+\tlong long r0, u0, drawn, used, refills, tol;\n+\tu64 t0, t1;\n+\tint i;\n+\n+\tbpf_map__set_autoattach(ctx-\u003eskel-\u003emaps.partial_ops, false);\n+\tbpf_map__set_autoattach(ctx-\u003eskel-\u003emaps.full_ops, false);\n+\tSCX_FAIL_IF(cgroup_runtime__load(ctx-\u003eskel), \"Failed to load skel\");\n+\n+\tt0 = now_us();\n+\tr0 = read_runtime(ctx);\n+\tu0 = read_usage(ctx);\n+\tfor (i = 0; i \u003c NR_BURNERS; i++)\n+\t\tSCX_EQ(start_burner(ctx, i, SCHED_OTHER), 0);\n+\tusleep(100000);\n+\tif (attach_ops(ctx, false))\n+\t\treturn SCX_TEST_FAIL;\n+\tusleep(200000);\n+\tdetach(ctx);\n+\tusleep(100000);\n+\tstop_burners(ctx);\n+\tdrawn = r0 - read_runtime(ctx);\n+\tused = read_usage(ctx) - u0;\n+\tt1 = now_us();\n+\n+\trefills = LU_QUOTA_US * ((t1 - t0) / LU_PERIOD_US + 2);\n+\ttol = NR_BURNERS * ctx-\u003eslice_us;\n+\tprintf(\"ran %lld us, runtime down %lld us\\n\", used, drawn);\n+\tSCX_GE(used, 300000);\n+\tSCX_GE(used, drawn - tol);\n+\tSCX_LE(used, drawn + refills + tol);\n+\treturn SCX_TEST_PASS;\n+}\n+\n+/*\n+ * A scheduler that ignores scx_bpf_task_cpu_max_runtime() runs a task far\n+ * past the quota. Once the task is back on the fair class, it runs its quota\n+ * again, less at most a quota and a slice of debt.\n+ */\n+static enum scx_test_status run_clamp(void *arg)\n+{\n+\tstruct ctx *ctx = arg;\n+\tlong long u0, ignored, used;\n+\n+\tctx-\u003eskel-\u003ebss-\u003eignore_runtime = true;\n+\tif (load_ops(ctx, true))\n+\t\treturn SCX_TEST_FAIL;\n+\tSCX_EQ(start_burner(ctx, 0, SCHED_EXT), 0);\n+\n+\tu0 = read_usage(ctx);\n+\tusleep(5 * PERIOD_US);\n+\tignored = read_usage(ctx) - u0;\n+\n+\tSCX_EQ(set_policy(ctx-\u003eburner[0], SCHED_OTHER), 0);\n+\tu0 = read_usage(ctx);\n+\tusleep(5 * PERIOD_US);\n+\tused = read_usage(ctx) - u0;\n+\tstop_burners(ctx);\n+\n+\tprintf(\"ran %lld us ignoring the quota, then %lld us on the fair class\\n\",\n+\t ignored, used);\n+\tSCX_GE(ignored, 4 * PERIOD_US);\n+\tSCX_GE(used, 4 * QUOTA_US - 2 * ctx-\u003eslice_us);\n+\tSCX_LE(used, 6 * QUOTA_US + ctx-\u003eslice_us);\n+\tSCX_ASSERT_ALIVE(ctx-\u003eskel, uei);\n+\treturn SCX_TEST_PASS;\n+}\n+\n+/*\n+ * The scheduler stops a task only at a tick, so each period it overruns a\n+ * quota of 2 ms by up to a tick. With a slice of 1 ms, the next tick's\n+ * charge takes the CPU past the -slice floor. The debt must still be paid\n+ * from the next periods, so over 100 periods cg runs its quota, with the\n+ * second burner moving between CPUs 2 and 3 every 7 ms.\n+ */\n+#define DEBT_QUOTA_US\t2000LL\n+#define DEBT_PERIOD_US\t10000LL\n+#define DEBT_PERIODS\t100\n+\n+static enum scx_test_status setup_debt(void **ctxp)\n+{\n+\tenum scx_test_status ret;\n+\tstruct ctx *ctx;\n+\n+\tret = setup_ctx(ctxp, DEBT_QUOTA_US, DEBT_PERIOD_US, 0, DEBT_QUOTA_US);\n+\tif (ret != SCX_TEST_PASS)\n+\t\treturn ret;\n+\tctx = *ctxp;\n+\tif (write_str(\"/proc/sys/kernel\", \"sched_cfs_bandwidth_slice_us\", \"1000\"))\n+\t\treturn SCX_TEST_SKIP;\n+\tctx-\u003esaved_slice_us = ctx-\u003eslice_us;\n+\tctx-\u003eslice_us = 1000;\n+\treturn SCX_TEST_PASS;\n+}\n+\n+static enum scx_test_status run_debt(void *arg)\n+{\n+\tstruct ctx *ctx = arg;\n+\tlong long tol = (NR_BURNERS + 1) * ctx-\u003eslice_us + DEBT_QUOTA_US;\n+\tlong long want = DEBT_QUOTA_US * DEBT_PERIODS;\n+\tlong long used, u0;\n+\tbool moved = false;\n+\tcpu_set_t set;\n+\tu64 end;\n+\tint i;\n+\n+\tif (libbpf_num_possible_cpus() \u003c 4)\n+\t\treturn SCX_TEST_SKIP;\n+\tif (load_ops(ctx, true))\n+\t\treturn SCX_TEST_FAIL;\n+\tfor (i = 0; i \u003c NR_BURNERS; i++)\n+\t\tSCX_EQ(start_burner(ctx, i, SCHED_EXT), 0);\n+\n+\tusleep(3 * DEBT_PERIOD_US);\n+\tu0 = read_usage(ctx);\n+\tend = now_us() + DEBT_PERIODS * DEBT_PERIOD_US;\n+\twhile (now_us() \u003c end) {\n+\t\tmoved = !moved;\n+\t\tCPU_ZERO(\u0026set);\n+\t\tCPU_SET(moved ? 3 : 2, \u0026set);\n+\t\tSCX_EQ(sched_setaffinity(ctx-\u003eburner[1], sizeof(set), \u0026set), 0);\n+\t\tusleep(7000);\n+\t}\n+\tused = read_usage(ctx) - u0;\n+\tstop_burners(ctx);\n+\n+\tprintf(\"ran %lld us in %d periods of quota %lld us\\n\", used,\n+\t DEBT_PERIODS, DEBT_QUOTA_US);\n+\tSCX_GE(used, want - tol);\n+\tSCX_LE(used, want + tol);\n+\tSCX_ASSERT_ALIVE(ctx-\u003eskel, uei);\n+\treturn SCX_TEST_PASS;\n+}\n+\n+/*\n+ * One thread alternates cpu.max between quotas of 100ms and 10ms, without a\n+ * burst, while another writes a runtime of 90ms, which only the first\n+ * allows. The scheduler must never get a runtime above the quota it was last\n+ * given, and must end with the quota cpu.max has.\n+ */\n+#define INTERLEAVE_US\t2000000ULL\n+\n+struct interleave {\n+\tstruct ctx *ctx;\n+\tlong nr_ok;\n+\tlong nr_einval;\n+\tlong nr_err;\n+};\n+\n+static void *interleave_quota(void *arg)\n+{\n+\tstruct interleave *il = arg;\n+\tu64 end = now_us() + INTERLEAVE_US;\n+\tbool high = false;\n+\n+\twhile (now_us() \u003c end) {\n+\t\tif (write_str(il-\u003ectx-\u003ecg, \"cpu.max\", \"%lld %lld\",\n+\t\t\t high ? 100000LL : 10000LL, 1000000LL))\n+\t\t\til-\u003enr_err++;\n+\t\telse\n+\t\t\til-\u003enr_ok++;\n+\t\thigh = !high;\n+\t}\n+\treturn NULL;\n+}\n+\n+static void *interleave_runtime(void *arg)\n+{\n+\tstruct interleave *il = arg;\n+\tu64 end = now_us() + INTERLEAVE_US;\n+\n+\twhile (now_us() \u003c end) {\n+\t\tint fd = cg_open(il-\u003ectx-\u003ecg, \"cpu.max.runtime\", O_WRONLY);\n+\n+\t\tif (fd \u003c 0) {\n+\t\t\til-\u003enr_err++;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (write(fd, \"90000\", 5) == 5)\n+\t\t\til-\u003enr_ok++;\n+\t\telse if (errno == EINVAL)\n+\t\t\til-\u003enr_einval++;\n+\t\telse\n+\t\t\til-\u003enr_err++;\n+\t\tclose(fd);\n+\t}\n+\treturn NULL;\n+}\n+\n+static enum scx_test_status setup_interleave(void **ctxp)\n+{\n+\treturn setup_ctx(ctxp, 100000, 1000000, 0, 100000);\n+}\n+\n+static enum scx_test_status run_interleave(void *arg)\n+{\n+\tstruct ctx *ctx = arg;\n+\tstruct interleave quota = { .ctx = ctx }, runtime = { .ctx = ctx };\n+\tpthread_t tq, tr;\n+\tchar buf[64];\n+\n+\tif (load_ops(ctx, true))\n+\t\treturn SCX_TEST_FAIL;\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003equota_us, 100000);\n+\n+\tSCX_EQ(pthread_create(\u0026tq, NULL, interleave_quota, \u0026quota), 0);\n+\tSCX_EQ(pthread_create(\u0026tr, NULL, interleave_runtime, \u0026runtime), 0);\n+\tpthread_join(tq, NULL);\n+\tpthread_join(tr, NULL);\n+\n+\tSCX_EQ(quota.nr_err, 0);\n+\tSCX_EQ(runtime.nr_err, 0);\n+\tSCX_GT(runtime.nr_ok, 0);\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003enr_bad_order, 0);\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003enr_set_bw, quota.nr_ok);\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003enr_set_runtime, runtime.nr_ok);\n+\n+\tSCX_EQ(cg_read(ctx-\u003ecg, \"cpu.max\", buf, sizeof(buf)), 0);\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003equota_us, atoll(buf));\n+\tSCX_EQ(ctx-\u003eskel-\u003ebss-\u003eburst_us, 0);\n+\n+\tprintf(\"cpu.max writes %ld, cpu.max.runtime writes %ld (%ld EINVAL)\\n\",\n+\t quota.nr_ok, runtime.nr_ok, runtime.nr_einval);\n+\tSCX_ASSERT_ALIVE(ctx-\u003eskel, uei);\n+\treturn SCX_TEST_PASS;\n+}\n+\n+#define RUNTIME_TEST(__name, __setup, __desc)\t\t\t\t\\\n+\tstruct scx_test cgroup_runtime_##__name = {\t\t\t\\\n+\t\t.name = \"cgroup_runtime_\" #__name,\t\t\t\\\n+\t\t.description = __desc,\t\t\t\t\t\\\n+\t\t.setup = __setup,\t\t\t\t\t\\\n+\t\t.run = run_##__name,\t\t\t\t\t\\\n+\t\t.cleanup = cleanup,\t\t\t\t\t\\\n+\t}\n+\n+RUNTIME_TEST(full, setup_rate, \"Without partial switch, the BPF scheduler's tasks run their quota\");\n+RUNTIME_TEST(partial_ext, setup_rate, \"SCHED_EXT tasks of a cgroup run its quota\");\n+RUNTIME_TEST(partial_fair, setup_rate, \"Fair tasks of a cgroup run its quota\");\n+RUNTIME_TEST(partial_mixed, setup_rate, \"Fair and SCHED_EXT tasks of a cgroup share its quota\");\n+RUNTIME_TEST(switch, setup_rate, \"A task switching class every 7 ms stays within the quota\");\n+RUNTIME_TEST(load_unload, setup_load_unload, \"Load and unload neither gain nor lose runtime\");\n+RUNTIME_TEST(clamp, setup_rate, \"A scheduler ignoring the quota leaves a bounded debt\");\n+RUNTIME_TEST(debt, setup_debt, \"Debt past a quota is paid in the next periods\");\n+RUNTIME_TEST(interleave, setup_interleave, \"cpu.max writes reach the scheduler in order\");\n+\n+/* REGISTER_SCX_TEST() can be used once per file */\n+__attribute__((constructor))\n+static void register_cgroup_runtime_tests(void)\n+{\n+\tscx_test_register(\u0026cgroup_runtime_full);\n+\tscx_test_register(\u0026cgroup_runtime_partial_ext);\n+\tscx_test_register(\u0026cgroup_runtime_partial_fair);\n+\tscx_test_register(\u0026cgroup_runtime_partial_mixed);\n+\tscx_test_register(\u0026cgroup_runtime_switch);\n+\tscx_test_register(\u0026cgroup_runtime_load_unload);\n+\tscx_test_register(\u0026cgroup_runtime_clamp);\n+\tscx_test_register(\u0026cgroup_runtime_debt);\n+\tscx_test_register(\u0026cgroup_runtime_interleave);\n+}\ndiff --git a/tools/testing/selftests/sched_ext/config b/tools/testing/selftests/sched_ext/config\nindex 8173f9170ffe89..495b140403a18e 100644\n--- a/tools/testing/selftests/sched_ext/config\n+++ b/tools/testing/selftests/sched_ext/config\n@@ -9,3 +9,4 @@ CONFIG_DEBUG_INFO=y\n CONFIG_DEBUG_INFO_BTF=y\n CONFIG_EXPERT=y\n CONFIG_SCHED_PROXY_EXEC=y\n+CONFIG_CFS_BANDWIDTH=y\n"
} |
| 2/1 | 2026/11/13 14:16 | agent | patch-evaluator |
5mModel:core Args: null Results: {
"EnableConfigs": [
"CFS_BANDWIDTH",
"CGROUP_SCHED",
"FAIR_GROUP_SCHED",
"SCHED_CLASS_EXT"
],
"FocusSymbols": [
"cfs_bandwidth_set_runtime",
"cfs_bandwidth_get_runtime",
"cfs_bandwidth_refill_idle_periods",
"cfs_bandwidth_charge_task",
"cfs_bandwidth_return_task",
"cfs_bandwidth_task_runtime",
"scx_group_set_runtime",
"scx_bpf_task_cpu_max_runtime",
"cpu_runtime_write_u64"
],
"Reasoning": "The patch introduces the cpu.max.runtime cgroup interface to allow reading and setting accumulated CPU runtime, changes burst bandwidth constraints, and integrates CFS bandwidth tracking with the sched_ext extensible scheduler class (including quota sharing, runtime debt tracking, and BPF kfuncs). These modifications affect core scheduler logic and cgroup control interfaces reachable from userspace in standard virtualized environments.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d396475ecb337400ea2d7b99b7b993e3680b5228
Author: syz-cluster <triage@syzkaller.com>
Date: Fri Nov 13 14:16:07 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 9e3c67b02ae2e1..db9fa6e6dbd49e 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1231,12 +1231,37 @@ will be referred to. All time durations are in microseconds.
A read-write single value file which exists on non-root
cgroups. The default is "0".
- The burst in the range [0, $MAX].
+ The burst. The cgroup can accumulate the runtime it does not
+ use, up to $MAX + cpu.max.burst, also in the periods in which it
+ does not run. The burst may exceed $MAX, as long as $MAX +
+ cpu.max.burst is at most 2^44 - 1 (about 203 days).
This file affects only processes under the fair-class scheduler and a BPF
scheduler with the ``cgroup_set_bandwidth`` callback depending on what
the callback actually does.
+ cpu.max.runtime
+ A read-write single value file which exists on non-root
+ cgroups if the kernel is built with CONFIG_CFS_BANDWIDTH.
+
+ The runtime the cgroup has accumulated and not used yet, in
+ microseconds. Each period refills it by $MAX, up to $MAX +
+ cpu.max.burst, whether the cgroup runs in it or not. A read
+ returns at most $MAX + cpu.max.burst. A write sets it, up to
+ $MAX + cpu.max.burst, and lets a cgroup that ran out of runtime
+ run again at once. A write fails with EINVAL while $MAX is
+ "max".
+
+ The runtime does not include what the cgroup's CPUs already took
+ from it, at most a slice each (sched_cfs_bandwidth_slice_us).
+ A write leaves that with the CPUs.
+
+ This file affects only processes under the fair-class scheduler and a BPF
+ scheduler with the ``cgroup_set_runtime`` callback depending on what
+ the callback actually does. A BPF scheduler with the
+ ``SCX_OPS_CHARGE_CPU_MAX`` flag draws what its processes run from
+ the same runtime, so the cgroup's processes in both share it.
+
cpu.pressure
A read-write nested-keyed file.
diff --git a/Documentation/scheduler/sched-bwc.rst b/Documentation/scheduler/sched-bwc.rst
index e881a945c1888e..ccf7434ca73f0a 100644
--- a/Documentation/scheduler/sched-bwc.rst
+++ b/Documentation/scheduler/sched-bwc.rst
@@ -90,8 +90,8 @@ bandwidth restriction in place, such a group is described as an unconstrained
bandwidth group. This represents the traditional work-conserving behavior for
CFS.
-Writing any (valid) positive value(s) no smaller than cpu.cfs_burst_us will
-enact the specified bandwidth limit. The minimum quota allowed for the quota or
+Writing any (valid) positive value(s) will enact the specified bandwidth
+limit. The minimum quota allowed for the quota or
period is 1ms. There is also an upper bound on the period length of 1s.
Additional restrictions exist when bandwidth limits are used in a hierarchical
fashion, these are explained in more detail below.
@@ -101,9 +101,11 @@ and return the group to an unconstrained state once more.
A value of 0 for cpu.cfs_burst_us indicates that the group can not accumulate
any unused bandwidth. It makes the traditional bandwidth control behavior for
-CFS unchanged. Writing any (valid) positive value(s) no larger than
-cpu.cfs_quota_us into cpu.cfs_burst_us will enact the cap on unused bandwidth
-accumulation.
+CFS unchanged. Writing any (valid) positive value(s) into cpu.cfs_burst_us
+will enact the cap on unused bandwidth accumulation: the group can accumulate
+up to cpu.cfs_quota_us + cpu.cfs_burst_us, also over periods in which it does
+not run. The burst may be larger than the quota, as long as their sum is at
+most 2^44 - 1 microseconds (about 203 days).
Any updates to a group's bandwidth specification will result in it becoming
unthrottled if it is in a constrained state.
@@ -243,4 +245,4 @@ Examples
# echo 50000 > cpu.cfs_period_us /* period = 50ms */
# echo 10000 > cpu.cfs_burst_us /* burst = 10ms */
- Larger buffer setting (no larger than quota) allows greater burst capacity.
+ Larger buffer setting allows greater burst capacity.
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 175b52a7ea7938..25a4acb72106c7 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -9856,6 +9856,12 @@ static int tg_set_cfs_bandwidth(struct task_group *tg,
cfs_bandwidth_usage_inc();
scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
+ /*
+ * The new bandwidth applies from now on. The group keeps what
+ * it earned while idle under the old one.
+ */
+ cfs_bandwidth_refill_idle_periods(cfs_b);
+
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
cfs_b->burst = burst;
@@ -10093,6 +10099,14 @@ static u64 cpu_period_read_u64(struct cgroup_subsys_state *css,
return period_us;
}
+/*
+ * Held across a bandwidth or runtime write and the sched_ext callback that
+ * follows it, so that the BPF scheduler gets the writes in the order the fair
+ * class applied them. The callback runs after the fair class's update has
+ * dropped cpus_read_lock() and cfs_constraints_mutex.
+ */
+static DEFINE_MUTEX(tg_bandwidth_mutex);
+
static int tg_set_bandwidth(struct task_group *tg,
u64 period_us, u64 quota_us, u64 burst_us)
{
@@ -10131,10 +10145,11 @@ static int tg_set_bandwidth(struct task_group *tg,
if (quota_us != RUNTIME_INF && quota_us > max_bw_runtime_us)
return -EINVAL;
- if (quota_us != RUNTIME_INF && (burst_us > quota_us ||
- burst_us + quota_us > max_bw_runtime_us))
+ if (quota_us != RUNTIME_INF && burst_us > max_bw_runtime_us - quota_us)
return -EINVAL;
+ guard(mutex)(&tg_bandwidth_mutex);
+
#ifdef CONFIG_CFS_BANDWIDTH
ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us);
#endif /* CONFIG_CFS_BANDWIDTH */
@@ -10193,6 +10208,40 @@ static int cpu_burst_write_u64(struct cgroup_subsys_state *css,
tg_bandwidth(tg, &period_us, "a_us, NULL);
return tg_set_bandwidth(tg, period_us, quota_us, burst_us);
}
+
+#ifdef CONFIG_CFS_BANDWIDTH
+static int cpu_runtime_write_u64(struct cgroup_subsys_state *css,
+ struct cftype *cftype, u64 runtime_us)
+{
+ struct task_group *tg = css_tg(css);
+ int ret;
+
+ if (runtime_us > max_bw_runtime_us)
+ return -EINVAL;
+
+ /*
+ * Serialize against tg_set_bandwidth(), so that the BPF scheduler gets
+ * the runtime checked against the current quota + burst, and this and
+ * cpu.max writes reach it in the order the fair class took them.
+ */
+ guard(mutex)(&tg_bandwidth_mutex);
+
+ ret = cfs_bandwidth_set_runtime(&tg->cfs_bandwidth,
+ runtime_us * NSEC_PER_USEC);
+ if (!ret)
+ scx_group_set_runtime(tg, runtime_us);
+ return ret;
+}
+
+static u64 cpu_runtime_read_u64(struct cgroup_subsys_state *css,
+ struct cftype *cftype)
+{
+ struct task_group *tg = css_tg(css);
+
+ return div_u64(cfs_bandwidth_get_runtime(&tg->cfs_bandwidth),
+ NSEC_PER_USEC);
+}
+#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_GROUP_SCHED_BANDWIDTH */
#ifdef CONFIG_RT_GROUP_SCHED
@@ -10544,7 +10593,15 @@ static struct cftype cpu_files[] = {
.read_u64 = cpu_burst_read_u64,
.write_u64 = cpu_burst_write_u64,
},
+#ifdef CONFIG_CFS_BANDWIDTH
+ {
+ .name = "max.runtime",
+ .flags = CFTYPE_NOT_ON_ROOT,
+ .read_u64 = cpu_runtime_read_u64,
+ .write_u64 = cpu_runtime_write_u64,
+ },
#endif /* CONFIG_CFS_BANDWIDTH */
+#endif /* CONFIG_GROUP_SCHED_BANDWIDTH */
#ifdef CONFIG_UCLAMP_TASK_GROUP
{
.name = "uclamp.min",
diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index ebdf7b91f9d370..6ffc9ca2c5c9f1 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -1625,6 +1625,11 @@ static void expire_task_slice(struct task_struct *p)
scx_set_task_slice(p, 0);
}
+static bool scx_task_charges_cpu_max(const struct task_struct *p)
+{
+ return scx_task_sched(p)->ops.flags & SCX_OPS_CHARGE_CPU_MAX;
+}
+
static void update_curr_scx(struct rq *rq)
{
struct task_struct *donor;
@@ -1650,6 +1655,9 @@ static void update_curr_scx(struct rq *rq)
if (unlikely(donor == scx_rescuee(rq)))
scx_rescue_charge(rq, delta_exec);
+ if (scx_task_charges_cpu_max(donor))
+ cfs_bandwidth_charge_task(rq, donor, delta_exec);
+
dl_server_update(&rq->ext_server, delta_exec);
}
@@ -2605,6 +2613,13 @@ static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_
ops_dequeue(rq, p, deq_flags);
+ /* charge what @p ran, then return what @rq holds for its cgroups */
+ if (scx_task_charges_cpu_max(p)) {
+ if (task_current_donor(rq, p))
+ update_curr_scx(rq);
+ cfs_bandwidth_return_task(rq, p);
+ }
+
/*
* A current scheduling context which is going off @rq first gets
* dequeued and then stops running. As we want running <-> stopping
@@ -5817,6 +5832,19 @@ void scx_group_set_bandwidth(struct task_group *tg,
percpu_up_read(&scx_cgroup_ops_rwsem);
}
+
+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us)
+{
+ struct scx_sched *sch;
+
+ percpu_down_read(&scx_cgroup_ops_rwsem);
+ sch = scx_tg_knob_sched(tg);
+
+ if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_runtime))
+ SCX_CALL_OP(sch, cgroup_set_runtime, NULL, tg_cgrp(tg), runtime_us);
+
+ percpu_up_read(&scx_cgroup_ops_rwsem);
+}
#endif /* CONFIG_EXT_GROUP_SCHED */
#if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
@@ -9230,6 +9258,7 @@ static int bpf_scx_check_member(const struct btf_type *t,
case offsetof(struct sched_ext_ops, cgroup_exit):
case offsetof(struct sched_ext_ops, cgroup_prep_move):
case offsetof(struct sched_ext_ops, cgroup_set_bandwidth):
+ case offsetof(struct sched_ext_ops, cgroup_set_runtime):
#endif
case offsetof(struct sched_ext_ops, cpu_online):
case offsetof(struct sched_ext_ops, cpu_offline):
@@ -9392,6 +9421,7 @@ static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgro
static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
+static void sched_ext_ops__cgroup_set_runtime(struct cgroup *cgrp, u64 runtime_us) {}
#endif /* CONFIG_EXT_GROUP_SCHED */
static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
@@ -9434,6 +9464,7 @@ static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
.cgroup_set_weight = sched_ext_ops__cgroup_set_weight,
.cgroup_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth,
.cgroup_set_idle = sched_ext_ops__cgroup_set_idle,
+ .cgroup_set_runtime = sched_ext_ops__cgroup_set_runtime,
#endif
.sub_attach = sched_ext_ops__sub_attach,
.sub_detach = sched_ext_ops__sub_detach,
@@ -9502,6 +9533,7 @@ static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
.cpuctl_set_weight = sched_ext_ops__cgroup_set_weight,
.cpuctl_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth,
.cpuctl_set_idle = sched_ext_ops__cgroup_set_idle,
+ .cpuctl_set_runtime = sched_ext_ops__cgroup_set_runtime,
#endif
.sub_attach = sched_ext_ops__sub_attach,
.sub_detach = sched_ext_ops__sub_detach,
@@ -11776,6 +11808,24 @@ __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
return task_cpu(p);
}
+/**
+ * scx_bpf_task_cpu_max_runtime - Runtime a task has left under cpu.max
+ * @p: task of interest
+ *
+ * Return the runtime in nsecs that @p's cgroup and its ancestors have left
+ * under their cpu.max quotas for @p on its current CPU, the least over those
+ * with a quota: the cgroup's cpu.max.runtime plus what the CPU holds for
+ * the cgroup, less what it owes. U64_MAX if none limits it. Read without
+ * locks.
+ *
+ * With %SCX_OPS_CHARGE_CPU_MAX, the scheduler should run @p only while this
+ * returns more than 0. The runtime grows when a period refills it.
+ */
+__bpf_kfunc u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p)
+{
+ return cfs_bandwidth_task_runtime(p);
+}
+
/**
* scx_bpf_task_cid - cid a task is currently associated with
* @p: task of interest
@@ -12102,6 +12152,7 @@ BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
+BTF_ID_FLAGS(func, scx_bpf_task_cpu_max_runtime, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
@@ -12226,6 +12277,7 @@ static const u32 scx_kf_allow_flags[] = {
[SCX_OP_IDX(cgroup_set_weight)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(cgroup_set_idle)] = SCX_KF_ALLOW_UNLOCKED,
+ [SCX_OP_IDX(cgroup_set_runtime)] = SCX_KF_ALLOW_UNLOCKED,
#endif /* CONFIG_EXT_GROUP_SCHED */
[SCX_OP_IDX(sub_attach)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(sub_detach)] = SCX_KF_ALLOW_UNLOCKED,
@@ -12395,6 +12447,7 @@ static int __init scx_init(void)
CID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight);
CID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth);
CID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle);
+ CID_OFFSET_MATCH(cgroup_set_runtime, cpuctl_set_runtime);
#endif
/* @priv tail must align since both share the same data block */
CID_OFFSET_MATCH(priv, priv);
diff --git a/kernel/sched/ext/ext.h b/kernel/sched/ext/ext.h
index d32bc01071b01a..6d1ce582bf7240 100644
--- a/kernel/sched/ext/ext.h
+++ b/kernel/sched/ext/ext.h
@@ -94,6 +94,7 @@ void scx_cgroup_cancel_attach(struct cgroup_taskset *tset);
void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight);
void scx_group_set_idle(struct task_group *tg, bool idle);
void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us);
+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us);
#else /* CONFIG_EXT_GROUP_SCHED */
static inline void scx_tg_init(struct task_group *tg) {}
static inline int scx_tg_online(struct task_group *tg) { return 0; }
@@ -104,5 +105,6 @@ static inline void scx_cgroup_cancel_attach(struct cgroup_taskset *tset) {}
static inline void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight) {}
static inline void scx_group_set_idle(struct task_group *tg, bool idle) {}
static inline void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us) {}
+static inline void scx_group_set_runtime(struct task_group *tg, u64 runtime_us) {}
#endif /* CONFIG_EXT_GROUP_SCHED */
#endif /* CONFIG_CGROUP_SCHED */
diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h
index ff0a3d508533f0..e8c0b573d0a434 100644
--- a/kernel/sched/ext/internal.h
+++ b/kernel/sched/ext/internal.h
@@ -243,6 +243,27 @@ enum scx_ops_flags {
*/
SCX_OPS_ENQ_BLOCKED = 1LLU << 10,
+ /*
+ * If set, what the scheduler's tasks run is charged to the cpu.max
+ * bandwidth of their cgroups, the runtime the fair class keeps and
+ * cpu.max.runtime reads, as what fair tasks run is. The tasks of a
+ * cgroup in both classes then share one quota, also with
+ * %SCX_OPS_SWITCH_PARTIAL, and nothing is handed over when tasks
+ * switch class.
+ *
+ * The kernel never throttles the scheduler's tasks. The scheduler
+ * enforces the quota by running a task only while
+ * scx_bpf_task_cpu_max_runtime() returns more than 0. What a task runs
+ * beyond that is charged: up to a slice (sched_cfs_bandwidth_slice_us)
+ * per CPU as a debt the cgroup's fair tasks on that CPU pay back, and up
+ * to a quota more from the cgroup's next period. The scheduler does not
+ * need ops.cgroup_set_runtime(), as a write of cpu.max.runtime sets that
+ * runtime.
+ *
+ * Without CONFIG_CFS_BANDWIDTH, this flag has no effect.
+ */
+ SCX_OPS_CHARGE_CPU_MAX = 1LLU << 11,
+
SCX_OPS_ALL_FLAGS = SCX_OPS_KEEP_BUILTIN_IDLE |
SCX_OPS_ENQ_LAST |
SCX_OPS_ENQ_EXITING |
@@ -253,7 +274,8 @@ enum scx_ops_flags {
SCX_OPS_ALWAYS_ENQ_IMMED |
SCX_OPS_TID_TO_TASK |
SCX_OPS_LAZY_RESCHED |
- SCX_OPS_ENQ_BLOCKED,
+ SCX_OPS_ENQ_BLOCKED |
+ SCX_OPS_CHARGE_CPU_MAX,
/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
__SCX_OPS_INTERNAL_MASK = 0xffLLU << 56,
@@ -863,6 +885,26 @@ struct sched_ext_ops {
*/
void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
+ /**
+ * @cgroup_set_runtime: A cgroup's runtime is being set
+ * @cgrp: cgroup whose runtime is being set
+ * @runtime_us: runtime in microseconds
+ *
+ * Set the runtime @cgrp has accumulated and not used yet to
+ * @runtime_us. This is from the cpu.max.runtime cgroup interface,
+ * which exists with CONFIG_CFS_BANDWIDTH only. It is called on every
+ * write, also of an unchanged value. The runtime goes down as @cgrp
+ * runs, so a write of the same value is a top-up.
+ *
+ * @cgrp has a quota, and @runtime_us is at most the quota + burst the
+ * scheduler was last given, by @cgroup_init or @cgroup_set_bandwidth:
+ * cpu.max and cpu.max.runtime writes reach the scheduler in the order
+ * the fair class applied them.
+ *
+ * Delivery follows the same rule as cgroup_set_weight().
+ */
+ void (*cgroup_set_runtime)(struct cgroup *cgrp, u64 runtime_us);
+
#endif /* CONFIG_EXT_GROUP_SCHED */
/**
@@ -1239,6 +1281,7 @@ struct sched_ext_ops_cid {
void (*cpuctl_set_bandwidth)(struct cgroup *cgrp, u64 period_us, u64 quota_us,
u64 burst_us);
void (*cpuctl_set_idle)(struct cgroup *cgrp, bool idle);
+ void (*cpuctl_set_runtime)(struct cgroup *cgrp, u64 runtime_us);
#endif /* CONFIG_EXT_GROUP_SCHED */
s32 (*sub_attach)(struct scx_sub_attach_args *args);
void (*sub_detach)(struct scx_sub_detach_args *args);
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index d4cc0caee6265d..9ff239f122bdaa 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -6875,6 +6875,11 @@ void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
}
cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
+
+ /* pay the debt cfs_bandwidth_charge_task() left */
+ runtime = min(cfs_b->runtime, cfs_b->debt);
+ cfs_b->runtime -= runtime;
+ cfs_b->debt -= runtime;
cfs_b->runtime_snap = cfs_b->runtime;
}
@@ -7421,6 +7426,8 @@ static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
struct cfs_rq *cfs_rq;
struct rq *rq;
+ lockdep_assert_irqs_disabled();
+
guard(rcu)();
list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
@@ -7811,6 +7818,140 @@ static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
}
+/*
+ * Runtime after @periods refills of quota, capped at quota + burst as each
+ * refill in __refill_cfs_bandwidth_runtime() caps it. The runtime can be above
+ * the cap (__return_cfs_rq_runtime() does not cap it), and a refill then cuts
+ * it to the cap.
+ */
+static u64 cfs_bandwidth_refilled(struct cfs_bandwidth *cfs_b, u64 periods)
+{
+ u64 cap = cfs_b->quota + cfs_b->burst;
+ u64 runtime = cfs_b->runtime;
+
+ if (!periods || cfs_b->quota == RUNTIME_INF)
+ return runtime;
+ if (runtime >= cap ||
+ periods >= div64_u64(cap - runtime, cfs_b->quota) + 1)
+ return cap;
+ return runtime + periods * cfs_b->quota;
+}
+
+/*
+ * The period timer stops after a period in which the group took no runtime
+ * (do_sched_cfs_period_timer()), and start_cfs_bandwidth() restarts it on
+ * the next demand. The periods it slept through refill quota too: unused
+ * quota accumulates up to quota + burst whether or not the group ran. While
+ * the timer is stopped its expiry is the first period boundary it missed,
+ * so the boundaries passed since then are the refills still owed.
+ *
+ * Without burst the cap is quota. The timer stops right after a refill that
+ * nothing drew from, so the runtime is at quota then, and this changes nothing
+ * for groups without a burst.
+ *
+ * This is the overrun that hrtimer_forward_now() returns, without moving the
+ * expiry: one for the expiry itself, plus one for each full period since.
+ */
+static u64 cfs_bandwidth_idle_periods(struct cfs_bandwidth *cfs_b)
+{
+ ktime_t now = ktime_get();
+ s64 delta;
+
+ if (cfs_b->period_active)
+ return 0;
+
+ delta = ktime_to_ns(ktime_sub(now, hrtimer_get_expires(&cfs_b->period_timer)));
+ if (delta < 0)
+ return 0;
+ return div64_u64(delta, ktime_to_ns(cfs_b->period)) + 1;
+}
+
+/*
+ * Refill the periods a stopped timer slept through, at the bandwidth they
+ * were earned under, and move its expiry past them so that they are not
+ * counted again. A change of the bandwidth or a cpu.max.runtime write calls
+ * this first, so that the change applies from then on and the group keeps
+ * what it earned before. A group without a quota earned nothing.
+ */
+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b)
+{
+ u64 idle_periods;
+
+ lockdep_assert_held(&cfs_b->lock);
+
+ if (cfs_b->period_active)
+ return;
+
+ idle_periods = hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
+ cfs_b->runtime = cfs_bandwidth_refilled(cfs_b, idle_periods);
+ cfs_b->runtime_snap = cfs_b->runtime;
+}
+
+/*
+ * The runtime of @cfs_b, as cpu.max.runtime reads it.
+ *
+ * __return_cfs_rq_runtime() returns slack without capping it, so the runtime
+ * can exceed quota + burst until the next refill caps it. Report it capped,
+ * so that a value read can always be written back.
+ */
+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b)
+{
+ u64 runtime;
+
+ guard(raw_spinlock_irq)(&cfs_b->lock);
+
+ runtime = cfs_bandwidth_refilled(cfs_b, cfs_bandwidth_idle_periods(cfs_b));
+ if (cfs_b->quota != RUNTIME_INF)
+ runtime = min(runtime, cfs_b->quota + cfs_b->burst);
+
+ return runtime;
+}
+
+/*
+ * Set the runtime of @cfs_b, as a cpu.max.runtime write does, and hand it to
+ * the throttled cfs_rqs at once rather than at the next period.
+ */
+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime)
+{
+ bool throttled;
+ s64 snap;
+
+ guard(irq)();
+
+ scoped_guard (raw_spinlock, &cfs_b->lock) {
+ if (cfs_b->quota == RUNTIME_INF ||
+ runtime > cfs_b->quota + cfs_b->burst)
+ return -EINVAL;
+
+ /*
+ * Refill the periods that passed before the write, so that the
+ * write replaces them and only the periods after it refill.
+ */
+ cfs_bandwidth_refill_idle_periods(cfs_b);
+
+ /*
+ * The next refill counts runtime_snap - runtime as burst usage.
+ * Move runtime_snap by what the write adds or takes away, so
+ * that the write itself is not counted as burst usage but what
+ * the group ran since the last refill still is.
+ */
+ snap = cfs_b->runtime_snap + runtime - cfs_b->runtime;
+ cfs_b->runtime_snap = max(snap, 0);
+ cfs_b->runtime = runtime;
+
+ throttled = !list_empty(&cfs_b->throttled_cfs_rq) && runtime;
+ }
+
+ /*
+ * distribute_cfs_runtime() takes the rq locks, so it runs without
+ * cfs_b->lock and with interrupts disabled, as from the slack timer.
+ */
+ if (throttled)
+ distribute_cfs_runtime(cfs_b);
+
+ return 0;
+}
+
void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
{
lockdep_assert_held(&cfs_b->lock);
@@ -7818,8 +7959,8 @@ void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
if (cfs_b->period_active)
return;
+ cfs_bandwidth_refill_idle_periods(cfs_b);
cfs_b->period_active = 1;
- hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
}
@@ -7940,6 +8081,123 @@ bool cfs_task_bw_constrained(struct task_struct *p)
return false;
}
+/*
+ * Charge @delta_exec, which @p ran on @rq outside the fair class, to the
+ * bandwidth of its task group and of each ancestor with a quota, as
+ * account_cfs_rq_runtime() charges a fair task. A cfs_rq that runs out takes
+ * another slice from cfs_b, but @p is never throttled: the BPF scheduler that
+ * runs it stops it, and the group's fair tasks are throttled when they run.
+ *
+ * Debt below -slice that cfs_b cannot cover moves to cfs_b, up to a quota,
+ * and the next refill pays it, so that a scheduler which keeps running @p
+ * cannot put the group's fair tasks on @rq in more debt than a slice.
+ */
+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,
+ u64 delta_exec)
+{
+ s64 floor = -(s64)sched_cfs_bandwidth_slice();
+ struct task_group *tg;
+
+ lockdep_assert_rq_held(rq);
+
+ if (!cfs_bandwidth_used())
+ return;
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
+
+ if (!cfs_rq->runtime_enabled)
+ continue;
+
+ cfs_rq->runtime_remaining -= delta_exec;
+
+ /*
+ * A throttled cfs_rq gets runtime from distribute_cfs_runtime().
+ * Without runtime, an active period timer refills it, so skip
+ * the lock. A stopped one is restarted by the assign.
+ */
+ if (cfs_rq->runtime_remaining <= 0 && !cfs_rq->throttled &&
+ (READ_ONCE(cfs_b->runtime) || !READ_ONCE(cfs_b->period_active))) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ __assign_cfs_rq_runtime(cfs_b, cfs_rq,
+ sched_cfs_bandwidth_slice());
+ }
+
+ if (cfs_rq->runtime_remaining < floor) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ cfs_b->debt = min_t(u64, cfs_b->debt + floor -
+ cfs_rq->runtime_remaining, cfs_b->quota);
+ cfs_rq->runtime_remaining = floor;
+ }
+ }
+}
+
+/*
+ * @p leaves @rq: give the runtime @rq holds for its groups back, less
+ * min_cfs_rq_runtime, as a fair dequeue does when a cfs_rq empties. Pay
+ * what @rq owes from cfs_b, as @p may not run on @rq again.
+ */
+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p)
+{
+ struct task_group *tg;
+
+ lockdep_assert_rq_held(rq);
+
+ if (!cfs_bandwidth_used())
+ return;
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
+
+ return_cfs_rq_runtime(cfs_rq);
+
+ if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining < 0 &&
+ !cfs_rq->throttled && READ_ONCE(cfs_b->runtime)) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ __assign_cfs_rq_runtime(cfs_b, cfs_rq, 0);
+ }
+ }
+}
+
+/*
+ * The runtime @p's groups have left for it on its CPU, without locks: the
+ * least, over the groups with a quota, of what the CPU holds or owes and
+ * cfs_b's runtime. Debt counts up to a quota less 1ns, so that a full period
+ * lets @p run and pay the rest. A group whose period timer is stopped does
+ * not count, as the next charge restarts the timer and refills what it owes.
+ * RUNTIME_INF if no group counts.
+ */
+u64 cfs_bandwidth_task_runtime(struct task_struct *p)
+{
+ u64 runtime = RUNTIME_INF;
+ struct task_group *tg;
+ int cpu = task_cpu(p);
+
+ if (!cfs_bandwidth_used())
+ return runtime;
+
+ guard(rcu)();
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);
+ s64 held;
+
+ if (!READ_ONCE(cfs_rq->runtime_enabled) ||
+ !READ_ONCE(cfs_b->period_active))
+ continue;
+
+ held = max_t(s64, READ_ONCE(cfs_rq->runtime_remaining),
+ 1 - (s64)READ_ONCE(cfs_b->quota));
+ held += READ_ONCE(cfs_b->runtime);
+ runtime = min_t(u64, runtime, max_t(s64, held, 0));
+ }
+
+ return runtime;
+}
+
#ifdef CONFIG_NO_HZ_FULL
/* called from pick_next_task_fair() */
static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index a4df59c9c9b601..fd98000ffd7449 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -456,6 +456,7 @@ struct cfs_bandwidth {
u64 runtime;
u64 burst;
u64 runtime_snap;
+ u64 debt;
s64 hierarchical_quota;
u8 idle;
@@ -578,6 +579,9 @@ extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth
extern void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b);
extern void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b);
+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b);
+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime);
+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b);
extern void unthrottle_cfs_rq(struct cfs_rq *cfs_rq);
extern bool cfs_task_bw_constrained(struct task_struct *p);
@@ -618,6 +622,17 @@ static inline bool cfs_task_bw_constrained(struct task_struct *p) { return false
#endif /* !CONFIG_CGROUP_SCHED */
+#ifdef CONFIG_CFS_BANDWIDTH
+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p, u64 delta_exec);
+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p);
+u64 cfs_bandwidth_task_runtime(struct task_struct *p);
+#else
+static inline void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,
+ u64 delta_exec) { }
+static inline void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p) { }
+static inline u64 cfs_bandwidth_task_runtime(struct task_struct *p) { return RUNTIME_INF; }
+#endif
+
/*
* A weight of 0 or 1 can cause arithmetics problems.
* A weight of a cfs_rq is the sum of weights of which entities
diff --git a/tools/sched_ext/include/scx/common.bpf.h b/tools/sched_ext/include/scx/common.bpf.h
index 6194484d4d9a99..cfb7f1b70665fc 100644
--- a/tools/sched_ext/include/scx/common.bpf.h
+++ b/tools/sched_ext/include/scx/common.bpf.h
@@ -98,6 +98,7 @@ s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags
s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
bool scx_bpf_task_running(const struct task_struct *p) __ksym;
s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;
+u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p) __ksym __weak;
struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym __weak;
struct rq *scx_bpf_locked_rq(void) __ksym;
struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;
diff --git a/tools/sched_ext/include/scx/compat.h b/tools/sched_ext/include/scx/compat.h
index 07fb55e63c57c5..60b9972f1a5dc2 100644
--- a/tools/sched_ext/include/scx/compat.h
+++ b/tools/sched_ext/include/scx/compat.h
@@ -215,6 +215,7 @@ static inline bool __COMPAT_struct_has_field(const char *type, const char *field
#define SCX_OPS_BUILTIN_IDLE_PER_NODE SCX_OPS_FLAG(SCX_OPS_BUILTIN_IDLE_PER_NODE)
#define SCX_OPS_ALWAYS_ENQ_IMMED SCX_OPS_FLAG(SCX_OPS_ALWAYS_ENQ_IMMED)
#define SCX_OPS_ENQ_BLOCKED SCX_OPS_FLAG(SCX_OPS_ENQ_BLOCKED)
+#define SCX_OPS_CHARGE_CPU_MAX SCX_OPS_FLAG(SCX_OPS_CHARGE_CPU_MAX)
#define SCX_PICK_IDLE_FLAG(name) __COMPAT_ENUM_OR_ZERO("scx_pick_idle_cpu_flags", #name)
diff --git a/tools/testing/selftests/cgroup/test_cpu.c b/tools/testing/selftests/cgroup/test_cpu.c
index 3456e3e988c68a..04a061da514cec 100644
--- a/tools/testing/selftests/cgroup/test_cpu.c
+++ b/tools/testing/selftests/cgroup/test_cpu.c
@@ -809,6 +809,517 @@ static int test_cpucg_max_nested(const char *root)
return ret;
}
+/* Wait until the period timer of @cgroup starts a new period. */
+static int wait_period_start(const char *cgroup)
+{
+ long nr_periods = cg_read_key_long(cgroup, "cpu.stat", "nr_periods");
+ int i;
+
+ for (i = 0; i < 3000; i++) {
+ usleep(1000);
+ if (cg_read_key_long(cgroup, "cpu.stat", "nr_periods") != nr_periods)
+ return 0;
+ }
+ return -1;
+}
+
+static long long monotonic_ns(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000000000LL + ts.tv_nsec;
+}
+
+/* For (long)arg seconds, run for 1ms and then sleep for 10ms. */
+static int run_and_sleep(const char *cgroup, void *arg)
+{
+ long long end = monotonic_ns() + (long)arg * 1000000000LL;
+ long long start;
+
+ while ((start = monotonic_ns()) < end) {
+ while (monotonic_ns() - start < 1000000)
+ ;
+ usleep(10000);
+ }
+ return 0;
+}
+
+static int test_cpucg_max_runtime(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 1000; /* 1ms (minimum) */
+ long period_usec = 100000; /* 100ms */
+ long burst_usec = 5000000; /* 5s, so cap = 5001ms */
+ long runtime_usec = 2500000; /* 2500ms, half of the 5s run */
+ long duration_sec = 5;
+ /* The injected runtime plus the quota refilled each period of the run */
+ long expected_usec = runtime_usec +
+ duration_sec * USEC_PER_SEC / period_usec * quota_usec;
+ long usage_usec;
+ char *cpucg;
+ char buf[64];
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* Without a quota there is no runtime to set. */
+ if (!cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", burst_usec))
+ goto cleanup;
+
+ /* Start burner, let it settle, then inject credits */
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = duration_sec, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ usleep(100000);
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec)) {
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ goto cleanup;
+ }
+
+ waitpid(pid, NULL, 0);
+
+ usage_usec = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (usage_usec <= 0)
+ goto cleanup;
+
+ /* At least the injected runtime, at most 5% above the expected usage. */
+ if (usage_usec < runtime_usec ||
+ usage_usec > expected_usec + expected_usec / 20)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write is not burst usage: writing a runtime below the
+ * current one leaves cpu.stat's nr_bursts and burst_usec where they were.
+ */
+static int test_cpucg_max_runtime_burst_stats(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long nr_bursts, burst_usec;
+ char *cpucg;
+
+ cpucg = cg_name(root, "cpucg_runtime_burst_stats_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* A long period, so the write lands before the timer's first refill. */
+ if (cg_write(cpucg, "cpu.max", "10000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 0))
+ goto cleanup;
+
+ /* The idle group refills for a few periods. */
+ sleep(3);
+ nr_bursts = cg_read_key_long(cpucg, "cpu.stat", "nr_bursts");
+ burst_usec = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ if (nr_bursts != 0 || burst_usec != 0)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write hands the runtime to a throttled group at once,
+ * rather than at the next period: with a 1s period, the group runs again
+ * within 100ms of the write, before the next period starts.
+ */
+static int test_cpucg_max_runtime_unthrottle(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long usage_before, usage_after, nr_periods;
+ char *cpucg;
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_unthrottle_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* 1ms per 1s period, with room for a runtime of up to 1s. */
+ if (cg_write(cpucg, "cpu.max", "1000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 999000))
+ goto cleanup;
+
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = 2, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ /*
+ * The period timer's phase is random: start right after a boundary,
+ * so that the next one is some 900ms away. The hog uses up its runtime
+ * and is throttled for the period.
+ */
+ if (wait_period_start(cpucg))
+ goto cleanup_hog;
+ nr_periods = cg_read_key_long(cpucg, "cpu.stat", "nr_periods");
+ usleep(50000);
+ usage_before = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (usage_before < 0 || usage_before > 20000)
+ goto cleanup_hog;
+
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 500000))
+ goto cleanup_hog;
+
+ /* No period started meanwhile: only the write lets the hog run. */
+ usleep(100000);
+ usage_after = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (cg_read_key_long(cpucg, "cpu.stat", "nr_periods") != nr_periods)
+ goto cleanup_hog;
+ if (usage_after - usage_before < 50000)
+ goto cleanup_hog;
+
+ ret = KSFT_PASS;
+
+cleanup_hog:
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * What a group ran beyond its quota before a cpu.max.runtime write is still
+ * burst usage: a write of the runtime the group has left does not hide it.
+ */
+static int test_cpucg_max_runtime_burst_kept(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long burst_before, burst_after, runtime_usec;
+ char *cpucg;
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_burst_kept_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* 10ms per 1s period, and a runtime of 1s to run on. */
+ if (cg_write(cpucg, "cpu.max", "10000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 990000))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 1000000))
+ goto cleanup;
+
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = 10, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ /* Run some 300ms, all in one period, and stop. */
+ if (wait_period_start(cpucg)) {
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ goto cleanup;
+ }
+ burst_before = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ usleep(300000);
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+
+ /* Write back what is left: the next refill counts the 300ms run. */
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup;
+ sleep(1);
+ burst_after = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ if (burst_before < 0 || burst_after - burst_before < 250000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * cpu.max.runtime reads at most quota + burst, so that a value read can be
+ * written back. A cfs_rq that dequeues returns its unused runtime, which can
+ * take the runtime above quota + burst until the next refill caps it: run
+ * tasks that keep doing that, and read and write back the runtime meanwhile.
+ */
+static int test_cpucg_max_runtime_read_capped(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long cap_usec = 100000; /* quota 100ms, no burst */
+ long long end;
+ long runtime_usec;
+ char *cpucg;
+ int pids[2];
+ int i, n = 0;
+
+ cpucg = cg_name(root, "cpucg_runtime_read_capped_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ if (cg_write(cpucg, "cpu.max", "100000 100000"))
+ goto cleanup;
+
+ for (n = 0; n < 2; n++) {
+ pids[n] = cg_run_nowait(cpucg, run_and_sleep, (void *)4L);
+ if (pids[n] < 0)
+ goto cleanup_tasks;
+ }
+
+ end = monotonic_ns() + 3000000000LL;
+ while (monotonic_ns() < end) {
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 0 || runtime_usec > cap_usec)
+ goto cleanup_tasks;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup_tasks;
+ }
+
+ ret = KSFT_PASS;
+
+cleanup_tasks:
+ for (i = 0; i < n; i++) {
+ kill(pids[i], SIGKILL);
+ waitpid(pids[i], NULL, 0);
+ }
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A group with a burst keeps earning quota while it is idle, up to
+ * quota + burst, and cpu.max.runtime reads what it has earned. Without a
+ * burst the runtime stays at quota.
+ */
+static int test_cpucg_max_idle_refill(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 10000; /* 10ms */
+ long period_usec = 100000; /* 100ms */
+ long burst_usec = 990000; /* cap 1s */
+ long runtime_usec;
+ char *cpucg;
+ char buf[64];
+
+ cpucg = cg_name(root, "cpucg_idle_refill_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+
+ /* No burst: the runtime stays at quota while idle. */
+ sleep(1);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != quota_usec)
+ goto cleanup;
+
+ /* Burst: the write refills once (20ms), then 1s idle earns 10 more. */
+ if (cg_write_numeric(cpucg, "cpu.max.burst", burst_usec))
+ goto cleanup;
+ sleep(1);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 110000 || runtime_usec > 130000)
+ goto cleanup;
+
+ /* Capped at quota + burst. */
+ sleep(10);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != quota_usec + burst_usec)
+ goto cleanup;
+
+ /*
+ * A write sets the runtime from now on: 500ms later, five refills, or
+ * six if the sleep overruns into the next period.
+ */
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 0))
+ goto cleanup;
+ usleep(500000);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 50000 || runtime_usec > 60000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max or cpu.max.burst write applies from then on: what a group with
+ * a quota earned while idle is kept, capped at the new quota + burst, and a
+ * group that had no quota has earned nothing while it had none.
+ */
+static int test_cpucg_max_idle_refill_write(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 10000; /* 10ms */
+ long period_usec = 100000; /* 100ms */
+ long runtime_usec;
+ char *cpucg = NULL, *fresh = NULL;
+ char buf[64];
+
+ cpucg = cg_name(root, "cpucg_idle_refill_write_test");
+ fresh = cg_name(root, "cpucg_idle_refill_fresh_test");
+ if (!cpucg || !fresh)
+ goto cleanup;
+
+ if (cg_create(cpucg) || cg_create(fresh))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+
+ /* 3s idle fills the group to quota + burst. */
+ sleep(3);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 200000)
+ goto cleanup;
+
+ /* Writing the same cpu.max keeps what the group earned. */
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 200000)
+ goto cleanup;
+
+ /* A lower burst keeps it too, capped at the new quota + burst. */
+ sleep(2);
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 90000))
+ goto cleanup;
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 100000)
+ goto cleanup;
+
+ /* A group given a quota after idling without one starts with a refill. */
+ if (cg_write_numeric(fresh, "cpu.max.burst", 190000))
+ goto cleanup;
+ sleep(2);
+ if (cg_write(fresh, "cpu.max", buf))
+ goto cleanup;
+ runtime_usec = cg_read_long(fresh, "cpu.max.runtime");
+ if (runtime_usec != quota_usec)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ if (fresh)
+ cg_destroy(fresh);
+ if (cpucg)
+ cg_destroy(cpucg);
+ free(fresh);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write sets the runtime exactly, and only the periods
+ * after it refill.
+ */
+static int test_cpucg_max_idle_refill_runtime_write(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long runtime_usec;
+ char *cpucg;
+
+ cpucg = cg_name(root, "cpucg_idle_refill_runtime_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ if (cg_write(cpucg, "cpu.max", "10000 100000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+
+ sleep(3);
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 30000))
+ goto cleanup;
+ /* One refill if a period boundary passes before the read. */
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 30000 && runtime_usec != 40000)
+ goto cleanup;
+
+ /* 250ms after the write: two or three refills, by the boundaries. */
+ usleep(250000);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 50000 || runtime_usec > 60000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
#define T(x) { x, #x }
struct cpucg_test {
int (*fn)(const char *root);
@@ -823,6 +1334,14 @@ struct cpucg_test {
T(test_cpucg_nested_weight_underprovisioned),
T(test_cpucg_max),
T(test_cpucg_max_nested),
+ T(test_cpucg_max_runtime),
+ T(test_cpucg_max_runtime_burst_stats),
+ T(test_cpucg_max_runtime_unthrottle),
+ T(test_cpucg_max_runtime_burst_kept),
+ T(test_cpucg_max_runtime_read_capped),
+ T(test_cpucg_max_idle_refill),
+ T(test_cpucg_max_idle_refill_write),
+ T(test_cpucg_max_idle_refill_runtime_write),
};
#undef T
diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile
index c5d3a2eaea7da2..4a727b8dc7aabc 100644
--- a/tools/testing/selftests/sched_ext/Makefile
+++ b/tools/testing/selftests/sched_ext/Makefile
@@ -165,6 +165,7 @@ all_test_bpfprogs := $(foreach prog,$(wildcard *.bpf.c),$(INCLUDE_DIR)/$(patsubs
auto-test-targets := \
cgroup_nr_cpus \
+ cgroup_runtime \
create_dsq \
dequeue \
dequeue_iter \
diff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c
new file mode 100644
index 00000000000000..ec98a25d19c291
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A scheduler with SCX_OPS_CHARGE_CPU_MAX, for the cgroup_runtime tests. It
+ * runs a task only while scx_bpf_task_cpu_max_runtime() says it has runtime
+ * left, unless @ignore_runtime is set. A task that has none waits in HELD_DSQ,
+ * and a timer kicks the idle CPUs every millisecond, so that they take it
+ * once a period refills the runtime.
+ *
+ * partial_ops sets SCX_OPS_SWITCH_PARTIAL and full_ops does not. Both pass
+ * the cpu.max and cpu.max.runtime writes of @cgid on to the test.
+ */
+
+#include <scx/common.bpf.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define HELD_DSQ 0
+#define KICK_NS 1000000
+
+UEI_DEFINE(uei);
+
+/* the cgroup under test, set before attaching */
+u64 cgid;
+
+/* run tasks whether or not they have runtime left */
+bool ignore_runtime;
+
+/* tasks held for lack of runtime */
+u64 nr_held;
+
+/* the cpu.max and cpu.max.runtime writes of @cgid */
+u64 nr_set_bw;
+u64 quota_us;
+u64 burst_us;
+u64 nr_set_runtime;
+/* cgroup_set_runtime() calls above the quota + burst last given */
+u64 nr_bad_order;
+
+struct kick_timer {
+ struct bpf_timer timer;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, u32);
+ __type(value, struct kick_timer);
+} kick_timer SEC(".maps");
+
+static bool runnable(struct task_struct *p)
+{
+ return ignore_runtime || scx_bpf_task_cpu_max_runtime(p);
+}
+
+s32 BPF_STRUCT_OPS(cgroup_runtime_select_cpu, struct task_struct *p,
+ s32 prev_cpu, u64 wake_flags)
+{
+ return prev_cpu;
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_enqueue, struct task_struct *p,
+ u64 enq_flags)
+{
+ if (!runnable(p)) {
+ __sync_fetch_and_add(&nr_held, 1);
+ scx_bpf_dsq_insert(p, HELD_DSQ, SCX_SLICE_DFL, enq_flags);
+ return;
+ }
+ /* the last task of a CPU going idle must go to its local DSQ */
+ if (enq_flags & SCX_ENQ_LAST)
+ scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, enq_flags);
+ else
+ scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_dispatch, s32 cpu, struct task_struct *prev)
+{
+ struct task_struct *p = __COMPAT_scx_bpf_dsq_peek(HELD_DSQ);
+
+ if (p && runnable(p))
+ scx_bpf_dsq_move_to_local(HELD_DSQ, 0);
+}
+
+/*
+ * Stop a task that ran out, so that it goes through enqueue again.
+ * SCX_OPS_ENQ_LAST makes that so also when it is alone on its CPU.
+ */
+void BPF_STRUCT_OPS(cgroup_runtime_tick, struct task_struct *p)
+{
+ if (!runnable(p))
+ scx_bpf_task_set_slice(p, 0);
+}
+
+static int kick_timerfn(void *map, int *key, struct bpf_timer *timer)
+{
+ s32 cpu;
+
+ if (scx_bpf_dsq_nr_queued(HELD_DSQ))
+ bpf_for(cpu, 0, scx_bpf_nr_cpu_ids())
+ scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE);
+
+ bpf_timer_start(timer, KICK_NS, 0);
+ return 0;
+}
+
+s32 BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_init)
+{
+ struct bpf_timer *timer;
+ u32 key = 0;
+ s32 ret;
+
+ ret = scx_bpf_create_dsq(HELD_DSQ, -1);
+ if (ret)
+ return ret;
+
+ timer = bpf_map_lookup_elem(&kick_timer, &key);
+ if (!timer)
+ return -ESRCH;
+ bpf_timer_init(timer, &kick_timer, CLOCK_MONOTONIC);
+ bpf_timer_set_callback(timer, kick_timerfn);
+ return bpf_timer_start(timer, KICK_NS, 0);
+}
+
+static bool is_target(struct cgroup *cgrp)
+{
+ return cgid && cgrp->kn->id == cgid;
+}
+
+/* sleepable: cpu.max writes call it in process context */
+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_bandwidth,
+ struct cgroup *cgrp, u64 period_us, u64 quota,
+ u64 burst)
+{
+ if (!is_target(cgrp))
+ return;
+
+ __sync_fetch_and_add(&nr_set_bw, 1);
+ quota_us = quota;
+ burst_us = burst;
+}
+
+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_runtime,
+ struct cgroup *cgrp, u64 runtime_us)
+{
+ if (!is_target(cgrp))
+ return;
+
+ __sync_fetch_and_add(&nr_set_runtime, 1);
+ if (runtime_us > quota_us + burst_us)
+ __sync_fetch_and_add(&nr_bad_order, 1);
+}
+
+s32 BPF_STRUCT_OPS(cgroup_runtime_cgroup_init, struct cgroup *cgrp,
+ struct scx_cgroup_init_args *args)
+{
+ if (is_target(cgrp)) {
+ quota_us = args->bw_quota_us;
+ burst_us = args->bw_burst_us;
+ }
+ return 0;
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_exit, struct scx_exit_info *ei)
+{
+ UEI_RECORD(uei, ei);
+}
+
+SCX_OPS_DEFINE(partial_ops,
+ .select_cpu = (void *)cgroup_runtime_select_cpu,
+ .enqueue = (void *)cgroup_runtime_enqueue,
+ .dispatch = (void *)cgroup_runtime_dispatch,
+ .tick = (void *)cgroup_runtime_tick,
+ .init = (void *)cgroup_runtime_init,
+ .cgroup_init = (void *)cgroup_runtime_cgroup_init,
+ .cgroup_set_bandwidth = (void *)cgroup_runtime_cgroup_set_bandwidth,
+ .cgroup_set_runtime = (void *)cgroup_runtime_cgroup_set_runtime,
+ .exit = (void *)cgroup_runtime_exit,
+ .flags = SCX_OPS_SWITCH_PARTIAL |
+ SCX_OPS_ENQ_LAST |
+ SCX_OPS_CHARGE_CPU_MAX,
+ .name = "cgroup_runtime");
+
+SCX_OPS_DEFINE(full_ops,
+ .select_cpu = (void *)cgroup_runtime_select_cpu,
+ .enqueue = (void *)cgroup_runtime_enqueue,
+ .dispatch = (void *)cgroup_runtime_dispatch,
+ .tick = (void *)cgroup_runtime_tick,
+ .init = (void *)cgroup_runtime_init,
+ .cgroup_init = (void *)cgroup_runtime_cgroup_init,
+ .cgroup_set_bandwidth = (void *)cgroup_runtime_cgroup_set_bandwidth,
+ .cgroup_set_runtime = (void *)cgroup_runtime_cgroup_set_runtime,
+ .exit = (void *)cgroup_runtime_exit,
+ .flags = SCX_OPS_ENQ_LAST |
+ SCX_OPS_CHARGE_CPU_MAX,
+ .name = "cgroup_runtime_full");
diff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.c b/tools/testing/selftests/sched_ext/cgroup_runtime.c
new file mode 100644
index 00000000000000..86d50a63a6e738
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.c
@@ -0,0 +1,652 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Verify that a BPF scheduler with SCX_OPS_CHARGE_CPU_MAX shares a cgroup's
+ * cpu.max quota with the fair class: what the cgroup's tasks run in both
+ * classes, with and without SCX_OPS_SWITCH_PARTIAL and while tasks switch
+ * class, stays within the quota; nothing is gained or lost when the
+ * scheduler loads and unloads; and a scheduler that ignores
+ * scx_bpf_task_cpu_max_runtime() leaves the fair tasks at most a quota of
+ * debt and a slice per CPU, while one that stops tasks late pays the overrun
+ * back.
+ * Also verify that cpu.max and cpu.max.runtime writes reach the scheduler
+ * in the order the fair class applied them.
+ *
+ * Usage is cpu.stat's usage_usec. A window of n periods may hold n + 1
+ * refills and start or end with up to a quota, and each CPU may hold up to
+ * a slice (sched_cfs_bandwidth_slice_us), so the checks allow that.
+ */
+
+#define _GNU_SOURCE
+#include <bpf/bpf.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <linux/limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <scx/common.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "cgroup_runtime.bpf.skel.h"
+#include "cgroup_util.h"
+#include "scx_test.h"
+
+#ifndef SCHED_EXT
+#define SCHED_EXT 7
+#endif
+
+#define PERIOD_US 100000LL
+#define QUOTA_US 20000LL
+#define NR_PERIODS 10
+#define NR_BURNERS 2
+
+struct ctx {
+ struct cgroup_runtime *skel;
+ struct bpf_link *link;
+ char root[PATH_MAX];
+ char parent[PATH_MAX];
+ char cg[PATH_MAX];
+ bool parent_created;
+ bool cg_created;
+ pid_t burner[NR_BURNERS];
+ long long slice_us;
+ long long saved_slice_us;
+};
+
+static int join_path(char *dst, size_t dst_size, const char *parent, const char *name)
+{
+ int ret;
+
+ ret = snprintf(dst, dst_size, "%s/%s", parent, name);
+ if (ret < 0 || (size_t)ret >= dst_size)
+ return -ENAMETOOLONG;
+ return 0;
+}
+
+static u64 now_us(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000000ULL + ts.tv_nsec / 1000;
+}
+
+static u64 cgroup_id(const char *path)
+{
+ union {
+ u64 id;
+ unsigned char bytes[8];
+ } id = {};
+ struct file_handle *handle;
+ int mount_id, ret;
+
+ handle = calloc(1, sizeof(*handle) + sizeof(id));
+ if (!handle)
+ return 0;
+ handle->handle_bytes = sizeof(id);
+ ret = name_to_handle_at(AT_FDCWD, path, handle, &mount_id, 0);
+ if (!ret && handle->handle_bytes == sizeof(id))
+ memcpy(id.bytes, handle->f_handle, sizeof(id));
+ free(handle);
+
+ return ret ? 0 : id.id;
+}
+
+static long long read_runtime(struct ctx *ctx)
+{
+ return cg_read_long(ctx->cg, "cpu.max.runtime");
+}
+
+static long long read_usage(struct ctx *ctx)
+{
+ return cg_read_key_long(ctx->cg, "cpu.stat", "usage_usec");
+}
+
+static int write_str(const char *cgroup, const char *file, const char *fmt, ...)
+{
+ char buf[64];
+ va_list ap;
+
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ return cg_write(cgroup, file, buf);
+}
+
+static bool controller_enabled(const char *cgroup, const char *file, const char *controller)
+{
+ char buf[4096], *saveptr, *token;
+
+ if (cg_read(cgroup, file, buf, sizeof(buf)))
+ return false;
+ for (token = strtok_r(buf, "\n ", &saveptr); token;
+ token = strtok_r(NULL, "\n ", &saveptr))
+ if (!strcmp(token, controller))
+ return true;
+ return false;
+}
+
+static int set_policy(pid_t pid, int policy)
+{
+ struct sched_param param = {};
+
+ return sched_setscheduler(pid, policy, ¶m);
+}
+
+static void stop_burners(struct ctx *ctx)
+{
+ int i;
+
+ for (i = 0; i < NR_BURNERS; i++) {
+ if (ctx->burner[i] <= 0)
+ continue;
+ kill(ctx->burner[i], SIGKILL);
+ waitpid(ctx->burner[i], NULL, 0);
+ ctx->burner[i] = 0;
+ }
+}
+
+/* a task in @ctx->cg that spins on CPU @i + 1 under @policy */
+static int start_burner(struct ctx *ctx, int i, int policy)
+{
+ cpu_set_t set;
+ pid_t pid;
+
+ pid = fork();
+ if (pid < 0)
+ return -errno;
+ if (!pid)
+ for (;;)
+ ;
+
+ ctx->burner[i] = pid;
+ CPU_ZERO(&set);
+ CPU_SET((i + 1) % libbpf_num_possible_cpus(), &set);
+ if (sched_setaffinity(pid, sizeof(set), &set) ||
+ cg_enter(ctx->cg, pid) || set_policy(pid, policy))
+ return -1;
+ return 0;
+}
+
+static void cleanup(void *arg)
+{
+ struct ctx *ctx = arg;
+
+ if (!ctx)
+ return;
+ stop_burners(ctx);
+ bpf_link__destroy(ctx->link);
+ cgroup_runtime__destroy(ctx->skel);
+ if (ctx->saved_slice_us)
+ write_str("/proc/sys/kernel", "sched_cfs_bandwidth_slice_us", "%lld",
+ ctx->saved_slice_us);
+ if (ctx->cg_created)
+ cg_destroy(ctx->cg);
+ if (ctx->parent_created)
+ cg_destroy(ctx->parent);
+ free(ctx);
+}
+
+/*
+ * Open the skeleton and make parent/cg under the cgroup2 root, with a quota
+ * of @quota us per @period us, a burst of @burst us and a runtime of
+ * @runtime us on cg.
+ */
+static enum scx_test_status setup_ctx(void **ctxp, long long quota,
+ long long period, long long burst,
+ long long runtime)
+{
+ struct ctx *ctx;
+ char name[64];
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (!ctx)
+ return SCX_TEST_FAIL;
+ *ctxp = ctx;
+
+ /* SCX_ENUM_INIT() exits if vmlinux BTF can't be loaded: before cgroups */
+ ctx->skel = cgroup_runtime__open();
+ if (!ctx->skel) {
+ SCX_ERR("Failed to open skel");
+ return SCX_TEST_FAIL;
+ }
+ SCX_ENUM_INIT(ctx->skel);
+
+ ctx->slice_us = 5000;
+ if (!access("/proc/sys/kernel/sched_cfs_bandwidth_slice_us", R_OK))
+ ctx->slice_us = cg_read_long("/proc/sys/kernel",
+ "sched_cfs_bandwidth_slice_us");
+
+ if (cg_find_unified_root(ctx->root, sizeof(ctx->root), NULL))
+ return SCX_TEST_SKIP;
+ if (!controller_enabled(ctx->root, "cgroup.subtree_control", "cpu") &&
+ cg_write(ctx->root, "cgroup.subtree_control", "+cpu"))
+ return SCX_TEST_SKIP;
+
+ snprintf(name, sizeof(name), "scx_cgroup_runtime_%d", getpid());
+ if (join_path(ctx->parent, sizeof(ctx->parent), ctx->root, name) ||
+ join_path(ctx->cg, sizeof(ctx->cg), ctx->parent, "cg")) {
+ SCX_ERR("Cgroup path is too long");
+ return SCX_TEST_FAIL;
+ }
+
+ if (cg_create(ctx->parent)) {
+ SCX_ERR("Failed to create %s", ctx->parent);
+ return SCX_TEST_FAIL;
+ }
+ ctx->parent_created = true;
+ if (cg_write(ctx->parent, "cgroup.subtree_control", "+cpu")) {
+ SCX_ERR("Failed to enable cpu in %s", ctx->parent);
+ return SCX_TEST_FAIL;
+ }
+ if (cg_create(ctx->cg)) {
+ SCX_ERR("Failed to create %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+ ctx->cg_created = true;
+
+ if (access(cg_control(ctx->cg, "cpu.max.runtime"), F_OK))
+ return SCX_TEST_SKIP;
+
+ if (write_str(ctx->cg, "cpu.max", "%lld %lld", quota, period) ||
+ write_str(ctx->cg, "cpu.max.burst", "%lld", burst) ||
+ write_str(ctx->cg, "cpu.max.runtime", "%lld", runtime)) {
+ SCX_ERR("Failed to configure %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+
+ ctx->skel->bss->cgid = cgroup_id(ctx->cg);
+ if (!ctx->skel->bss->cgid) {
+ SCX_ERR("Failed to read the cgroup ID of %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+ if (libbpf_num_possible_cpus() < NR_BURNERS + 1)
+ return SCX_TEST_SKIP;
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status setup_rate(void **ctxp)
+{
+ return setup_ctx(ctxp, QUOTA_US, PERIOD_US, 0, QUOTA_US);
+}
+
+static enum scx_test_status attach_ops(struct ctx *ctx, bool partial)
+{
+ ctx->link = bpf_map__attach_struct_ops(partial ? ctx->skel->maps.partial_ops :
+ ctx->skel->maps.full_ops);
+ SCX_FAIL_IF(!ctx->link, "Failed to attach scheduler");
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status load_ops(struct ctx *ctx, bool partial)
+{
+ bpf_map__set_autoattach(ctx->skel->maps.partial_ops, false);
+ bpf_map__set_autoattach(ctx->skel->maps.full_ops, false);
+ SCX_FAIL_IF(cgroup_runtime__load(ctx->skel), "Failed to load skel");
+ return attach_ops(ctx, partial);
+}
+
+static void detach(struct ctx *ctx)
+{
+ bpf_link__destroy(ctx->link);
+ ctx->link = NULL;
+}
+
+/*
+ * Run two burners in cg under @policy[], the first switching class every
+ * 7 ms if @toggle, and check that cg runs its quota per period, no more and
+ * not much less.
+ */
+static enum scx_test_status run_rate(struct ctx *ctx, bool partial,
+ const int *policy, bool toggle)
+{
+ long long tol = NR_BURNERS * ctx->slice_us + QUOTA_US;
+ long long used, u0;
+ bool ext = false;
+ u64 end;
+ int i;
+
+ if (load_ops(ctx, partial))
+ return SCX_TEST_FAIL;
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, policy[i]), 0);
+
+ usleep(3 * PERIOD_US);
+ u0 = read_usage(ctx);
+ end = now_us() + NR_PERIODS * PERIOD_US;
+ while (now_us() < end) {
+ if (toggle) {
+ ext = !ext;
+ SCX_EQ(set_policy(ctx->burner[0], ext ? SCHED_EXT : SCHED_OTHER), 0);
+ }
+ usleep(7000);
+ }
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us in %d periods of quota %lld us, %lu held\n",
+ used, NR_PERIODS, QUOTA_US, (unsigned long)ctx->skel->bss->nr_held);
+ SCX_GE(used, QUOTA_US * NR_PERIODS - tol);
+ SCX_LE(used, QUOTA_US * NR_PERIODS + tol);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run_full(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_OTHER };
+
+ return run_rate(arg, false, policy, false);
+}
+
+static enum scx_test_status run_partial_ext(void *arg)
+{
+ static const int policy[] = { SCHED_EXT, SCHED_EXT };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_partial_fair(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_OTHER };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_partial_mixed(void *arg)
+{
+ static const int policy[] = { SCHED_EXT, SCHED_OTHER };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_switch(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_EXT };
+
+ return run_rate(arg, true, policy, true);
+}
+
+/*
+ * With a quota of 1 ms per second and a runtime of 3 s, what cg runs while
+ * the scheduler loads, runs and unloads is what its runtime loses, up to a
+ * slice per CPU and the few refills.
+ */
+#define LU_QUOTA_US 1000LL
+#define LU_PERIOD_US 1000000LL
+
+static enum scx_test_status setup_load_unload(void **ctxp)
+{
+ return setup_ctx(ctxp, LU_QUOTA_US, LU_PERIOD_US, 4000000, 3000000);
+}
+
+static enum scx_test_status run_load_unload(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long r0, u0, drawn, used, refills, tol;
+ u64 t0, t1;
+ int i;
+
+ bpf_map__set_autoattach(ctx->skel->maps.partial_ops, false);
+ bpf_map__set_autoattach(ctx->skel->maps.full_ops, false);
+ SCX_FAIL_IF(cgroup_runtime__load(ctx->skel), "Failed to load skel");
+
+ t0 = now_us();
+ r0 = read_runtime(ctx);
+ u0 = read_usage(ctx);
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, SCHED_OTHER), 0);
+ usleep(100000);
+ if (attach_ops(ctx, false))
+ return SCX_TEST_FAIL;
+ usleep(200000);
+ detach(ctx);
+ usleep(100000);
+ stop_burners(ctx);
+ drawn = r0 - read_runtime(ctx);
+ used = read_usage(ctx) - u0;
+ t1 = now_us();
+
+ refills = LU_QUOTA_US * ((t1 - t0) / LU_PERIOD_US + 2);
+ tol = NR_BURNERS * ctx->slice_us;
+ printf("ran %lld us, runtime down %lld us\n", used, drawn);
+ SCX_GE(used, 300000);
+ SCX_GE(used, drawn - tol);
+ SCX_LE(used, drawn + refills + tol);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * A scheduler that ignores scx_bpf_task_cpu_max_runtime() runs a task far
+ * past the quota. Once the task is back on the fair class, it runs its quota
+ * again, less at most a quota and a slice of debt.
+ */
+static enum scx_test_status run_clamp(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long u0, ignored, used;
+
+ ctx->skel->bss->ignore_runtime = true;
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ SCX_EQ(start_burner(ctx, 0, SCHED_EXT), 0);
+
+ u0 = read_usage(ctx);
+ usleep(5 * PERIOD_US);
+ ignored = read_usage(ctx) - u0;
+
+ SCX_EQ(set_policy(ctx->burner[0], SCHED_OTHER), 0);
+ u0 = read_usage(ctx);
+ usleep(5 * PERIOD_US);
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us ignoring the quota, then %lld us on the fair class\n",
+ ignored, used);
+ SCX_GE(ignored, 4 * PERIOD_US);
+ SCX_GE(used, 4 * QUOTA_US - 2 * ctx->slice_us);
+ SCX_LE(used, 6 * QUOTA_US + ctx->slice_us);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * The scheduler stops a task only at a tick, so each period it overruns a
+ * quota of 2 ms by up to a tick. With a slice of 1 ms, the next tick's
+ * charge takes the CPU past the -slice floor. The debt must still be paid
+ * from the next periods, so over 100 periods cg runs its quota, with the
+ * second burner moving between CPUs 2 and 3 every 7 ms.
+ */
+#define DEBT_QUOTA_US 2000LL
+#define DEBT_PERIOD_US 10000LL
+#define DEBT_PERIODS 100
+
+static enum scx_test_status setup_debt(void **ctxp)
+{
+ enum scx_test_status ret;
+ struct ctx *ctx;
+
+ ret = setup_ctx(ctxp, DEBT_QUOTA_US, DEBT_PERIOD_US, 0, DEBT_QUOTA_US);
+ if (ret != SCX_TEST_PASS)
+ return ret;
+ ctx = *ctxp;
+ if (write_str("/proc/sys/kernel", "sched_cfs_bandwidth_slice_us", "1000"))
+ return SCX_TEST_SKIP;
+ ctx->saved_slice_us = ctx->slice_us;
+ ctx->slice_us = 1000;
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run_debt(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long tol = (NR_BURNERS + 1) * ctx->slice_us + DEBT_QUOTA_US;
+ long long want = DEBT_QUOTA_US * DEBT_PERIODS;
+ long long used, u0;
+ bool moved = false;
+ cpu_set_t set;
+ u64 end;
+ int i;
+
+ if (libbpf_num_possible_cpus() < 4)
+ return SCX_TEST_SKIP;
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, SCHED_EXT), 0);
+
+ usleep(3 * DEBT_PERIOD_US);
+ u0 = read_usage(ctx);
+ end = now_us() + DEBT_PERIODS * DEBT_PERIOD_US;
+ while (now_us() < end) {
+ moved = !moved;
+ CPU_ZERO(&set);
+ CPU_SET(moved ? 3 : 2, &set);
+ SCX_EQ(sched_setaffinity(ctx->burner[1], sizeof(set), &set), 0);
+ usleep(7000);
+ }
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us in %d periods of quota %lld us\n", used,
+ DEBT_PERIODS, DEBT_QUOTA_US);
+ SCX_GE(used, want - tol);
+ SCX_LE(used, want + tol);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * One thread alternates cpu.max between quotas of 100ms and 10ms, without a
+ * burst, while another writes a runtime of 90ms, which only the first
+ * allows. The scheduler must never get a runtime above the quota it was last
+ * given, and must end with the quota cpu.max has.
+ */
+#define INTERLEAVE_US 2000000ULL
+
+struct interleave {
+ struct ctx *ctx;
+ long nr_ok;
+ long nr_einval;
+ long nr_err;
+};
+
+static void *interleave_quota(void *arg)
+{
+ struct interleave *il = arg;
+ u64 end = now_us() + INTERLEAVE_US;
+ bool high = false;
+
+ while (now_us() < end) {
+ if (write_str(il->ctx->cg, "cpu.max", "%lld %lld",
+ high ? 100000LL : 10000LL, 1000000LL))
+ il->nr_err++;
+ else
+ il->nr_ok++;
+ high = !high;
+ }
+ return NULL;
+}
+
+static void *interleave_runtime(void *arg)
+{
+ struct interleave *il = arg;
+ u64 end = now_us() + INTERLEAVE_US;
+
+ while (now_us() < end) {
+ int fd = cg_open(il->ctx->cg, "cpu.max.runtime", O_WRONLY);
+
+ if (fd < 0) {
+ il->nr_err++;
+ continue;
+ }
+ if (write(fd, "90000", 5) == 5)
+ il->nr_ok++;
+ else if (errno == EINVAL)
+ il->nr_einval++;
+ else
+ il->nr_err++;
+ close(fd);
+ }
+ return NULL;
+}
+
+static enum scx_test_status setup_interleave(void **ctxp)
+{
+ return setup_ctx(ctxp, 100000, 1000000, 0, 100000);
+}
+
+static enum scx_test_status run_interleave(void *arg)
+{
+ struct ctx *ctx = arg;
+ struct interleave quota = { .ctx = ctx }, runtime = { .ctx = ctx };
+ pthread_t tq, tr;
+ char buf[64];
+
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ SCX_EQ(ctx->skel->bss->quota_us, 100000);
+
+ SCX_EQ(pthread_create(&tq, NULL, interleave_quota, "a), 0);
+ SCX_EQ(pthread_create(&tr, NULL, interleave_runtime, &runtime), 0);
+ pthread_join(tq, NULL);
+ pthread_join(tr, NULL);
+
+ SCX_EQ(quota.nr_err, 0);
+ SCX_EQ(runtime.nr_err, 0);
+ SCX_GT(runtime.nr_ok, 0);
+ SCX_EQ(ctx->skel->bss->nr_bad_order, 0);
+ SCX_EQ(ctx->skel->bss->nr_set_bw, quota.nr_ok);
+ SCX_EQ(ctx->skel->bss->nr_set_runtime, runtime.nr_ok);
+
+ SCX_EQ(cg_read(ctx->cg, "cpu.max", buf, sizeof(buf)), 0);
+ SCX_EQ(ctx->skel->bss->quota_us, atoll(buf));
+ SCX_EQ(ctx->skel->bss->burst_us, 0);
+
+ printf("cpu.max writes %ld, cpu.max.runtime writes %ld (%ld EINVAL)\n",
+ quota.nr_ok, runtime.nr_ok, runtime.nr_einval);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+#define RUNTIME_TEST(__name, __setup, __desc) \
+ struct scx_test cgroup_runtime_##__name = { \
+ .name = "cgroup_runtime_" #__name, \
+ .description = __desc, \
+ .setup = __setup, \
+ .run = run_##__name, \
+ .cleanup = cleanup, \
+ }
+
+RUNTIME_TEST(full, setup_rate, "Without partial switch, the BPF scheduler's tasks run their quota");
+RUNTIME_TEST(partial_ext, setup_rate, "SCHED_EXT tasks of a cgroup run its quota");
+RUNTIME_TEST(partial_fair, setup_rate, "Fair tasks of a cgroup run its quota");
+RUNTIME_TEST(partial_mixed, setup_rate, "Fair and SCHED_EXT tasks of a cgroup share its quota");
+RUNTIME_TEST(switch, setup_rate, "A task switching class every 7 ms stays within the quota");
+RUNTIME_TEST(load_unload, setup_load_unload, "Load and unload neither gain nor lose runtime");
+RUNTIME_TEST(clamp, setup_rate, "A scheduler ignoring the quota leaves a bounded debt");
+RUNTIME_TEST(debt, setup_debt, "Debt past a quota is paid in the next periods");
+RUNTIME_TEST(interleave, setup_interleave, "cpu.max writes reach the scheduler in order");
+
+/* REGISTER_SCX_TEST() can be used once per file */
+__attribute__((constructor))
+static void register_cgroup_runtime_tests(void)
+{
+ scx_test_register(&cgroup_runtime_full);
+ scx_test_register(&cgroup_runtime_partial_ext);
+ scx_test_register(&cgroup_runtime_partial_fair);
+ scx_test_register(&cgroup_runtime_partial_mixed);
+ scx_test_register(&cgroup_runtime_switch);
+ scx_test_register(&cgroup_runtime_load_unload);
+ scx_test_register(&cgroup_runtime_clamp);
+ scx_test_register(&cgroup_runtime_debt);
+ scx_test_register(&cgroup_runtime_interleave);
+}
diff --git a/tools/testing/selftests/sched_ext/config b/tools/testing/selftests/sched_ext/config
index 8173f9170ffe89..495b140403a18e 100644
--- a/tools/testing/selftests/sched_ext/config
+++ b/tools/testing/selftests/sched_ext/config
@@ -9,3 +9,4 @@ CONFIG_DEBUG_INFO=y
CONFIG_DEBUG_INFO_BTF=y
CONFIG_EXPERT=y
CONFIG_SCHED_PROXY_EXEC=y
+CONFIG_CFS_BANDWIDTH=y
|
| 3/2 | 2026/11/13 14:16 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32007 output: 62 thoughts: 890 Thoughts: **Assessing the Fuzzing Potential of This Patch** Okay, let's break this down. My initial assessment is that this patch *looks* interesting for fuzzing with syzkaller, but I need to be methodical. First, I need to understand *what* it changes. It's touching a few key areas: the documentation for cgroup v2 and the scheduler, the kernel scheduler core itself, specifically `core.c`, fair scheduler (`fair.c`), and it's also making changes to sched\_ext integration in `ext.c`, and some related header and tools. Specifically, it looks like there's a good amount of work being done on `cgroup-v2.rst`, the scheduler bwc documentation, and then core files like `core.c` implementing things like `cpu.max.runtime` - that’s pretty substantial. It introduces a mutex, modifies bandwidth calculations and cgroup control files, and updates relevant structures. There are also a lot of new functions in `fair.c` dealing with CFS bandwidth management, debt, runtime, and charging/returning tasks. The sched\_ext changes add new BPF kfuncs, and integrate this into sched\_ext callbacks. Now, the crucial questions: Is this touching reachable kernel code? Absolutely! Core subsystems like the scheduler, cgroups (including the `cpu.max.runtime`, `cpu.max.burst` controls), CFS bandwidth throttling logic, and even sched_ext BPF kfuncs are all within the scope of these changes. Can this be reached in standard virtualized environments like QEMU or GCE? Yes, again! Cgroups v2's CPU controller, CFS bandwidth, writing to the `cpu.max`, `cpu.max.burst`, and `cpu.max.runtime` cgroup files, and sched_ext BPF schedulers are all readily accessible in these environments. This is core scheduler code. Given the scope and reachability, WorthFuzzing is definitely TRUE. Now I need to dig into the configurations and the specific symbols involved. I will now search the repository for Kconfig dependencies to gain a deeper understanding of the activation paths. |
| 4/2 | 2026/11/13 14:17 | tool | grepper |
0mArgs:{
"Expression": "config (CFS_BANDWIDTH|FAIR_GROUP_SCHED|EXT_GROUP_SCHED|SCHED_CLASS_EXT)",
"PathPrefixes": [
"init/Kconfig",
"kernel/sched/"
]
}Results: {
"Output": "init/Kconfig=960=config GROUP_SCHED_BANDWIDTH\n--\ninit/Kconfig-962-\ninit/Kconfig:963:config FAIR_GROUP_SCHED\ninit/Kconfig-964-\tbool \"Group scheduling for SCHED_OTHER\"\n--\ninit/Kconfig-968-\ninit/Kconfig:969:config CFS_BANDWIDTH\ninit/Kconfig-970-\tbool \"CPU bandwidth provisioning for FAIR_GROUP_SCHED\"\n--\ninit/Kconfig=992=config RT_GROUP_SCHED_DEFAULT_DISABLED\n--\ninit/Kconfig-1002-\ninit/Kconfig:1003:config EXT_GROUP_SCHED\ninit/Kconfig-1004-\tbool\n"
} |
| 5/2 | 2026/11/13 14:17 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33611 output: 32 thoughts: 26 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Diving into Kconfig and Scheduling Parameters** Alright, let's get down to brass tacks. I'm thinking we need to quickly verify the Kconfig options surrounding CFS bandwidth control, EXT_GROUP_SCHED, and SCHED_CLASS_EXT. We know how these pieces interact, and I want to refresh my mental model, especially given the nuances of how they influence each other. A quick check of the configuration options will confirm the current build configuration and ensure no unexpected dependencies or exclusions are in play. I'm especially interested in confirming that the expected features are enabled (or, if disabled, that we understand the implications). I'm looking to confirm how these aspects are orchestrated to work together or not. Essentially, confirming my assumptions about how these flags are working as expected will provide me a solid basis moving forward. This is likely a precursor to analyzing the scheduling policy configurations. |
| 6/2 | 2026/11/13 14:18 | tool | read-file |
0mArgs:{
"File": "init/Kconfig",
"FirstLine": 960,
"LineCount": 60
}Results: {
"Contents": " 960:\tconfig GROUP_SCHED_BANDWIDTH\n 961:\t\tdef_bool n\n 962:\t\n 963:\tconfig FAIR_GROUP_SCHED\n 964:\t\tbool \"Group scheduling for SCHED_OTHER\"\n 965:\t\tdepends on CGROUP_SCHED\n 966:\t\tselect GROUP_SCHED_WEIGHT\n 967:\t\tdefault CGROUP_SCHED\n 968:\t\n 969:\tconfig CFS_BANDWIDTH\n 970:\t\tbool \"CPU bandwidth provisioning for FAIR_GROUP_SCHED\"\n 971:\t\tdepends on FAIR_GROUP_SCHED\n 972:\t\tselect GROUP_SCHED_BANDWIDTH\n 973:\t\tdefault n\n 974:\t\thelp\n 975:\t\t This option allows users to define CPU bandwidth rates (limits) for\n 976:\t\t tasks running within the fair group scheduler. Groups with no limit\n 977:\t\t set are considered to be unconstrained and will run with no\n 978:\t\t restriction.\n 979:\t\t See Documentation/scheduler/sched-bwc.rst for more information.\n 980:\t\n 981:\tconfig RT_GROUP_SCHED\n 982:\t\tbool \"Group scheduling for SCHED_RR/FIFO\"\n 983:\t\tdepends on CGROUP_SCHED\n 984:\t\tdefault n\n 985:\t\thelp\n 986:\t\t This feature lets you explicitly allocate real CPU bandwidth\n 987:\t\t to task groups. If enabled, it will also make it impossible to\n 988:\t\t schedule realtime tasks for non-root users until you allocate\n 989:\t\t realtime bandwidth for them.\n 990:\t\t See Documentation/scheduler/sched-rt-group.rst for more information.\n 991:\t\n 992:\tconfig RT_GROUP_SCHED_DEFAULT_DISABLED\n 993:\t\tbool \"Require boot parameter to enable group scheduling for SCHED_RR/FIFO\"\n 994:\t\tdepends on RT_GROUP_SCHED\n 995:\t\tdefault n\n 996:\t\thelp\n 997:\t\t When set, the RT group scheduling is disabled by default. The option\n 998:\t\t is in inverted form so that mere RT_GROUP_SCHED enables the group\n 999:\t\t scheduling.\n1000:\t\n1001:\t\t Say N if unsure.\n1002:\t\n1003:\tconfig EXT_GROUP_SCHED\n1004:\t\tbool\n1005:\t\tdepends on SCHED_CLASS_EXT \u0026\u0026 CGROUP_SCHED\n1006:\t\tselect GROUP_SCHED_WEIGHT\n1007:\t\tselect GROUP_SCHED_BANDWIDTH\n1008:\t\tdefault y\n1009:\t\n1010:\tendif #CGROUP_SCHED\n1011:\t\n1012:\tconfig EXT_SUB_SCHED\n1013:\t def_bool y\n1014:\t depends on SCHED_CLASS_EXT \u0026\u0026 CGROUPS\n1015:\t\n1016:\tconfig SCHED_MM_CID\n1017:\t\tdef_bool y\n1018:\t\tdepends on SMP \u0026\u0026 RSEQ\n1019:\t\n"
} |
| 7/2 | 2026/11/13 14:18 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34713 output: 32 thoughts: 16 Thoughts: Here's a summary of my thought process: **Diving into Scheduler Class Extensions** Okay, first things first, I need to pinpoint the definition of `SCHED_CLASS_EXT`. This is likely a macro or a constant related to scheduler extensions, and understanding its definition is crucial to grasping the system's scheduling behavior. I need to know where this is defined to understand its meaning and impact. |
| 8/2 | 2026/11/13 14:20 | tool | grepper |
0mArgs:{
"Expression": "config SCHED_CLASS_EXT",
"PathPrefixes": [
"kernel/sched/"
]
}Results: {
"Output": "no matches"
} |
| 9/2 | 2026/11/13 14:20 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34860 output: 21 thoughts: 33 Thoughts: Here's my thought process, as if I were considering this myself: **Investigating the `SCHED_CLASS_EXT` Symbol** Okay, so I need to figure out where the `SCHED_CLASS_EXT` symbol is defined in the kernel configuration files. My first instinct is to use `grep`. Given that this sounds like a scheduler-related symbol, I'll start by searching in the `Kconfig` files located within the kernel's source tree. I'll target the obvious locations: `kernel/Kconfig*` and `init/Kconfig`. These are the usual suspects for configuration options related to core kernel features and initialization. If that doesn't turn anything up, I'll need to broaden the search to look across the entire source tree to make absolutely sure I don't miss anything, even if it's less likely. I'll need to figure out where the symbol is defined in the Kconfig files. |
| 10/2 | 2026/11/13 14:20 | tool | grepper |
0mArgs:{
"Expression": "config SCHED_CLASS_EXT"
}Results: {
"Output": "kernel/Kconfig.preempt=152=config SCHED_CORE\n--\nkernel/Kconfig.preempt-169-\nkernel/Kconfig.preempt:170:config SCHED_CLASS_EXT\nkernel/Kconfig.preempt-171-\tbool \"Extensible Scheduling Class\"\n"
} |
| 11/2 | 2026/11/13 14:20 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35200 output: 35 thoughts: 20 Thoughts: Okay, let's dive into this. Here's my thought process on this task: **Analyzing `kernel/Kconfig.preempt` - Line 170** Right, so I'm focusing on `kernel/Kconfig.preempt`, specifically around line 170. My immediate thought is, "Okay, what's likely defined *there*? Given the context, it's almost certainly going to be related to the preemption configuration options." I expect to find some critical definitions or dependencies related to how the kernel handles preemption and how it's enabled or disabled. Considering the location, it's probably setting up some crucial conditional logic. I need to understand what this specific location is declaring and how it may be affecting the kernel build process. I need to understand the implications of the definitions present at this line. |
| 12/2 | 2026/11/13 14:20 | tool | read-file |
0mArgs:{
"File": "kernel/Kconfig.preempt",
"FirstLine": 168,
"LineCount": 25
}Results: {
"Contents": " 168:\t\t be no measurable impact on performance.\n 169:\t\n 170:\tconfig SCHED_CLASS_EXT\n 171:\t\tbool \"Extensible Scheduling Class\"\n 172:\t\tdepends on BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n 173:\t\tselect GENERIC_ALLOCATOR\n 174:\t\tselect STACKTRACE if STACKTRACE_SUPPORT\n 175:\t\thelp\n 176:\t\t This option enables a new scheduler class sched_ext (SCX), which\n 177:\t\t allows scheduling policies to be implemented as BPF programs to\n 178:\t\t achieve the following:\n 179:\t\n 180:\t\t - Ease of experimentation and exploration: Enabling rapid\n 181:\t\t iteration of new scheduling policies.\n 182:\t\t - Customization: Building application-specific schedulers which\n 183:\t\t implement policies that are not applicable to general-purpose\n 184:\t\t schedulers.\n 185:\t\t - Rapid scheduler deployments: Non-disruptive swap outs of\n 186:\t\t scheduling policies in production environments.\n 187:\t\n 188:\t\t sched_ext leverages BPF struct_ops feature to define a structure\n 189:\t\t which exports function callbacks and flags to BPF programs that\n 190:\t\t wish to implement scheduling policies. The struct_ops structure\n 191:\t\t exported by sched_ext is struct sched_ext_ops, and is conceptually\n 192:\t\t similar to struct sched_class.\n"
} |
| 13/2 | 2026/11/13 14:20 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35844 output: 32 thoughts: 141 Thoughts: **Analyzing the Scheduler Configuration Landscape** Okay, let's break down these kernel configurations and how they interrelate. My immediate focus is on the scheduler and resource management components. First, I need to understand which configurations are at play here: 1) CGROUPS and CGROUP\_SCHED are fundamental, and I know those work together. 2) FAIR\_GROUP\_SCHED is right up there. I need to remember how that impacts the scheduler. 3) CFS\_BANDWIDTH is the next important piece; I recall that it is dependent on FAIR\_GROUP\_SCHED and inherently selects GROUP\_SCHED\_BANDWIDTH. Makes sense. 4) Now, SCHED\_CLASS\_EXT is optional but crucial because it bridges the "sched\_ext" framework with CFS bandwidth through "SCX\_OPS\_CHARGE\_CPU\_MAX" and "cgroup\_set\_runtime." I have worked with this before. It is critical to get this working. It does require BPF\_SYSCALL. My next step is to examine the dependencies of CGROUP\_SCHED in "init/Kconfig." This gives me a clear picture of its base requirements and any related configurations that must be present for it to function correctly. This is the place to start. |
| 14/2 | 2026/11/13 14:20 | tool | grepper |
0mArgs:{
"Expression": "config CGROUP_SCHED",
"PathPrefixes": [
"init/Kconfig"
]
}Results: {
"Output": "init/Kconfig=943=config CGROUP_WRITEBACK\n--\ninit/Kconfig-947-\ninit/Kconfig:948:menuconfig CGROUP_SCHED\ninit/Kconfig-949-\tbool \"CPU controller\"\n"
} |
| 15/2 | 2026/11/13 14:20 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36365 output: 32 thoughts: 19 Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience: **Analyzing `init/Kconfig` for Configuration Options** Okay, let's dive into line 945 through 965 of `init/Kconfig`. I need to understand what configuration options are being presented in this section, and how they relate to the broader system initialization process. Given the context of `init/` I'm expecting this to cover something fundamental about early boot or core system features. My immediate goal is to quickly grasp the logical flow and dependencies within this configuration block. I'll be looking for things like: * **Choice Blocks:** Are we dealing with mutually exclusive options, or is this more of an additive configuration? * **Dependencies:** Are there `depends on` statements? What other configuration symbols are required or can be selected to enable these options? * **Help Text:** Is the accompanying help text clear and concise? Does it provide sufficient technical detail for someone to make an informed choice? Specifically, are there implications for other subsystems? * **Defaults:** What are the default values being set? Are they sensible defaults that work well in a wide range of use cases, or are they specific to a particular hardware/software configuration? * **Implications:** Beyond just what the options *do*, I also want to anticipate the potential implications of selecting these options. Does a configuration affect security, memory usage, or runtime performance? This specific range probably impacts boot loading or a key core OS feature. So, I will be looking closely for the relationships between this config and things like: * Memory management. * Security. * Early hardware initialization. Hopefully, it's well-structured, easy to parse, and doesn't introduce any unexpected complexity. Let's see what's in there. |
| 16/2 | 2026/11/13 14:20 | tool | read-file |
0mArgs:{
"File": "init/Kconfig",
"FirstLine": 945,
"LineCount": 20
}Results: {
"Contents": " 945:\t\tdepends on MEMCG \u0026\u0026 BLK_CGROUP\n 946:\t\tdefault y\n 947:\t\n 948:\tmenuconfig CGROUP_SCHED\n 949:\t\tbool \"CPU controller\"\n 950:\t\tdefault n\n 951:\t\thelp\n 952:\t\t This feature lets CPU scheduler recognize task groups and control CPU\n 953:\t\t bandwidth allocation to such task groups. It uses cgroups to group\n 954:\t\t tasks.\n 955:\t\n 956:\tif CGROUP_SCHED\n 957:\tconfig GROUP_SCHED_WEIGHT\n 958:\t\tdef_bool n\n 959:\t\n 960:\tconfig GROUP_SCHED_BANDWIDTH\n 961:\t\tdef_bool n\n 962:\t\n 963:\tconfig FAIR_GROUP_SCHED\n 964:\t\tbool \"Group scheduling for SCHED_OTHER\"\n"
} |
| 17/2 | 2026/11/13 14:20 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37063 output: 248 thoughts: 3075 Thoughts: **Analysis of CFS Bandwidth and sched_ext Integration for Fuzzing Focus** Alright, let's break this down systematically. I need to identify the key areas of this patch for fuzzing. First, `CFS_BANDWIDTH` is the core, depending on `FAIR_GROUP_SCHED` and `CGROUP_SCHED`, which themselves rely on `CGROUPS`. Then, there's the optional extension, `SCHED_CLASS_EXT`, which hooks into `sched_ext`. I'm seeing changes in `kernel/sched/core.c`, `kernel/sched/fair.c`, and `kernel/sched/ext/ext.c`, so I need to understand what's been added or modified in these files. Specifically, it looks like `cpu_runtime_write_u64` and `cpu_runtime_read_u64` in `core.c` are important entry points for user control via the `cpu.max.runtime` file. In `fair.c`, functions like `cfs_bandwidth_refill_idle_periods`, `cfs_bandwidth_get_runtime`, `cfs_bandwidth_set_runtime`, `cfs_bandwidth_charge_task`, `cfs_bandwidth_return_task`, and `cfs_bandwidth_task_runtime` are introduced or modified, which are all critical for the new quota and burst logic. Then there is `__refill_cfs_bandwidth_runtime` which is modified to handle debt. Finally, in `ext.c`, `scx_group_set_runtime` and `scx_bpf_task_cpu_max_runtime` are key for sched_ext integration. These seem very specific to the added feature, not generic. I need to decide which functions are suitable for `FocusSymbols`. Obviously, I can't include anything ubiquitous like memory allocators or synchronization primitives. Considering the stated guidelines, the functions added or modified must either be specific feature logic or entrypoints into the subsystem. That means generic functions like `update_curr_scx` and `dequeue_task_scx` are out, even if they're frequently called when sched_ext is running, because they are not directly implementing the new bandwidth logic. They aren't the heart of the changes. I need to double check the focus symbols one last time. `cpu_runtime_write_u64`, `cfs_bandwidth_set_runtime`, `cfs_bandwidth_get_runtime`, `cfs_bandwidth_refill_idle_periods`, `cfs_bandwidth_charge_task`, `cfs_bandwidth_return_task`, `cfs_bandwidth_task_runtime`, `scx_group_set_runtime` and `scx_bpf_task_cpu_max_runtime` are feature-specific entrypoints. The final Reasoning should be concise. The main points are: it's a new cgroup control file, allowing bursts; introduces new logic to manage unused quota, integrates this bandwidth tracking into sched_ext, tracking debts and introducing new BPF kfuncs. The changes are in core scheduler and cgroup code, and are completely user-accessible. |
| 18/2 | 2026/11/13 14:21 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"CFS_BANDWIDTH",
"CGROUP_SCHED",
"FAIR_GROUP_SCHED",
"SCHED_CLASS_EXT"
],
"FocusSymbols": [
"cfs_bandwidth_set_runtime",
"cfs_bandwidth_get_runtime",
"cfs_bandwidth_refill_idle_periods",
"cfs_bandwidth_charge_task",
"cfs_bandwidth_return_task",
"cfs_bandwidth_task_runtime",
"scx_group_set_runtime",
"scx_bpf_task_cpu_max_runtime",
"cpu_runtime_write_u64"
],
"Reasoning": "The patch introduces the cpu.max.runtime cgroup interface to allow reading and setting accumulated CPU runtime, changes burst bandwidth constraints, and integrates CFS bandwidth tracking with the sched_ext extensible scheduler class (including quota sharing, runtime debt tracking, and BPF kfuncs). These modifications affect core scheduler logic and cgroup control interfaces reachable from userspace in standard virtualized environments.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"CFS_BANDWIDTH",
"CGROUP_SCHED",
"FAIR_GROUP_SCHED",
"SCHED_CLASS_EXT"
],
"FocusSymbols": [
"cfs_bandwidth_set_runtime",
"cfs_bandwidth_get_runtime",
"cfs_bandwidth_refill_idle_periods",
"cfs_bandwidth_charge_task",
"cfs_bandwidth_return_task",
"cfs_bandwidth_task_runtime",
"scx_group_set_runtime",
"scx_bpf_task_cpu_max_runtime",
"cpu_runtime_write_u64"
],
"Reasoning": "The patch introduces the cpu.max.runtime cgroup interface to allow reading and setting accumulated CPU runtime, changes burst bandwidth constraints, and integrates CFS bandwidth tracking with the sched_ext extensible scheduler class (including quota sharing, runtime debt tracking, and BPF kfuncs). These modifications affect core scheduler logic and cgroup control interfaces reachable from userspace in standard virtualized environments.",
"WorthFuzzing": true
} |
| 19/1 | 2026/11/13 14:21 | action | If |
5mArgs:{
"WorthFuzzing": true
}Results: null |
| 20/2 | 2026/11/13 14:21 | agent | kmsan-evaluator |
5mModel:core Args: null Results: {
"KMSANReasoning": "The patch series updates CFS bandwidth control (relaxing the burst limit cap to allow bursts exceeding quota and accumulating unused runtime during idle periods) and introduces the `cpu.max.runtime` cgroup v2 interface along with BPF sched_ext integration (`SCX_OPS_CHARGE_CPU_MAX`, `cgroup_set_runtime`, and `scx_bpf_task_cpu_max_runtime`).\n\nKMSAN vs KASAN/LOCKDEP applicability:\n1. No uninitialized memory or info-leak risk:\n - The newly introduced cgroup file `cpu.max.runtime` interacts with user space solely via scalar `u64` read/write handlers (`cpu_runtime_read_u64` and `cpu_runtime_write_u64`), which seq_printf/parse textual numbers without copying raw kernel memory, buffers, or structs with padding to user space.\n - The new field `debt` in `struct cfs_bandwidth` is embedded in `struct task_group`, which is allocated using `__GFP_ZERO` (`kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO)`), ensuring zero-initialization.\n - All stack variables added in the new/modified functions in `kernel/sched/fair.c`, `kernel/sched/core.c`, and `kernel/sched/ext/ext.c` (such as `throttled`, `snap`, `held`, `idle_periods`, `floor`, etc.) are explicitly initialized before any read.\n - The sched_ext BPF kfunc returns a scalar `u64` value, and the struct_ops callback passes standard pointers and scalar values.\n\n2. Bug surface:\n - The risks in this changeset primarily involve synchronization/locking ordering (`tg_bandwidth_mutex`, `cfs_b-\u003elock`, runqueue locks), arithmetic/underflow/overflow in bandwidth and debt tracking, or task reference lifecycles. These classes of bugs are already addressed by LOCKDEP, UBSAN, and KASAN.\n\nTherefore, dedicated KMSAN fuzzing is not warranted.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d396475ecb337400ea2d7b99b7b993e3680b5228
Author: syz-cluster <triage@syzkaller.com>
Date: Fri Nov 13 14:16:07 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 9e3c67b02ae2e1..db9fa6e6dbd49e 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1231,12 +1231,37 @@ will be referred to. All time durations are in microseconds.
A read-write single value file which exists on non-root
cgroups. The default is "0".
- The burst in the range [0, $MAX].
+ The burst. The cgroup can accumulate the runtime it does not
+ use, up to $MAX + cpu.max.burst, also in the periods in which it
+ does not run. The burst may exceed $MAX, as long as $MAX +
+ cpu.max.burst is at most 2^44 - 1 (about 203 days).
This file affects only processes under the fair-class scheduler and a BPF
scheduler with the ``cgroup_set_bandwidth`` callback depending on what
the callback actually does.
+ cpu.max.runtime
+ A read-write single value file which exists on non-root
+ cgroups if the kernel is built with CONFIG_CFS_BANDWIDTH.
+
+ The runtime the cgroup has accumulated and not used yet, in
+ microseconds. Each period refills it by $MAX, up to $MAX +
+ cpu.max.burst, whether the cgroup runs in it or not. A read
+ returns at most $MAX + cpu.max.burst. A write sets it, up to
+ $MAX + cpu.max.burst, and lets a cgroup that ran out of runtime
+ run again at once. A write fails with EINVAL while $MAX is
+ "max".
+
+ The runtime does not include what the cgroup's CPUs already took
+ from it, at most a slice each (sched_cfs_bandwidth_slice_us).
+ A write leaves that with the CPUs.
+
+ This file affects only processes under the fair-class scheduler and a BPF
+ scheduler with the ``cgroup_set_runtime`` callback depending on what
+ the callback actually does. A BPF scheduler with the
+ ``SCX_OPS_CHARGE_CPU_MAX`` flag draws what its processes run from
+ the same runtime, so the cgroup's processes in both share it.
+
cpu.pressure
A read-write nested-keyed file.
diff --git a/Documentation/scheduler/sched-bwc.rst b/Documentation/scheduler/sched-bwc.rst
index e881a945c1888e..ccf7434ca73f0a 100644
--- a/Documentation/scheduler/sched-bwc.rst
+++ b/Documentation/scheduler/sched-bwc.rst
@@ -90,8 +90,8 @@ bandwidth restriction in place, such a group is described as an unconstrained
bandwidth group. This represents the traditional work-conserving behavior for
CFS.
-Writing any (valid) positive value(s) no smaller than cpu.cfs_burst_us will
-enact the specified bandwidth limit. The minimum quota allowed for the quota or
+Writing any (valid) positive value(s) will enact the specified bandwidth
+limit. The minimum quota allowed for the quota or
period is 1ms. There is also an upper bound on the period length of 1s.
Additional restrictions exist when bandwidth limits are used in a hierarchical
fashion, these are explained in more detail below.
@@ -101,9 +101,11 @@ and return the group to an unconstrained state once more.
A value of 0 for cpu.cfs_burst_us indicates that the group can not accumulate
any unused bandwidth. It makes the traditional bandwidth control behavior for
-CFS unchanged. Writing any (valid) positive value(s) no larger than
-cpu.cfs_quota_us into cpu.cfs_burst_us will enact the cap on unused bandwidth
-accumulation.
+CFS unchanged. Writing any (valid) positive value(s) into cpu.cfs_burst_us
+will enact the cap on unused bandwidth accumulation: the group can accumulate
+up to cpu.cfs_quota_us + cpu.cfs_burst_us, also over periods in which it does
+not run. The burst may be larger than the quota, as long as their sum is at
+most 2^44 - 1 microseconds (about 203 days).
Any updates to a group's bandwidth specification will result in it becoming
unthrottled if it is in a constrained state.
@@ -243,4 +245,4 @@ Examples
# echo 50000 > cpu.cfs_period_us /* period = 50ms */
# echo 10000 > cpu.cfs_burst_us /* burst = 10ms */
- Larger buffer setting (no larger than quota) allows greater burst capacity.
+ Larger buffer setting allows greater burst capacity.
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 175b52a7ea7938..25a4acb72106c7 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -9856,6 +9856,12 @@ static int tg_set_cfs_bandwidth(struct task_group *tg,
cfs_bandwidth_usage_inc();
scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
+ /*
+ * The new bandwidth applies from now on. The group keeps what
+ * it earned while idle under the old one.
+ */
+ cfs_bandwidth_refill_idle_periods(cfs_b);
+
cfs_b->period = ns_to_ktime(period);
cfs_b->quota = quota;
cfs_b->burst = burst;
@@ -10093,6 +10099,14 @@ static u64 cpu_period_read_u64(struct cgroup_subsys_state *css,
return period_us;
}
+/*
+ * Held across a bandwidth or runtime write and the sched_ext callback that
+ * follows it, so that the BPF scheduler gets the writes in the order the fair
+ * class applied them. The callback runs after the fair class's update has
+ * dropped cpus_read_lock() and cfs_constraints_mutex.
+ */
+static DEFINE_MUTEX(tg_bandwidth_mutex);
+
static int tg_set_bandwidth(struct task_group *tg,
u64 period_us, u64 quota_us, u64 burst_us)
{
@@ -10131,10 +10145,11 @@ static int tg_set_bandwidth(struct task_group *tg,
if (quota_us != RUNTIME_INF && quota_us > max_bw_runtime_us)
return -EINVAL;
- if (quota_us != RUNTIME_INF && (burst_us > quota_us ||
- burst_us + quota_us > max_bw_runtime_us))
+ if (quota_us != RUNTIME_INF && burst_us > max_bw_runtime_us - quota_us)
return -EINVAL;
+ guard(mutex)(&tg_bandwidth_mutex);
+
#ifdef CONFIG_CFS_BANDWIDTH
ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us);
#endif /* CONFIG_CFS_BANDWIDTH */
@@ -10193,6 +10208,40 @@ static int cpu_burst_write_u64(struct cgroup_subsys_state *css,
tg_bandwidth(tg, &period_us, "a_us, NULL);
return tg_set_bandwidth(tg, period_us, quota_us, burst_us);
}
+
+#ifdef CONFIG_CFS_BANDWIDTH
+static int cpu_runtime_write_u64(struct cgroup_subsys_state *css,
+ struct cftype *cftype, u64 runtime_us)
+{
+ struct task_group *tg = css_tg(css);
+ int ret;
+
+ if (runtime_us > max_bw_runtime_us)
+ return -EINVAL;
+
+ /*
+ * Serialize against tg_set_bandwidth(), so that the BPF scheduler gets
+ * the runtime checked against the current quota + burst, and this and
+ * cpu.max writes reach it in the order the fair class took them.
+ */
+ guard(mutex)(&tg_bandwidth_mutex);
+
+ ret = cfs_bandwidth_set_runtime(&tg->cfs_bandwidth,
+ runtime_us * NSEC_PER_USEC);
+ if (!ret)
+ scx_group_set_runtime(tg, runtime_us);
+ return ret;
+}
+
+static u64 cpu_runtime_read_u64(struct cgroup_subsys_state *css,
+ struct cftype *cftype)
+{
+ struct task_group *tg = css_tg(css);
+
+ return div_u64(cfs_bandwidth_get_runtime(&tg->cfs_bandwidth),
+ NSEC_PER_USEC);
+}
+#endif /* CONFIG_CFS_BANDWIDTH */
#endif /* CONFIG_GROUP_SCHED_BANDWIDTH */
#ifdef CONFIG_RT_GROUP_SCHED
@@ -10544,7 +10593,15 @@ static struct cftype cpu_files[] = {
.read_u64 = cpu_burst_read_u64,
.write_u64 = cpu_burst_write_u64,
},
+#ifdef CONFIG_CFS_BANDWIDTH
+ {
+ .name = "max.runtime",
+ .flags = CFTYPE_NOT_ON_ROOT,
+ .read_u64 = cpu_runtime_read_u64,
+ .write_u64 = cpu_runtime_write_u64,
+ },
#endif /* CONFIG_CFS_BANDWIDTH */
+#endif /* CONFIG_GROUP_SCHED_BANDWIDTH */
#ifdef CONFIG_UCLAMP_TASK_GROUP
{
.name = "uclamp.min",
diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index ebdf7b91f9d370..6ffc9ca2c5c9f1 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -1625,6 +1625,11 @@ static void expire_task_slice(struct task_struct *p)
scx_set_task_slice(p, 0);
}
+static bool scx_task_charges_cpu_max(const struct task_struct *p)
+{
+ return scx_task_sched(p)->ops.flags & SCX_OPS_CHARGE_CPU_MAX;
+}
+
static void update_curr_scx(struct rq *rq)
{
struct task_struct *donor;
@@ -1650,6 +1655,9 @@ static void update_curr_scx(struct rq *rq)
if (unlikely(donor == scx_rescuee(rq)))
scx_rescue_charge(rq, delta_exec);
+ if (scx_task_charges_cpu_max(donor))
+ cfs_bandwidth_charge_task(rq, donor, delta_exec);
+
dl_server_update(&rq->ext_server, delta_exec);
}
@@ -2605,6 +2613,13 @@ static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_
ops_dequeue(rq, p, deq_flags);
+ /* charge what @p ran, then return what @rq holds for its cgroups */
+ if (scx_task_charges_cpu_max(p)) {
+ if (task_current_donor(rq, p))
+ update_curr_scx(rq);
+ cfs_bandwidth_return_task(rq, p);
+ }
+
/*
* A current scheduling context which is going off @rq first gets
* dequeued and then stops running. As we want running <-> stopping
@@ -5817,6 +5832,19 @@ void scx_group_set_bandwidth(struct task_group *tg,
percpu_up_read(&scx_cgroup_ops_rwsem);
}
+
+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us)
+{
+ struct scx_sched *sch;
+
+ percpu_down_read(&scx_cgroup_ops_rwsem);
+ sch = scx_tg_knob_sched(tg);
+
+ if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_runtime))
+ SCX_CALL_OP(sch, cgroup_set_runtime, NULL, tg_cgrp(tg), runtime_us);
+
+ percpu_up_read(&scx_cgroup_ops_rwsem);
+}
#endif /* CONFIG_EXT_GROUP_SCHED */
#if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
@@ -9230,6 +9258,7 @@ static int bpf_scx_check_member(const struct btf_type *t,
case offsetof(struct sched_ext_ops, cgroup_exit):
case offsetof(struct sched_ext_ops, cgroup_prep_move):
case offsetof(struct sched_ext_ops, cgroup_set_bandwidth):
+ case offsetof(struct sched_ext_ops, cgroup_set_runtime):
#endif
case offsetof(struct sched_ext_ops, cpu_online):
case offsetof(struct sched_ext_ops, cpu_offline):
@@ -9392,6 +9421,7 @@ static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgro
static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
+static void sched_ext_ops__cgroup_set_runtime(struct cgroup *cgrp, u64 runtime_us) {}
#endif /* CONFIG_EXT_GROUP_SCHED */
static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
@@ -9434,6 +9464,7 @@ static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
.cgroup_set_weight = sched_ext_ops__cgroup_set_weight,
.cgroup_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth,
.cgroup_set_idle = sched_ext_ops__cgroup_set_idle,
+ .cgroup_set_runtime = sched_ext_ops__cgroup_set_runtime,
#endif
.sub_attach = sched_ext_ops__sub_attach,
.sub_detach = sched_ext_ops__sub_detach,
@@ -9502,6 +9533,7 @@ static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
.cpuctl_set_weight = sched_ext_ops__cgroup_set_weight,
.cpuctl_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth,
.cpuctl_set_idle = sched_ext_ops__cgroup_set_idle,
+ .cpuctl_set_runtime = sched_ext_ops__cgroup_set_runtime,
#endif
.sub_attach = sched_ext_ops__sub_attach,
.sub_detach = sched_ext_ops__sub_detach,
@@ -11776,6 +11808,24 @@ __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
return task_cpu(p);
}
+/**
+ * scx_bpf_task_cpu_max_runtime - Runtime a task has left under cpu.max
+ * @p: task of interest
+ *
+ * Return the runtime in nsecs that @p's cgroup and its ancestors have left
+ * under their cpu.max quotas for @p on its current CPU, the least over those
+ * with a quota: the cgroup's cpu.max.runtime plus what the CPU holds for
+ * the cgroup, less what it owes. U64_MAX if none limits it. Read without
+ * locks.
+ *
+ * With %SCX_OPS_CHARGE_CPU_MAX, the scheduler should run @p only while this
+ * returns more than 0. The runtime grows when a period refills it.
+ */
+__bpf_kfunc u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p)
+{
+ return cfs_bandwidth_task_runtime(p);
+}
+
/**
* scx_bpf_task_cid - cid a task is currently associated with
* @p: task of interest
@@ -12102,6 +12152,7 @@ BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
+BTF_ID_FLAGS(func, scx_bpf_task_cpu_max_runtime, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
@@ -12226,6 +12277,7 @@ static const u32 scx_kf_allow_flags[] = {
[SCX_OP_IDX(cgroup_set_weight)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(cgroup_set_idle)] = SCX_KF_ALLOW_UNLOCKED,
+ [SCX_OP_IDX(cgroup_set_runtime)] = SCX_KF_ALLOW_UNLOCKED,
#endif /* CONFIG_EXT_GROUP_SCHED */
[SCX_OP_IDX(sub_attach)] = SCX_KF_ALLOW_UNLOCKED,
[SCX_OP_IDX(sub_detach)] = SCX_KF_ALLOW_UNLOCKED,
@@ -12395,6 +12447,7 @@ static int __init scx_init(void)
CID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight);
CID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth);
CID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle);
+ CID_OFFSET_MATCH(cgroup_set_runtime, cpuctl_set_runtime);
#endif
/* @priv tail must align since both share the same data block */
CID_OFFSET_MATCH(priv, priv);
diff --git a/kernel/sched/ext/ext.h b/kernel/sched/ext/ext.h
index d32bc01071b01a..6d1ce582bf7240 100644
--- a/kernel/sched/ext/ext.h
+++ b/kernel/sched/ext/ext.h
@@ -94,6 +94,7 @@ void scx_cgroup_cancel_attach(struct cgroup_taskset *tset);
void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight);
void scx_group_set_idle(struct task_group *tg, bool idle);
void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us);
+void scx_group_set_runtime(struct task_group *tg, u64 runtime_us);
#else /* CONFIG_EXT_GROUP_SCHED */
static inline void scx_tg_init(struct task_group *tg) {}
static inline int scx_tg_online(struct task_group *tg) { return 0; }
@@ -104,5 +105,6 @@ static inline void scx_cgroup_cancel_attach(struct cgroup_taskset *tset) {}
static inline void scx_group_set_weight(struct task_group *tg, unsigned long cgrp_weight) {}
static inline void scx_group_set_idle(struct task_group *tg, bool idle) {}
static inline void scx_group_set_bandwidth(struct task_group *tg, u64 period_us, u64 quota_us, u64 burst_us) {}
+static inline void scx_group_set_runtime(struct task_group *tg, u64 runtime_us) {}
#endif /* CONFIG_EXT_GROUP_SCHED */
#endif /* CONFIG_CGROUP_SCHED */
diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h
index ff0a3d508533f0..e8c0b573d0a434 100644
--- a/kernel/sched/ext/internal.h
+++ b/kernel/sched/ext/internal.h
@@ -243,6 +243,27 @@ enum scx_ops_flags {
*/
SCX_OPS_ENQ_BLOCKED = 1LLU << 10,
+ /*
+ * If set, what the scheduler's tasks run is charged to the cpu.max
+ * bandwidth of their cgroups, the runtime the fair class keeps and
+ * cpu.max.runtime reads, as what fair tasks run is. The tasks of a
+ * cgroup in both classes then share one quota, also with
+ * %SCX_OPS_SWITCH_PARTIAL, and nothing is handed over when tasks
+ * switch class.
+ *
+ * The kernel never throttles the scheduler's tasks. The scheduler
+ * enforces the quota by running a task only while
+ * scx_bpf_task_cpu_max_runtime() returns more than 0. What a task runs
+ * beyond that is charged: up to a slice (sched_cfs_bandwidth_slice_us)
+ * per CPU as a debt the cgroup's fair tasks on that CPU pay back, and up
+ * to a quota more from the cgroup's next period. The scheduler does not
+ * need ops.cgroup_set_runtime(), as a write of cpu.max.runtime sets that
+ * runtime.
+ *
+ * Without CONFIG_CFS_BANDWIDTH, this flag has no effect.
+ */
+ SCX_OPS_CHARGE_CPU_MAX = 1LLU << 11,
+
SCX_OPS_ALL_FLAGS = SCX_OPS_KEEP_BUILTIN_IDLE |
SCX_OPS_ENQ_LAST |
SCX_OPS_ENQ_EXITING |
@@ -253,7 +274,8 @@ enum scx_ops_flags {
SCX_OPS_ALWAYS_ENQ_IMMED |
SCX_OPS_TID_TO_TASK |
SCX_OPS_LAZY_RESCHED |
- SCX_OPS_ENQ_BLOCKED,
+ SCX_OPS_ENQ_BLOCKED |
+ SCX_OPS_CHARGE_CPU_MAX,
/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
__SCX_OPS_INTERNAL_MASK = 0xffLLU << 56,
@@ -863,6 +885,26 @@ struct sched_ext_ops {
*/
void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
+ /**
+ * @cgroup_set_runtime: A cgroup's runtime is being set
+ * @cgrp: cgroup whose runtime is being set
+ * @runtime_us: runtime in microseconds
+ *
+ * Set the runtime @cgrp has accumulated and not used yet to
+ * @runtime_us. This is from the cpu.max.runtime cgroup interface,
+ * which exists with CONFIG_CFS_BANDWIDTH only. It is called on every
+ * write, also of an unchanged value. The runtime goes down as @cgrp
+ * runs, so a write of the same value is a top-up.
+ *
+ * @cgrp has a quota, and @runtime_us is at most the quota + burst the
+ * scheduler was last given, by @cgroup_init or @cgroup_set_bandwidth:
+ * cpu.max and cpu.max.runtime writes reach the scheduler in the order
+ * the fair class applied them.
+ *
+ * Delivery follows the same rule as cgroup_set_weight().
+ */
+ void (*cgroup_set_runtime)(struct cgroup *cgrp, u64 runtime_us);
+
#endif /* CONFIG_EXT_GROUP_SCHED */
/**
@@ -1239,6 +1281,7 @@ struct sched_ext_ops_cid {
void (*cpuctl_set_bandwidth)(struct cgroup *cgrp, u64 period_us, u64 quota_us,
u64 burst_us);
void (*cpuctl_set_idle)(struct cgroup *cgrp, bool idle);
+ void (*cpuctl_set_runtime)(struct cgroup *cgrp, u64 runtime_us);
#endif /* CONFIG_EXT_GROUP_SCHED */
s32 (*sub_attach)(struct scx_sub_attach_args *args);
void (*sub_detach)(struct scx_sub_detach_args *args);
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index d4cc0caee6265d..9ff239f122bdaa 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -6875,6 +6875,11 @@ void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
}
cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
+
+ /* pay the debt cfs_bandwidth_charge_task() left */
+ runtime = min(cfs_b->runtime, cfs_b->debt);
+ cfs_b->runtime -= runtime;
+ cfs_b->debt -= runtime;
cfs_b->runtime_snap = cfs_b->runtime;
}
@@ -7421,6 +7426,8 @@ static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
struct cfs_rq *cfs_rq;
struct rq *rq;
+ lockdep_assert_irqs_disabled();
+
guard(rcu)();
list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
@@ -7811,6 +7818,140 @@ static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
}
+/*
+ * Runtime after @periods refills of quota, capped at quota + burst as each
+ * refill in __refill_cfs_bandwidth_runtime() caps it. The runtime can be above
+ * the cap (__return_cfs_rq_runtime() does not cap it), and a refill then cuts
+ * it to the cap.
+ */
+static u64 cfs_bandwidth_refilled(struct cfs_bandwidth *cfs_b, u64 periods)
+{
+ u64 cap = cfs_b->quota + cfs_b->burst;
+ u64 runtime = cfs_b->runtime;
+
+ if (!periods || cfs_b->quota == RUNTIME_INF)
+ return runtime;
+ if (runtime >= cap ||
+ periods >= div64_u64(cap - runtime, cfs_b->quota) + 1)
+ return cap;
+ return runtime + periods * cfs_b->quota;
+}
+
+/*
+ * The period timer stops after a period in which the group took no runtime
+ * (do_sched_cfs_period_timer()), and start_cfs_bandwidth() restarts it on
+ * the next demand. The periods it slept through refill quota too: unused
+ * quota accumulates up to quota + burst whether or not the group ran. While
+ * the timer is stopped its expiry is the first period boundary it missed,
+ * so the boundaries passed since then are the refills still owed.
+ *
+ * Without burst the cap is quota. The timer stops right after a refill that
+ * nothing drew from, so the runtime is at quota then, and this changes nothing
+ * for groups without a burst.
+ *
+ * This is the overrun that hrtimer_forward_now() returns, without moving the
+ * expiry: one for the expiry itself, plus one for each full period since.
+ */
+static u64 cfs_bandwidth_idle_periods(struct cfs_bandwidth *cfs_b)
+{
+ ktime_t now = ktime_get();
+ s64 delta;
+
+ if (cfs_b->period_active)
+ return 0;
+
+ delta = ktime_to_ns(ktime_sub(now, hrtimer_get_expires(&cfs_b->period_timer)));
+ if (delta < 0)
+ return 0;
+ return div64_u64(delta, ktime_to_ns(cfs_b->period)) + 1;
+}
+
+/*
+ * Refill the periods a stopped timer slept through, at the bandwidth they
+ * were earned under, and move its expiry past them so that they are not
+ * counted again. A change of the bandwidth or a cpu.max.runtime write calls
+ * this first, so that the change applies from then on and the group keeps
+ * what it earned before. A group without a quota earned nothing.
+ */
+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b)
+{
+ u64 idle_periods;
+
+ lockdep_assert_held(&cfs_b->lock);
+
+ if (cfs_b->period_active)
+ return;
+
+ idle_periods = hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
+ cfs_b->runtime = cfs_bandwidth_refilled(cfs_b, idle_periods);
+ cfs_b->runtime_snap = cfs_b->runtime;
+}
+
+/*
+ * The runtime of @cfs_b, as cpu.max.runtime reads it.
+ *
+ * __return_cfs_rq_runtime() returns slack without capping it, so the runtime
+ * can exceed quota + burst until the next refill caps it. Report it capped,
+ * so that a value read can always be written back.
+ */
+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b)
+{
+ u64 runtime;
+
+ guard(raw_spinlock_irq)(&cfs_b->lock);
+
+ runtime = cfs_bandwidth_refilled(cfs_b, cfs_bandwidth_idle_periods(cfs_b));
+ if (cfs_b->quota != RUNTIME_INF)
+ runtime = min(runtime, cfs_b->quota + cfs_b->burst);
+
+ return runtime;
+}
+
+/*
+ * Set the runtime of @cfs_b, as a cpu.max.runtime write does, and hand it to
+ * the throttled cfs_rqs at once rather than at the next period.
+ */
+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime)
+{
+ bool throttled;
+ s64 snap;
+
+ guard(irq)();
+
+ scoped_guard (raw_spinlock, &cfs_b->lock) {
+ if (cfs_b->quota == RUNTIME_INF ||
+ runtime > cfs_b->quota + cfs_b->burst)
+ return -EINVAL;
+
+ /*
+ * Refill the periods that passed before the write, so that the
+ * write replaces them and only the periods after it refill.
+ */
+ cfs_bandwidth_refill_idle_periods(cfs_b);
+
+ /*
+ * The next refill counts runtime_snap - runtime as burst usage.
+ * Move runtime_snap by what the write adds or takes away, so
+ * that the write itself is not counted as burst usage but what
+ * the group ran since the last refill still is.
+ */
+ snap = cfs_b->runtime_snap + runtime - cfs_b->runtime;
+ cfs_b->runtime_snap = max(snap, 0);
+ cfs_b->runtime = runtime;
+
+ throttled = !list_empty(&cfs_b->throttled_cfs_rq) && runtime;
+ }
+
+ /*
+ * distribute_cfs_runtime() takes the rq locks, so it runs without
+ * cfs_b->lock and with interrupts disabled, as from the slack timer.
+ */
+ if (throttled)
+ distribute_cfs_runtime(cfs_b);
+
+ return 0;
+}
+
void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
{
lockdep_assert_held(&cfs_b->lock);
@@ -7818,8 +7959,8 @@ void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
if (cfs_b->period_active)
return;
+ cfs_bandwidth_refill_idle_periods(cfs_b);
cfs_b->period_active = 1;
- hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
}
@@ -7940,6 +8081,123 @@ bool cfs_task_bw_constrained(struct task_struct *p)
return false;
}
+/*
+ * Charge @delta_exec, which @p ran on @rq outside the fair class, to the
+ * bandwidth of its task group and of each ancestor with a quota, as
+ * account_cfs_rq_runtime() charges a fair task. A cfs_rq that runs out takes
+ * another slice from cfs_b, but @p is never throttled: the BPF scheduler that
+ * runs it stops it, and the group's fair tasks are throttled when they run.
+ *
+ * Debt below -slice that cfs_b cannot cover moves to cfs_b, up to a quota,
+ * and the next refill pays it, so that a scheduler which keeps running @p
+ * cannot put the group's fair tasks on @rq in more debt than a slice.
+ */
+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,
+ u64 delta_exec)
+{
+ s64 floor = -(s64)sched_cfs_bandwidth_slice();
+ struct task_group *tg;
+
+ lockdep_assert_rq_held(rq);
+
+ if (!cfs_bandwidth_used())
+ return;
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
+
+ if (!cfs_rq->runtime_enabled)
+ continue;
+
+ cfs_rq->runtime_remaining -= delta_exec;
+
+ /*
+ * A throttled cfs_rq gets runtime from distribute_cfs_runtime().
+ * Without runtime, an active period timer refills it, so skip
+ * the lock. A stopped one is restarted by the assign.
+ */
+ if (cfs_rq->runtime_remaining <= 0 && !cfs_rq->throttled &&
+ (READ_ONCE(cfs_b->runtime) || !READ_ONCE(cfs_b->period_active))) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ __assign_cfs_rq_runtime(cfs_b, cfs_rq,
+ sched_cfs_bandwidth_slice());
+ }
+
+ if (cfs_rq->runtime_remaining < floor) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ cfs_b->debt = min_t(u64, cfs_b->debt + floor -
+ cfs_rq->runtime_remaining, cfs_b->quota);
+ cfs_rq->runtime_remaining = floor;
+ }
+ }
+}
+
+/*
+ * @p leaves @rq: give the runtime @rq holds for its groups back, less
+ * min_cfs_rq_runtime, as a fair dequeue does when a cfs_rq empties. Pay
+ * what @rq owes from cfs_b, as @p may not run on @rq again.
+ */
+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p)
+{
+ struct task_group *tg;
+
+ lockdep_assert_rq_held(rq);
+
+ if (!cfs_bandwidth_used())
+ return;
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq));
+
+ return_cfs_rq_runtime(cfs_rq);
+
+ if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining < 0 &&
+ !cfs_rq->throttled && READ_ONCE(cfs_b->runtime)) {
+ scoped_guard (raw_spinlock, &cfs_b->lock)
+ __assign_cfs_rq_runtime(cfs_b, cfs_rq, 0);
+ }
+ }
+}
+
+/*
+ * The runtime @p's groups have left for it on its CPU, without locks: the
+ * least, over the groups with a quota, of what the CPU holds or owes and
+ * cfs_b's runtime. Debt counts up to a quota less 1ns, so that a full period
+ * lets @p run and pay the rest. A group whose period timer is stopped does
+ * not count, as the next charge restarts the timer and refills what it owes.
+ * RUNTIME_INF if no group counts.
+ */
+u64 cfs_bandwidth_task_runtime(struct task_struct *p)
+{
+ u64 runtime = RUNTIME_INF;
+ struct task_group *tg;
+ int cpu = task_cpu(p);
+
+ if (!cfs_bandwidth_used())
+ return runtime;
+
+ guard(rcu)();
+
+ for (tg = task_group(p); tg; tg = tg->parent) {
+ struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
+ struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu);
+ s64 held;
+
+ if (!READ_ONCE(cfs_rq->runtime_enabled) ||
+ !READ_ONCE(cfs_b->period_active))
+ continue;
+
+ held = max_t(s64, READ_ONCE(cfs_rq->runtime_remaining),
+ 1 - (s64)READ_ONCE(cfs_b->quota));
+ held += READ_ONCE(cfs_b->runtime);
+ runtime = min_t(u64, runtime, max_t(s64, held, 0));
+ }
+
+ return runtime;
+}
+
#ifdef CONFIG_NO_HZ_FULL
/* called from pick_next_task_fair() */
static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index a4df59c9c9b601..fd98000ffd7449 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -456,6 +456,7 @@ struct cfs_bandwidth {
u64 runtime;
u64 burst;
u64 runtime_snap;
+ u64 debt;
s64 hierarchical_quota;
u8 idle;
@@ -578,6 +579,9 @@ extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth
extern void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b);
extern void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b);
+u64 cfs_bandwidth_get_runtime(struct cfs_bandwidth *cfs_b);
+int cfs_bandwidth_set_runtime(struct cfs_bandwidth *cfs_b, u64 runtime);
+void cfs_bandwidth_refill_idle_periods(struct cfs_bandwidth *cfs_b);
extern void unthrottle_cfs_rq(struct cfs_rq *cfs_rq);
extern bool cfs_task_bw_constrained(struct task_struct *p);
@@ -618,6 +622,17 @@ static inline bool cfs_task_bw_constrained(struct task_struct *p) { return false
#endif /* !CONFIG_CGROUP_SCHED */
+#ifdef CONFIG_CFS_BANDWIDTH
+void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p, u64 delta_exec);
+void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p);
+u64 cfs_bandwidth_task_runtime(struct task_struct *p);
+#else
+static inline void cfs_bandwidth_charge_task(struct rq *rq, struct task_struct *p,
+ u64 delta_exec) { }
+static inline void cfs_bandwidth_return_task(struct rq *rq, struct task_struct *p) { }
+static inline u64 cfs_bandwidth_task_runtime(struct task_struct *p) { return RUNTIME_INF; }
+#endif
+
/*
* A weight of 0 or 1 can cause arithmetics problems.
* A weight of a cfs_rq is the sum of weights of which entities
diff --git a/tools/sched_ext/include/scx/common.bpf.h b/tools/sched_ext/include/scx/common.bpf.h
index 6194484d4d9a99..cfb7f1b70665fc 100644
--- a/tools/sched_ext/include/scx/common.bpf.h
+++ b/tools/sched_ext/include/scx/common.bpf.h
@@ -98,6 +98,7 @@ s32 scx_bpf_pick_any_cpu_node(const cpumask_t *cpus_allowed, int node, u64 flags
s32 scx_bpf_pick_any_cpu(const cpumask_t *cpus_allowed, u64 flags) __ksym;
bool scx_bpf_task_running(const struct task_struct *p) __ksym;
s32 scx_bpf_task_cpu(const struct task_struct *p) __ksym;
+u64 scx_bpf_task_cpu_max_runtime(struct task_struct *p) __ksym __weak;
struct rq *scx_bpf_cpu_rq(s32 cpu) __ksym __weak;
struct rq *scx_bpf_locked_rq(void) __ksym;
struct task_struct *scx_bpf_cpu_curr(s32 cpu) __ksym __weak;
diff --git a/tools/sched_ext/include/scx/compat.h b/tools/sched_ext/include/scx/compat.h
index 07fb55e63c57c5..60b9972f1a5dc2 100644
--- a/tools/sched_ext/include/scx/compat.h
+++ b/tools/sched_ext/include/scx/compat.h
@@ -215,6 +215,7 @@ static inline bool __COMPAT_struct_has_field(const char *type, const char *field
#define SCX_OPS_BUILTIN_IDLE_PER_NODE SCX_OPS_FLAG(SCX_OPS_BUILTIN_IDLE_PER_NODE)
#define SCX_OPS_ALWAYS_ENQ_IMMED SCX_OPS_FLAG(SCX_OPS_ALWAYS_ENQ_IMMED)
#define SCX_OPS_ENQ_BLOCKED SCX_OPS_FLAG(SCX_OPS_ENQ_BLOCKED)
+#define SCX_OPS_CHARGE_CPU_MAX SCX_OPS_FLAG(SCX_OPS_CHARGE_CPU_MAX)
#define SCX_PICK_IDLE_FLAG(name) __COMPAT_ENUM_OR_ZERO("scx_pick_idle_cpu_flags", #name)
diff --git a/tools/testing/selftests/cgroup/test_cpu.c b/tools/testing/selftests/cgroup/test_cpu.c
index 3456e3e988c68a..04a061da514cec 100644
--- a/tools/testing/selftests/cgroup/test_cpu.c
+++ b/tools/testing/selftests/cgroup/test_cpu.c
@@ -809,6 +809,517 @@ static int test_cpucg_max_nested(const char *root)
return ret;
}
+/* Wait until the period timer of @cgroup starts a new period. */
+static int wait_period_start(const char *cgroup)
+{
+ long nr_periods = cg_read_key_long(cgroup, "cpu.stat", "nr_periods");
+ int i;
+
+ for (i = 0; i < 3000; i++) {
+ usleep(1000);
+ if (cg_read_key_long(cgroup, "cpu.stat", "nr_periods") != nr_periods)
+ return 0;
+ }
+ return -1;
+}
+
+static long long monotonic_ns(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000000000LL + ts.tv_nsec;
+}
+
+/* For (long)arg seconds, run for 1ms and then sleep for 10ms. */
+static int run_and_sleep(const char *cgroup, void *arg)
+{
+ long long end = monotonic_ns() + (long)arg * 1000000000LL;
+ long long start;
+
+ while ((start = monotonic_ns()) < end) {
+ while (monotonic_ns() - start < 1000000)
+ ;
+ usleep(10000);
+ }
+ return 0;
+}
+
+static int test_cpucg_max_runtime(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 1000; /* 1ms (minimum) */
+ long period_usec = 100000; /* 100ms */
+ long burst_usec = 5000000; /* 5s, so cap = 5001ms */
+ long runtime_usec = 2500000; /* 2500ms, half of the 5s run */
+ long duration_sec = 5;
+ /* The injected runtime plus the quota refilled each period of the run */
+ long expected_usec = runtime_usec +
+ duration_sec * USEC_PER_SEC / period_usec * quota_usec;
+ long usage_usec;
+ char *cpucg;
+ char buf[64];
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* Without a quota there is no runtime to set. */
+ if (!cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", burst_usec))
+ goto cleanup;
+
+ /* Start burner, let it settle, then inject credits */
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = duration_sec, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ usleep(100000);
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec)) {
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ goto cleanup;
+ }
+
+ waitpid(pid, NULL, 0);
+
+ usage_usec = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (usage_usec <= 0)
+ goto cleanup;
+
+ /* At least the injected runtime, at most 5% above the expected usage. */
+ if (usage_usec < runtime_usec ||
+ usage_usec > expected_usec + expected_usec / 20)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write is not burst usage: writing a runtime below the
+ * current one leaves cpu.stat's nr_bursts and burst_usec where they were.
+ */
+static int test_cpucg_max_runtime_burst_stats(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long nr_bursts, burst_usec;
+ char *cpucg;
+
+ cpucg = cg_name(root, "cpucg_runtime_burst_stats_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* A long period, so the write lands before the timer's first refill. */
+ if (cg_write(cpucg, "cpu.max", "10000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 0))
+ goto cleanup;
+
+ /* The idle group refills for a few periods. */
+ sleep(3);
+ nr_bursts = cg_read_key_long(cpucg, "cpu.stat", "nr_bursts");
+ burst_usec = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ if (nr_bursts != 0 || burst_usec != 0)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write hands the runtime to a throttled group at once,
+ * rather than at the next period: with a 1s period, the group runs again
+ * within 100ms of the write, before the next period starts.
+ */
+static int test_cpucg_max_runtime_unthrottle(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long usage_before, usage_after, nr_periods;
+ char *cpucg;
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_unthrottle_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* 1ms per 1s period, with room for a runtime of up to 1s. */
+ if (cg_write(cpucg, "cpu.max", "1000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 999000))
+ goto cleanup;
+
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = 2, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ /*
+ * The period timer's phase is random: start right after a boundary,
+ * so that the next one is some 900ms away. The hog uses up its runtime
+ * and is throttled for the period.
+ */
+ if (wait_period_start(cpucg))
+ goto cleanup_hog;
+ nr_periods = cg_read_key_long(cpucg, "cpu.stat", "nr_periods");
+ usleep(50000);
+ usage_before = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (usage_before < 0 || usage_before > 20000)
+ goto cleanup_hog;
+
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 500000))
+ goto cleanup_hog;
+
+ /* No period started meanwhile: only the write lets the hog run. */
+ usleep(100000);
+ usage_after = cg_read_key_long(cpucg, "cpu.stat", "usage_usec");
+ if (cg_read_key_long(cpucg, "cpu.stat", "nr_periods") != nr_periods)
+ goto cleanup_hog;
+ if (usage_after - usage_before < 50000)
+ goto cleanup_hog;
+
+ ret = KSFT_PASS;
+
+cleanup_hog:
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * What a group ran beyond its quota before a cpu.max.runtime write is still
+ * burst usage: a write of the runtime the group has left does not hide it.
+ */
+static int test_cpucg_max_runtime_burst_kept(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long burst_before, burst_after, runtime_usec;
+ char *cpucg;
+ int pid;
+
+ cpucg = cg_name(root, "cpucg_runtime_burst_kept_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ /* 10ms per 1s period, and a runtime of 1s to run on. */
+ if (cg_write(cpucg, "cpu.max", "10000 1000000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 990000))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 1000000))
+ goto cleanup;
+
+ struct cpu_hog_func_param param = {
+ .nprocs = 1,
+ .ts = { .tv_sec = 10, .tv_nsec = 0 },
+ .clock_type = CPU_HOG_CLOCK_WALL,
+ };
+ pid = cg_run_nowait(cpucg, hog_cpus_timed, (void *)¶m);
+ if (pid < 0)
+ goto cleanup;
+
+ /* Run some 300ms, all in one period, and stop. */
+ if (wait_period_start(cpucg)) {
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ goto cleanup;
+ }
+ burst_before = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ usleep(300000);
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+
+ /* Write back what is left: the next refill counts the 300ms run. */
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup;
+ sleep(1);
+ burst_after = cg_read_key_long(cpucg, "cpu.stat", "burst_usec");
+ if (burst_before < 0 || burst_after - burst_before < 250000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * cpu.max.runtime reads at most quota + burst, so that a value read can be
+ * written back. A cfs_rq that dequeues returns its unused runtime, which can
+ * take the runtime above quota + burst until the next refill caps it: run
+ * tasks that keep doing that, and read and write back the runtime meanwhile.
+ */
+static int test_cpucg_max_runtime_read_capped(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long cap_usec = 100000; /* quota 100ms, no burst */
+ long long end;
+ long runtime_usec;
+ char *cpucg;
+ int pids[2];
+ int i, n = 0;
+
+ cpucg = cg_name(root, "cpucg_runtime_read_capped_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ if (cg_write(cpucg, "cpu.max", "100000 100000"))
+ goto cleanup;
+
+ for (n = 0; n < 2; n++) {
+ pids[n] = cg_run_nowait(cpucg, run_and_sleep, (void *)4L);
+ if (pids[n] < 0)
+ goto cleanup_tasks;
+ }
+
+ end = monotonic_ns() + 3000000000LL;
+ while (monotonic_ns() < end) {
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 0 || runtime_usec > cap_usec)
+ goto cleanup_tasks;
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", runtime_usec))
+ goto cleanup_tasks;
+ }
+
+ ret = KSFT_PASS;
+
+cleanup_tasks:
+ for (i = 0; i < n; i++) {
+ kill(pids[i], SIGKILL);
+ waitpid(pids[i], NULL, 0);
+ }
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A group with a burst keeps earning quota while it is idle, up to
+ * quota + burst, and cpu.max.runtime reads what it has earned. Without a
+ * burst the runtime stays at quota.
+ */
+static int test_cpucg_max_idle_refill(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 10000; /* 10ms */
+ long period_usec = 100000; /* 100ms */
+ long burst_usec = 990000; /* cap 1s */
+ long runtime_usec;
+ char *cpucg;
+ char buf[64];
+
+ cpucg = cg_name(root, "cpucg_idle_refill_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+
+ /* No burst: the runtime stays at quota while idle. */
+ sleep(1);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != quota_usec)
+ goto cleanup;
+
+ /* Burst: the write refills once (20ms), then 1s idle earns 10 more. */
+ if (cg_write_numeric(cpucg, "cpu.max.burst", burst_usec))
+ goto cleanup;
+ sleep(1);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 110000 || runtime_usec > 130000)
+ goto cleanup;
+
+ /* Capped at quota + burst. */
+ sleep(10);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != quota_usec + burst_usec)
+ goto cleanup;
+
+ /*
+ * A write sets the runtime from now on: 500ms later, five refills, or
+ * six if the sleep overruns into the next period.
+ */
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 0))
+ goto cleanup;
+ usleep(500000);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 50000 || runtime_usec > 60000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max or cpu.max.burst write applies from then on: what a group with
+ * a quota earned while idle is kept, capped at the new quota + burst, and a
+ * group that had no quota has earned nothing while it had none.
+ */
+static int test_cpucg_max_idle_refill_write(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long quota_usec = 10000; /* 10ms */
+ long period_usec = 100000; /* 100ms */
+ long runtime_usec;
+ char *cpucg = NULL, *fresh = NULL;
+ char buf[64];
+
+ cpucg = cg_name(root, "cpucg_idle_refill_write_test");
+ fresh = cg_name(root, "cpucg_idle_refill_fresh_test");
+ if (!cpucg || !fresh)
+ goto cleanup;
+
+ if (cg_create(cpucg) || cg_create(fresh))
+ goto cleanup;
+
+ snprintf(buf, sizeof(buf), "%ld %ld", quota_usec, period_usec);
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+
+ /* 3s idle fills the group to quota + burst. */
+ sleep(3);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 200000)
+ goto cleanup;
+
+ /* Writing the same cpu.max keeps what the group earned. */
+ if (cg_write(cpucg, "cpu.max", buf))
+ goto cleanup;
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 200000)
+ goto cleanup;
+
+ /* A lower burst keeps it too, capped at the new quota + burst. */
+ sleep(2);
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 90000))
+ goto cleanup;
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 100000)
+ goto cleanup;
+
+ /* A group given a quota after idling without one starts with a refill. */
+ if (cg_write_numeric(fresh, "cpu.max.burst", 190000))
+ goto cleanup;
+ sleep(2);
+ if (cg_write(fresh, "cpu.max", buf))
+ goto cleanup;
+ runtime_usec = cg_read_long(fresh, "cpu.max.runtime");
+ if (runtime_usec != quota_usec)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ if (fresh)
+ cg_destroy(fresh);
+ if (cpucg)
+ cg_destroy(cpucg);
+ free(fresh);
+ free(cpucg);
+ return ret;
+}
+
+/*
+ * A cpu.max.runtime write sets the runtime exactly, and only the periods
+ * after it refill.
+ */
+static int test_cpucg_max_idle_refill_runtime_write(const char *root)
+{
+ int ret = KSFT_FAIL;
+ long runtime_usec;
+ char *cpucg;
+
+ cpucg = cg_name(root, "cpucg_idle_refill_runtime_test");
+ if (!cpucg)
+ goto cleanup;
+
+ if (cg_create(cpucg))
+ goto cleanup;
+
+ if (cg_write(cpucg, "cpu.max", "10000 100000"))
+ goto cleanup;
+ if (cg_write_numeric(cpucg, "cpu.max.burst", 190000))
+ goto cleanup;
+
+ sleep(3);
+ if (cg_write_numeric(cpucg, "cpu.max.runtime", 30000))
+ goto cleanup;
+ /* One refill if a period boundary passes before the read. */
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec != 30000 && runtime_usec != 40000)
+ goto cleanup;
+
+ /* 250ms after the write: two or three refills, by the boundaries. */
+ usleep(250000);
+ runtime_usec = cg_read_long(cpucg, "cpu.max.runtime");
+ if (runtime_usec < 50000 || runtime_usec > 60000)
+ goto cleanup;
+
+ ret = KSFT_PASS;
+
+cleanup:
+ cg_destroy(cpucg);
+ free(cpucg);
+ return ret;
+}
+
#define T(x) { x, #x }
struct cpucg_test {
int (*fn)(const char *root);
@@ -823,6 +1334,14 @@ struct cpucg_test {
T(test_cpucg_nested_weight_underprovisioned),
T(test_cpucg_max),
T(test_cpucg_max_nested),
+ T(test_cpucg_max_runtime),
+ T(test_cpucg_max_runtime_burst_stats),
+ T(test_cpucg_max_runtime_unthrottle),
+ T(test_cpucg_max_runtime_burst_kept),
+ T(test_cpucg_max_runtime_read_capped),
+ T(test_cpucg_max_idle_refill),
+ T(test_cpucg_max_idle_refill_write),
+ T(test_cpucg_max_idle_refill_runtime_write),
};
#undef T
diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile
index c5d3a2eaea7da2..4a727b8dc7aabc 100644
--- a/tools/testing/selftests/sched_ext/Makefile
+++ b/tools/testing/selftests/sched_ext/Makefile
@@ -165,6 +165,7 @@ all_test_bpfprogs := $(foreach prog,$(wildcard *.bpf.c),$(INCLUDE_DIR)/$(patsubs
auto-test-targets := \
cgroup_nr_cpus \
+ cgroup_runtime \
create_dsq \
dequeue \
dequeue_iter \
diff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c
new file mode 100644
index 00000000000000..ec98a25d19c291
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.bpf.c
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A scheduler with SCX_OPS_CHARGE_CPU_MAX, for the cgroup_runtime tests. It
+ * runs a task only while scx_bpf_task_cpu_max_runtime() says it has runtime
+ * left, unless @ignore_runtime is set. A task that has none waits in HELD_DSQ,
+ * and a timer kicks the idle CPUs every millisecond, so that they take it
+ * once a period refills the runtime.
+ *
+ * partial_ops sets SCX_OPS_SWITCH_PARTIAL and full_ops does not. Both pass
+ * the cpu.max and cpu.max.runtime writes of @cgid on to the test.
+ */
+
+#include <scx/common.bpf.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define HELD_DSQ 0
+#define KICK_NS 1000000
+
+UEI_DEFINE(uei);
+
+/* the cgroup under test, set before attaching */
+u64 cgid;
+
+/* run tasks whether or not they have runtime left */
+bool ignore_runtime;
+
+/* tasks held for lack of runtime */
+u64 nr_held;
+
+/* the cpu.max and cpu.max.runtime writes of @cgid */
+u64 nr_set_bw;
+u64 quota_us;
+u64 burst_us;
+u64 nr_set_runtime;
+/* cgroup_set_runtime() calls above the quota + burst last given */
+u64 nr_bad_order;
+
+struct kick_timer {
+ struct bpf_timer timer;
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, u32);
+ __type(value, struct kick_timer);
+} kick_timer SEC(".maps");
+
+static bool runnable(struct task_struct *p)
+{
+ return ignore_runtime || scx_bpf_task_cpu_max_runtime(p);
+}
+
+s32 BPF_STRUCT_OPS(cgroup_runtime_select_cpu, struct task_struct *p,
+ s32 prev_cpu, u64 wake_flags)
+{
+ return prev_cpu;
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_enqueue, struct task_struct *p,
+ u64 enq_flags)
+{
+ if (!runnable(p)) {
+ __sync_fetch_and_add(&nr_held, 1);
+ scx_bpf_dsq_insert(p, HELD_DSQ, SCX_SLICE_DFL, enq_flags);
+ return;
+ }
+ /* the last task of a CPU going idle must go to its local DSQ */
+ if (enq_flags & SCX_ENQ_LAST)
+ scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, enq_flags);
+ else
+ scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_dispatch, s32 cpu, struct task_struct *prev)
+{
+ struct task_struct *p = __COMPAT_scx_bpf_dsq_peek(HELD_DSQ);
+
+ if (p && runnable(p))
+ scx_bpf_dsq_move_to_local(HELD_DSQ, 0);
+}
+
+/*
+ * Stop a task that ran out, so that it goes through enqueue again.
+ * SCX_OPS_ENQ_LAST makes that so also when it is alone on its CPU.
+ */
+void BPF_STRUCT_OPS(cgroup_runtime_tick, struct task_struct *p)
+{
+ if (!runnable(p))
+ scx_bpf_task_set_slice(p, 0);
+}
+
+static int kick_timerfn(void *map, int *key, struct bpf_timer *timer)
+{
+ s32 cpu;
+
+ if (scx_bpf_dsq_nr_queued(HELD_DSQ))
+ bpf_for(cpu, 0, scx_bpf_nr_cpu_ids())
+ scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE);
+
+ bpf_timer_start(timer, KICK_NS, 0);
+ return 0;
+}
+
+s32 BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_init)
+{
+ struct bpf_timer *timer;
+ u32 key = 0;
+ s32 ret;
+
+ ret = scx_bpf_create_dsq(HELD_DSQ, -1);
+ if (ret)
+ return ret;
+
+ timer = bpf_map_lookup_elem(&kick_timer, &key);
+ if (!timer)
+ return -ESRCH;
+ bpf_timer_init(timer, &kick_timer, CLOCK_MONOTONIC);
+ bpf_timer_set_callback(timer, kick_timerfn);
+ return bpf_timer_start(timer, KICK_NS, 0);
+}
+
+static bool is_target(struct cgroup *cgrp)
+{
+ return cgid && cgrp->kn->id == cgid;
+}
+
+/* sleepable: cpu.max writes call it in process context */
+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_bandwidth,
+ struct cgroup *cgrp, u64 period_us, u64 quota,
+ u64 burst)
+{
+ if (!is_target(cgrp))
+ return;
+
+ __sync_fetch_and_add(&nr_set_bw, 1);
+ quota_us = quota;
+ burst_us = burst;
+}
+
+void BPF_STRUCT_OPS_SLEEPABLE(cgroup_runtime_cgroup_set_runtime,
+ struct cgroup *cgrp, u64 runtime_us)
+{
+ if (!is_target(cgrp))
+ return;
+
+ __sync_fetch_and_add(&nr_set_runtime, 1);
+ if (runtime_us > quota_us + burst_us)
+ __sync_fetch_and_add(&nr_bad_order, 1);
+}
+
+s32 BPF_STRUCT_OPS(cgroup_runtime_cgroup_init, struct cgroup *cgrp,
+ struct scx_cgroup_init_args *args)
+{
+ if (is_target(cgrp)) {
+ quota_us = args->bw_quota_us;
+ burst_us = args->bw_burst_us;
+ }
+ return 0;
+}
+
+void BPF_STRUCT_OPS(cgroup_runtime_exit, struct scx_exit_info *ei)
+{
+ UEI_RECORD(uei, ei);
+}
+
+SCX_OPS_DEFINE(partial_ops,
+ .select_cpu = (void *)cgroup_runtime_select_cpu,
+ .enqueue = (void *)cgroup_runtime_enqueue,
+ .dispatch = (void *)cgroup_runtime_dispatch,
+ .tick = (void *)cgroup_runtime_tick,
+ .init = (void *)cgroup_runtime_init,
+ .cgroup_init = (void *)cgroup_runtime_cgroup_init,
+ .cgroup_set_bandwidth = (void *)cgroup_runtime_cgroup_set_bandwidth,
+ .cgroup_set_runtime = (void *)cgroup_runtime_cgroup_set_runtime,
+ .exit = (void *)cgroup_runtime_exit,
+ .flags = SCX_OPS_SWITCH_PARTIAL |
+ SCX_OPS_ENQ_LAST |
+ SCX_OPS_CHARGE_CPU_MAX,
+ .name = "cgroup_runtime");
+
+SCX_OPS_DEFINE(full_ops,
+ .select_cpu = (void *)cgroup_runtime_select_cpu,
+ .enqueue = (void *)cgroup_runtime_enqueue,
+ .dispatch = (void *)cgroup_runtime_dispatch,
+ .tick = (void *)cgroup_runtime_tick,
+ .init = (void *)cgroup_runtime_init,
+ .cgroup_init = (void *)cgroup_runtime_cgroup_init,
+ .cgroup_set_bandwidth = (void *)cgroup_runtime_cgroup_set_bandwidth,
+ .cgroup_set_runtime = (void *)cgroup_runtime_cgroup_set_runtime,
+ .exit = (void *)cgroup_runtime_exit,
+ .flags = SCX_OPS_ENQ_LAST |
+ SCX_OPS_CHARGE_CPU_MAX,
+ .name = "cgroup_runtime_full");
diff --git a/tools/testing/selftests/sched_ext/cgroup_runtime.c b/tools/testing/selftests/sched_ext/cgroup_runtime.c
new file mode 100644
index 00000000000000..86d50a63a6e738
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/cgroup_runtime.c
@@ -0,0 +1,652 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Verify that a BPF scheduler with SCX_OPS_CHARGE_CPU_MAX shares a cgroup's
+ * cpu.max quota with the fair class: what the cgroup's tasks run in both
+ * classes, with and without SCX_OPS_SWITCH_PARTIAL and while tasks switch
+ * class, stays within the quota; nothing is gained or lost when the
+ * scheduler loads and unloads; and a scheduler that ignores
+ * scx_bpf_task_cpu_max_runtime() leaves the fair tasks at most a quota of
+ * debt and a slice per CPU, while one that stops tasks late pays the overrun
+ * back.
+ * Also verify that cpu.max and cpu.max.runtime writes reach the scheduler
+ * in the order the fair class applied them.
+ *
+ * Usage is cpu.stat's usage_usec. A window of n periods may hold n + 1
+ * refills and start or end with up to a quota, and each CPU may hold up to
+ * a slice (sched_cfs_bandwidth_slice_us), so the checks allow that.
+ */
+
+#define _GNU_SOURCE
+#include <bpf/bpf.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <linux/limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <scx/common.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "cgroup_runtime.bpf.skel.h"
+#include "cgroup_util.h"
+#include "scx_test.h"
+
+#ifndef SCHED_EXT
+#define SCHED_EXT 7
+#endif
+
+#define PERIOD_US 100000LL
+#define QUOTA_US 20000LL
+#define NR_PERIODS 10
+#define NR_BURNERS 2
+
+struct ctx {
+ struct cgroup_runtime *skel;
+ struct bpf_link *link;
+ char root[PATH_MAX];
+ char parent[PATH_MAX];
+ char cg[PATH_MAX];
+ bool parent_created;
+ bool cg_created;
+ pid_t burner[NR_BURNERS];
+ long long slice_us;
+ long long saved_slice_us;
+};
+
+static int join_path(char *dst, size_t dst_size, const char *parent, const char *name)
+{
+ int ret;
+
+ ret = snprintf(dst, dst_size, "%s/%s", parent, name);
+ if (ret < 0 || (size_t)ret >= dst_size)
+ return -ENAMETOOLONG;
+ return 0;
+}
+
+static u64 now_us(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000000ULL + ts.tv_nsec / 1000;
+}
+
+static u64 cgroup_id(const char *path)
+{
+ union {
+ u64 id;
+ unsigned char bytes[8];
+ } id = {};
+ struct file_handle *handle;
+ int mount_id, ret;
+
+ handle = calloc(1, sizeof(*handle) + sizeof(id));
+ if (!handle)
+ return 0;
+ handle->handle_bytes = sizeof(id);
+ ret = name_to_handle_at(AT_FDCWD, path, handle, &mount_id, 0);
+ if (!ret && handle->handle_bytes == sizeof(id))
+ memcpy(id.bytes, handle->f_handle, sizeof(id));
+ free(handle);
+
+ return ret ? 0 : id.id;
+}
+
+static long long read_runtime(struct ctx *ctx)
+{
+ return cg_read_long(ctx->cg, "cpu.max.runtime");
+}
+
+static long long read_usage(struct ctx *ctx)
+{
+ return cg_read_key_long(ctx->cg, "cpu.stat", "usage_usec");
+}
+
+static int write_str(const char *cgroup, const char *file, const char *fmt, ...)
+{
+ char buf[64];
+ va_list ap;
+
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ return cg_write(cgroup, file, buf);
+}
+
+static bool controller_enabled(const char *cgroup, const char *file, const char *controller)
+{
+ char buf[4096], *saveptr, *token;
+
+ if (cg_read(cgroup, file, buf, sizeof(buf)))
+ return false;
+ for (token = strtok_r(buf, "\n ", &saveptr); token;
+ token = strtok_r(NULL, "\n ", &saveptr))
+ if (!strcmp(token, controller))
+ return true;
+ return false;
+}
+
+static int set_policy(pid_t pid, int policy)
+{
+ struct sched_param param = {};
+
+ return sched_setscheduler(pid, policy, ¶m);
+}
+
+static void stop_burners(struct ctx *ctx)
+{
+ int i;
+
+ for (i = 0; i < NR_BURNERS; i++) {
+ if (ctx->burner[i] <= 0)
+ continue;
+ kill(ctx->burner[i], SIGKILL);
+ waitpid(ctx->burner[i], NULL, 0);
+ ctx->burner[i] = 0;
+ }
+}
+
+/* a task in @ctx->cg that spins on CPU @i + 1 under @policy */
+static int start_burner(struct ctx *ctx, int i, int policy)
+{
+ cpu_set_t set;
+ pid_t pid;
+
+ pid = fork();
+ if (pid < 0)
+ return -errno;
+ if (!pid)
+ for (;;)
+ ;
+
+ ctx->burner[i] = pid;
+ CPU_ZERO(&set);
+ CPU_SET((i + 1) % libbpf_num_possible_cpus(), &set);
+ if (sched_setaffinity(pid, sizeof(set), &set) ||
+ cg_enter(ctx->cg, pid) || set_policy(pid, policy))
+ return -1;
+ return 0;
+}
+
+static void cleanup(void *arg)
+{
+ struct ctx *ctx = arg;
+
+ if (!ctx)
+ return;
+ stop_burners(ctx);
+ bpf_link__destroy(ctx->link);
+ cgroup_runtime__destroy(ctx->skel);
+ if (ctx->saved_slice_us)
+ write_str("/proc/sys/kernel", "sched_cfs_bandwidth_slice_us", "%lld",
+ ctx->saved_slice_us);
+ if (ctx->cg_created)
+ cg_destroy(ctx->cg);
+ if (ctx->parent_created)
+ cg_destroy(ctx->parent);
+ free(ctx);
+}
+
+/*
+ * Open the skeleton and make parent/cg under the cgroup2 root, with a quota
+ * of @quota us per @period us, a burst of @burst us and a runtime of
+ * @runtime us on cg.
+ */
+static enum scx_test_status setup_ctx(void **ctxp, long long quota,
+ long long period, long long burst,
+ long long runtime)
+{
+ struct ctx *ctx;
+ char name[64];
+
+ ctx = calloc(1, sizeof(*ctx));
+ if (!ctx)
+ return SCX_TEST_FAIL;
+ *ctxp = ctx;
+
+ /* SCX_ENUM_INIT() exits if vmlinux BTF can't be loaded: before cgroups */
+ ctx->skel = cgroup_runtime__open();
+ if (!ctx->skel) {
+ SCX_ERR("Failed to open skel");
+ return SCX_TEST_FAIL;
+ }
+ SCX_ENUM_INIT(ctx->skel);
+
+ ctx->slice_us = 5000;
+ if (!access("/proc/sys/kernel/sched_cfs_bandwidth_slice_us", R_OK))
+ ctx->slice_us = cg_read_long("/proc/sys/kernel",
+ "sched_cfs_bandwidth_slice_us");
+
+ if (cg_find_unified_root(ctx->root, sizeof(ctx->root), NULL))
+ return SCX_TEST_SKIP;
+ if (!controller_enabled(ctx->root, "cgroup.subtree_control", "cpu") &&
+ cg_write(ctx->root, "cgroup.subtree_control", "+cpu"))
+ return SCX_TEST_SKIP;
+
+ snprintf(name, sizeof(name), "scx_cgroup_runtime_%d", getpid());
+ if (join_path(ctx->parent, sizeof(ctx->parent), ctx->root, name) ||
+ join_path(ctx->cg, sizeof(ctx->cg), ctx->parent, "cg")) {
+ SCX_ERR("Cgroup path is too long");
+ return SCX_TEST_FAIL;
+ }
+
+ if (cg_create(ctx->parent)) {
+ SCX_ERR("Failed to create %s", ctx->parent);
+ return SCX_TEST_FAIL;
+ }
+ ctx->parent_created = true;
+ if (cg_write(ctx->parent, "cgroup.subtree_control", "+cpu")) {
+ SCX_ERR("Failed to enable cpu in %s", ctx->parent);
+ return SCX_TEST_FAIL;
+ }
+ if (cg_create(ctx->cg)) {
+ SCX_ERR("Failed to create %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+ ctx->cg_created = true;
+
+ if (access(cg_control(ctx->cg, "cpu.max.runtime"), F_OK))
+ return SCX_TEST_SKIP;
+
+ if (write_str(ctx->cg, "cpu.max", "%lld %lld", quota, period) ||
+ write_str(ctx->cg, "cpu.max.burst", "%lld", burst) ||
+ write_str(ctx->cg, "cpu.max.runtime", "%lld", runtime)) {
+ SCX_ERR("Failed to configure %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+
+ ctx->skel->bss->cgid = cgroup_id(ctx->cg);
+ if (!ctx->skel->bss->cgid) {
+ SCX_ERR("Failed to read the cgroup ID of %s", ctx->cg);
+ return SCX_TEST_FAIL;
+ }
+ if (libbpf_num_possible_cpus() < NR_BURNERS + 1)
+ return SCX_TEST_SKIP;
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status setup_rate(void **ctxp)
+{
+ return setup_ctx(ctxp, QUOTA_US, PERIOD_US, 0, QUOTA_US);
+}
+
+static enum scx_test_status attach_ops(struct ctx *ctx, bool partial)
+{
+ ctx->link = bpf_map__attach_struct_ops(partial ? ctx->skel->maps.partial_ops :
+ ctx->skel->maps.full_ops);
+ SCX_FAIL_IF(!ctx->link, "Failed to attach scheduler");
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status load_ops(struct ctx *ctx, bool partial)
+{
+ bpf_map__set_autoattach(ctx->skel->maps.partial_ops, false);
+ bpf_map__set_autoattach(ctx->skel->maps.full_ops, false);
+ SCX_FAIL_IF(cgroup_runtime__load(ctx->skel), "Failed to load skel");
+ return attach_ops(ctx, partial);
+}
+
+static void detach(struct ctx *ctx)
+{
+ bpf_link__destroy(ctx->link);
+ ctx->link = NULL;
+}
+
+/*
+ * Run two burners in cg under @policy[], the first switching class every
+ * 7 ms if @toggle, and check that cg runs its quota per period, no more and
+ * not much less.
+ */
+static enum scx_test_status run_rate(struct ctx *ctx, bool partial,
+ const int *policy, bool toggle)
+{
+ long long tol = NR_BURNERS * ctx->slice_us + QUOTA_US;
+ long long used, u0;
+ bool ext = false;
+ u64 end;
+ int i;
+
+ if (load_ops(ctx, partial))
+ return SCX_TEST_FAIL;
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, policy[i]), 0);
+
+ usleep(3 * PERIOD_US);
+ u0 = read_usage(ctx);
+ end = now_us() + NR_PERIODS * PERIOD_US;
+ while (now_us() < end) {
+ if (toggle) {
+ ext = !ext;
+ SCX_EQ(set_policy(ctx->burner[0], ext ? SCHED_EXT : SCHED_OTHER), 0);
+ }
+ usleep(7000);
+ }
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us in %d periods of quota %lld us, %lu held\n",
+ used, NR_PERIODS, QUOTA_US, (unsigned long)ctx->skel->bss->nr_held);
+ SCX_GE(used, QUOTA_US * NR_PERIODS - tol);
+ SCX_LE(used, QUOTA_US * NR_PERIODS + tol);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run_full(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_OTHER };
+
+ return run_rate(arg, false, policy, false);
+}
+
+static enum scx_test_status run_partial_ext(void *arg)
+{
+ static const int policy[] = { SCHED_EXT, SCHED_EXT };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_partial_fair(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_OTHER };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_partial_mixed(void *arg)
+{
+ static const int policy[] = { SCHED_EXT, SCHED_OTHER };
+
+ return run_rate(arg, true, policy, false);
+}
+
+static enum scx_test_status run_switch(void *arg)
+{
+ static const int policy[] = { SCHED_OTHER, SCHED_EXT };
+
+ return run_rate(arg, true, policy, true);
+}
+
+/*
+ * With a quota of 1 ms per second and a runtime of 3 s, what cg runs while
+ * the scheduler loads, runs and unloads is what its runtime loses, up to a
+ * slice per CPU and the few refills.
+ */
+#define LU_QUOTA_US 1000LL
+#define LU_PERIOD_US 1000000LL
+
+static enum scx_test_status setup_load_unload(void **ctxp)
+{
+ return setup_ctx(ctxp, LU_QUOTA_US, LU_PERIOD_US, 4000000, 3000000);
+}
+
+static enum scx_test_status run_load_unload(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long r0, u0, drawn, used, refills, tol;
+ u64 t0, t1;
+ int i;
+
+ bpf_map__set_autoattach(ctx->skel->maps.partial_ops, false);
+ bpf_map__set_autoattach(ctx->skel->maps.full_ops, false);
+ SCX_FAIL_IF(cgroup_runtime__load(ctx->skel), "Failed to load skel");
+
+ t0 = now_us();
+ r0 = read_runtime(ctx);
+ u0 = read_usage(ctx);
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, SCHED_OTHER), 0);
+ usleep(100000);
+ if (attach_ops(ctx, false))
+ return SCX_TEST_FAIL;
+ usleep(200000);
+ detach(ctx);
+ usleep(100000);
+ stop_burners(ctx);
+ drawn = r0 - read_runtime(ctx);
+ used = read_usage(ctx) - u0;
+ t1 = now_us();
+
+ refills = LU_QUOTA_US * ((t1 - t0) / LU_PERIOD_US + 2);
+ tol = NR_BURNERS * ctx->slice_us;
+ printf("ran %lld us, runtime down %lld us\n", used, drawn);
+ SCX_GE(used, 300000);
+ SCX_GE(used, drawn - tol);
+ SCX_LE(used, drawn + refills + tol);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * A scheduler that ignores scx_bpf_task_cpu_max_runtime() runs a task far
+ * past the quota. Once the task is back on the fair class, it runs its quota
+ * again, less at most a quota and a slice of debt.
+ */
+static enum scx_test_status run_clamp(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long u0, ignored, used;
+
+ ctx->skel->bss->ignore_runtime = true;
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ SCX_EQ(start_burner(ctx, 0, SCHED_EXT), 0);
+
+ u0 = read_usage(ctx);
+ usleep(5 * PERIOD_US);
+ ignored = read_usage(ctx) - u0;
+
+ SCX_EQ(set_policy(ctx->burner[0], SCHED_OTHER), 0);
+ u0 = read_usage(ctx);
+ usleep(5 * PERIOD_US);
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us ignoring the quota, then %lld us on the fair class\n",
+ ignored, used);
+ SCX_GE(ignored, 4 * PERIOD_US);
+ SCX_GE(used, 4 * QUOTA_US - 2 * ctx->slice_us);
+ SCX_LE(used, 6 * QUOTA_US + ctx->slice_us);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * The scheduler stops a task only at a tick, so each period it overruns a
+ * quota of 2 ms by up to a tick. With a slice of 1 ms, the next tick's
+ * charge takes the CPU past the -slice floor. The debt must still be paid
+ * from the next periods, so over 100 periods cg runs its quota, with the
+ * second burner moving between CPUs 2 and 3 every 7 ms.
+ */
+#define DEBT_QUOTA_US 2000LL
+#define DEBT_PERIOD_US 10000LL
+#define DEBT_PERIODS 100
+
+static enum scx_test_status setup_debt(void **ctxp)
+{
+ enum scx_test_status ret;
+ struct ctx *ctx;
+
+ ret = setup_ctx(ctxp, DEBT_QUOTA_US, DEBT_PERIOD_US, 0, DEBT_QUOTA_US);
+ if (ret != SCX_TEST_PASS)
+ return ret;
+ ctx = *ctxp;
+ if (write_str("/proc/sys/kernel", "sched_cfs_bandwidth_slice_us", "1000"))
+ return SCX_TEST_SKIP;
+ ctx->saved_slice_us = ctx->slice_us;
+ ctx->slice_us = 1000;
+ return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run_debt(void *arg)
+{
+ struct ctx *ctx = arg;
+ long long tol = (NR_BURNERS + 1) * ctx->slice_us + DEBT_QUOTA_US;
+ long long want = DEBT_QUOTA_US * DEBT_PERIODS;
+ long long used, u0;
+ bool moved = false;
+ cpu_set_t set;
+ u64 end;
+ int i;
+
+ if (libbpf_num_possible_cpus() < 4)
+ return SCX_TEST_SKIP;
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ for (i = 0; i < NR_BURNERS; i++)
+ SCX_EQ(start_burner(ctx, i, SCHED_EXT), 0);
+
+ usleep(3 * DEBT_PERIOD_US);
+ u0 = read_usage(ctx);
+ end = now_us() + DEBT_PERIODS * DEBT_PERIOD_US;
+ while (now_us() < end) {
+ moved = !moved;
+ CPU_ZERO(&set);
+ CPU_SET(moved ? 3 : 2, &set);
+ SCX_EQ(sched_setaffinity(ctx->burner[1], sizeof(set), &set), 0);
+ usleep(7000);
+ }
+ used = read_usage(ctx) - u0;
+ stop_burners(ctx);
+
+ printf("ran %lld us in %d periods of quota %lld us\n", used,
+ DEBT_PERIODS, DEBT_QUOTA_US);
+ SCX_GE(used, want - tol);
+ SCX_LE(used, want + tol);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+/*
+ * One thread alternates cpu.max between quotas of 100ms and 10ms, without a
+ * burst, while another writes a runtime of 90ms, which only the first
+ * allows. The scheduler must never get a runtime above the quota it was last
+ * given, and must end with the quota cpu.max has.
+ */
+#define INTERLEAVE_US 2000000ULL
+
+struct interleave {
+ struct ctx *ctx;
+ long nr_ok;
+ long nr_einval;
+ long nr_err;
+};
+
+static void *interleave_quota(void *arg)
+{
+ struct interleave *il = arg;
+ u64 end = now_us() + INTERLEAVE_US;
+ bool high = false;
+
+ while (now_us() < end) {
+ if (write_str(il->ctx->cg, "cpu.max", "%lld %lld",
+ high ? 100000LL : 10000LL, 1000000LL))
+ il->nr_err++;
+ else
+ il->nr_ok++;
+ high = !high;
+ }
+ return NULL;
+}
+
+static void *interleave_runtime(void *arg)
+{
+ struct interleave *il = arg;
+ u64 end = now_us() + INTERLEAVE_US;
+
+ while (now_us() < end) {
+ int fd = cg_open(il->ctx->cg, "cpu.max.runtime", O_WRONLY);
+
+ if (fd < 0) {
+ il->nr_err++;
+ continue;
+ }
+ if (write(fd, "90000", 5) == 5)
+ il->nr_ok++;
+ else if (errno == EINVAL)
+ il->nr_einval++;
+ else
+ il->nr_err++;
+ close(fd);
+ }
+ return NULL;
+}
+
+static enum scx_test_status setup_interleave(void **ctxp)
+{
+ return setup_ctx(ctxp, 100000, 1000000, 0, 100000);
+}
+
+static enum scx_test_status run_interleave(void *arg)
+{
+ struct ctx *ctx = arg;
+ struct interleave quota = { .ctx = ctx }, runtime = { .ctx = ctx };
+ pthread_t tq, tr;
+ char buf[64];
+
+ if (load_ops(ctx, true))
+ return SCX_TEST_FAIL;
+ SCX_EQ(ctx->skel->bss->quota_us, 100000);
+
+ SCX_EQ(pthread_create(&tq, NULL, interleave_quota, "a), 0);
+ SCX_EQ(pthread_create(&tr, NULL, interleave_runtime, &runtime), 0);
+ pthread_join(tq, NULL);
+ pthread_join(tr, NULL);
+
+ SCX_EQ(quota.nr_err, 0);
+ SCX_EQ(runtime.nr_err, 0);
+ SCX_GT(runtime.nr_ok, 0);
+ SCX_EQ(ctx->skel->bss->nr_bad_order, 0);
+ SCX_EQ(ctx->skel->bss->nr_set_bw, quota.nr_ok);
+ SCX_EQ(ctx->skel->bss->nr_set_runtime, runtime.nr_ok);
+
+ SCX_EQ(cg_read(ctx->cg, "cpu.max", buf, sizeof(buf)), 0);
+ SCX_EQ(ctx->skel->bss->quota_us, atoll(buf));
+ SCX_EQ(ctx->skel->bss->burst_us, 0);
+
+ printf("cpu.max writes %ld, cpu.max.runtime writes %ld (%ld EINVAL)\n",
+ quota.nr_ok, runtime.nr_ok, runtime.nr_einval);
+ SCX_ASSERT_ALIVE(ctx->skel, uei);
+ return SCX_TEST_PASS;
+}
+
+#define RUNTIME_TEST(__name, __setup, __desc) \
+ struct scx_test cgroup_runtime_##__name = { \
+ .name = "cgroup_runtime_" #__name, \
+ .description = __desc, \
+ .setup = __setup, \
+ .run = run_##__name, \
+ .cleanup = cleanup, \
+ }
+
+RUNTIME_TEST(full, setup_rate, "Without partial switch, the BPF scheduler's tasks run their quota");
+RUNTIME_TEST(partial_ext, setup_rate, "SCHED_EXT tasks of a cgroup run its quota");
+RUNTIME_TEST(partial_fair, setup_rate, "Fair tasks of a cgroup run its quota");
+RUNTIME_TEST(partial_mixed, setup_rate, "Fair and SCHED_EXT tasks of a cgroup share its quota");
+RUNTIME_TEST(switch, setup_rate, "A task switching class every 7 ms stays within the quota");
+RUNTIME_TEST(load_unload, setup_load_unload, "Load and unload neither gain nor lose runtime");
+RUNTIME_TEST(clamp, setup_rate, "A scheduler ignoring the quota leaves a bounded debt");
+RUNTIME_TEST(debt, setup_debt, "Debt past a quota is paid in the next periods");
+RUNTIME_TEST(interleave, setup_interleave, "cpu.max writes reach the scheduler in order");
+
+/* REGISTER_SCX_TEST() can be used once per file */
+__attribute__((constructor))
+static void register_cgroup_runtime_tests(void)
+{
+ scx_test_register(&cgroup_runtime_full);
+ scx_test_register(&cgroup_runtime_partial_ext);
+ scx_test_register(&cgroup_runtime_partial_fair);
+ scx_test_register(&cgroup_runtime_partial_mixed);
+ scx_test_register(&cgroup_runtime_switch);
+ scx_test_register(&cgroup_runtime_load_unload);
+ scx_test_register(&cgroup_runtime_clamp);
+ scx_test_register(&cgroup_runtime_debt);
+ scx_test_register(&cgroup_runtime_interleave);
+}
diff --git a/tools/testing/selftests/sched_ext/config b/tools/testing/selftests/sched_ext/config
index 8173f9170ffe89..495b140403a18e 100644
--- a/tools/testing/selftests/sched_ext/config
+++ b/tools/testing/selftests/sched_ext/config
@@ -9,3 +9,4 @@ CONFIG_DEBUG_INFO=y
CONFIG_DEBUG_INFO_BTF=y
CONFIG_EXPERT=y
CONFIG_SCHED_PROXY_EXEC=y
+CONFIG_CFS_BANDWIDTH=y
|
| 21/3 | 2026/11/13 14:21 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31219 output: 20 thoughts: 1350 Thoughts: **KMSAN Evaluation: Patch Series Analysis**
Alright, let's break this down. The task is to determine if this patch series warrants a dedicated KMSAN fuzzing session. The key is to assess whether it introduces or modifies code that could lead to uninitialized memory reads or information leaks, especially in interactions with user space. Standard KASAN builds are in place, so we only need to worry about KMSAN if this patch series opens new doors for *uninitialized* memory access that KASAN might miss.
Looking at the patch itself, it seems like a fairly significant update to the cgroup bandwidth control (cgroup-v2, and related scheduling changes). We have file additions, deletions, and a lot of changes related to bandwidth calculation and accounting. My initial impression is that the changes are primarily focused on performance improvements, adding new features, and enabling BPF to manage runtime.
Let's dive into the specifics:
* **Documentation Updates:** Documentation changes alone are unlikely to trigger KMSAN issues, so we can likely gloss over these.
* **`kernel/sched/core.c`:** This is where things start to get interesting. We have:
* Calls to `cfs_bandwidth_refill_idle_periods()` which touches `cfs_bandwidth`. Let's look at how this is initialized.
* Mutex `tg_bandwidth_mutex` which is a good thing for data integrity, but doesn't inherently point to a KMSAN issue.
* `cpu_runtime_read_u64` and `cpu_runtime_write_u64`: This involves reading/writing to `cpu.max.runtime`, and that is a key area to scrutinize. Since these are standard cgroup seq\_file/cftype reading, we need to check if the `runtime` value within the `cfs_bandwidth` structure is initialized before being read.
* `div_u64(cfs_bandwidth_get_runtime(&tg->cfs_bandwidth), NSEC_PER_USEC)`: This reads from the `cfs_bandwidth`. Where and how is `cfs_bandwidth` created/initialized?
* `cfs_bandwidth` is defined and used by other functions, so it is necessary to consider the init path.
* **`kernel/sched/ext/ext.c` and `ext.h`:** This seems to be related to extended scheduling features with BPF. Specifically, the `scx_task_charges_cpu_max` and other functions are dealing with charging and returning runtime. We need to check the initialization of related structs, like in `update_curr_scx`. BPF is a high-risk area since it can access kernel data structures from user-space via kfuncs, and we are adding `scx_bpf_task_cpu_max_runtime` which calls `cfs_bandwidth_task_runtime()`. These new BPF kfuncs directly reference bandwidth/runtime, making KMSAN relevant.
* **`kernel/sched/fair.c` and `sched.h`:** This is where the core logic for cfs\_bandwidth calculations resides. We see a significant amount of changes to `cfs_bandwidth` related functions:
* `__refill_cfs_bandwidth_runtime`: Handles debt which is related to `debt` in `cfs_bandwidth`.
* `cfs_bandwidth_refilled`: computes runtime after refill
* `cfs_bandwidth_idle_periods`: computes delta
* `cfs_bandwidth_refill_idle_periods`: updates `cfs_b->runtime` and `cfs_b->runtime_snap`
* `cfs_bandwidth_get_runtime`: reads runtime under lock
* `cfs_bandwidth_set_runtime`: sets runtime under lock
* `start_cfs_bandwidth`: calls `cfs_bandwidth_refill_idle_periods(cfs_b);`
* `cfs_bandwidth_charge_task`: charges delta\_exec to cfs\_rq/cfs\_b
* `cfs_bandwidth_return_task`: returns runtime on dequeue
* `cfs_bandwidth_task_runtime`: reads task runtime across hierarchy
* `struct cfs_bandwidth`: added `u64 debt;` (This is particularly interesting). We need to see how and where `debt` is initialized.
* **Tools/selftests:** These are good, but unless they introduce a new way to interact with potentially uninitialized memory, they are unlikely to be a KMSAN concern.
**Conclusion:**
Based on this preliminary analysis, I
|
| 22/3 | 2026/11/13 14:22 | tool | grepper |
0mArgs:{
"Expression": "init_cfs_bandwidth"
}Results: {
"Output": "kernel/sched/core.c=8923=void __init sched_init(void)\n--\nkernel/sched/core.c-8943-\troot_task_group.shares = ROOT_TASK_GROUP_LOAD;\nkernel/sched/core.c:8944:\tinit_cfs_bandwidth(\u0026root_task_group.cfs_bandwidth, NULL);\nkernel/sched/core.c-8945-#endif /* CONFIG_FAIR_GROUP_SCHED */\n--\nkernel/sched/fair.c=7735=static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)\n--\nkernel/sched/fair.c-7791-\nkernel/sched/fair.c:7792:void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)\nkernel/sched/fair.c-7793-{\n--\nkernel/sched/fair.c=7967=static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)\n--\nkernel/sched/fair.c-7970-\nkernel/sched/fair.c:7971:\t/* init_cfs_bandwidth() was not called */\nkernel/sched/fair.c-7972-\tif (!cfs_b-\u003ethrottled_cfs_rq.next)\n--\nkernel/sched/fair.c=8254=static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)\n--\nkernel/sched/fair.c-8259-#ifdef CONFIG_FAIR_GROUP_SCHED\nkernel/sched/fair.c:8260:void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}\nkernel/sched/fair.c-8261-static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}\n--\nkernel/sched/fair.c=15946=int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)\n--\nkernel/sched/fair.c-15959-\nkernel/sched/fair.c:15960:\tinit_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));\nkernel/sched/fair.c-15961-\n--\nkernel/sched/sched.h=575=extern void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,\n--\nkernel/sched/sched.h-577-\t\t\tstruct sched_entity *parent);\nkernel/sched/sched.h:578:extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent);\nkernel/sched/sched.h-579-\n"
} |
| 23/3 | 2026/11/13 14:23 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34343 output: 36 thoughts: 32 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Diving into CFS Bandwidth Initialization and Task Group Allocation** Alright, my internal gears are already turning. I need to refresh my memory on the critical interplay between CFS bandwidth management and task group assignment within the kernel scheduler. Specifically, I'm going to head straight to `kernel/sched/fair.c`. That's where the magic happens, and I want to pinpoint exactly how `init_cfs_bandwidth` is defined and used. I'm keen to understand the initial setup of bandwidth controllers. I also need to see how a `task_group` is allocated because I'm betting that plays a key role in the bandwidth management scheme. Is the allocation static or dynamic? What's the relationship between the `task_group` structure and the bandwidth attributes, particularly for root and non-root groups? I need to understand this to have a full grasp of the bandwidth implementation and identify any performance implications. I am trying to figure out if there are any subtle inefficiencies or opportunities for optimization within the framework. |
| 24/3 | 2026/11/13 14:23 | tool | read-file |
0mArgs:{
"File": "kernel/sched/fair.c",
"FirstLine": 7790,
"LineCount": 30
}Results: {
"Contents": "7790:\t}\n7791:\t\n7792:\tvoid init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)\n7793:\t{\n7794:\t\traw_spin_lock_init(\u0026cfs_b-\u003elock);\n7795:\t\tcfs_b-\u003eruntime = 0;\n7796:\t\tcfs_b-\u003equota = RUNTIME_INF;\n7797:\t\tcfs_b-\u003eperiod = us_to_ktime(default_bw_period_us());\n7798:\t\tcfs_b-\u003eburst = 0;\n7799:\t\tcfs_b-\u003ehierarchical_quota = parent ? parent-\u003ehierarchical_quota : RUNTIME_INF;\n7800:\t\n7801:\t\tINIT_LIST_HEAD(\u0026cfs_b-\u003ethrottled_cfs_rq);\n7802:\t\thrtimer_setup(\u0026cfs_b-\u003eperiod_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,\n7803:\t\t\t HRTIMER_MODE_ABS_PINNED);\n7804:\t\n7805:\t\t/* Add a random offset so that timers interleave */\n7806:\t\thrtimer_set_expires(\u0026cfs_b-\u003eperiod_timer,\n7807:\t\t\t\t get_random_u32_below(cfs_b-\u003eperiod));\n7808:\t\thrtimer_setup(\u0026cfs_b-\u003eslack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,\n7809:\t\t\t HRTIMER_MODE_REL);\n7810:\t\tcfs_b-\u003eslack_started = false;\n7811:\t}\n7812:\t\n7813:\tstatic void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)\n7814:\t{\n7815:\t\tcfs_rq-\u003eruntime_enabled = 0;\n7816:\t\tINIT_LIST_HEAD(\u0026cfs_rq-\u003ethrottled_list);\n7817:\t\tINIT_LIST_HEAD(\u0026cfs_rq-\u003ethrottled_csd_list);\n7818:\t\tINIT_LIST_HEAD(\u0026cfs_rq-\u003ethrottled_limbo_list);\n7819:\t}\n"
} |
| 25/3 | 2026/11/13 14:23 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35237 output: 42 thoughts: 23 Thoughts: Okay, here's my understanding, assuming I'm an expert in kernel scheduling: **Diving into `struct task_group` Allocation in `kernel/sched/core.c`** Alright, let's get down to brass tacks. I need to understand how `struct task_group` instances are allocated within the scheduler code, specifically in `kernel/sched/core.c`. This is fundamental; it tells me how the system manages the hierarchical organization of tasks and the resources associated with those groups. I want to see if they're using a standard `kmalloc`-style approach, or something more intricate. Are they pre-allocating a pool? Are they using a custom allocator to optimize for size or alignment? What kind of initialization is happening alongside the allocation? Are there any subtle implications for NUMA awareness or memory management in general? I need to check the exact function calls used and the surrounding context to truly grasp the memory model. Let's dig in and see the whole picture. |
| 26/3 | 2026/11/13 14:24 | tool | grepper |
0mArgs:{
"Expression": "kzalloc.*task_group|kmem_cache_zalloc.*task_group",
"PathPrefixes": [
"kernel/sched"
]
}Results: {
"Output": "no matches"
} |
| 27/3 | 2026/11/13 14:24 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35526 output: 29 thoughts: 23 Thoughts: Here's my thought process, as requested: **Digging into Task Group Creation** Okay, so I need to understand how these task groups are created. The first thing that pops into my head is to dive into the kernel source and start with the core functions. My instincts are to use `grep`. I want to zero in on the creation process. Specifically, I'm looking for where new `task_group` structures are allocated. That's the heart of the matter. So, I'll `grep` for either `sched_create_group`, because that sounds like a likely creator function, or I'll look for where the `struct task_group` itself is being allocated, perhaps with something like `kmalloc` or `kmem_cache_alloc`. The goal is to identify the points where the kernel actually sets up these resource management containers. I expect this to immediately turn up the key code paths I need to examine. |
| 28/3 | 2026/11/13 14:25 | tool | grepper |
0mArgs:{
"Expression": "sched_create_group",
"PathPrefixes": [
"kernel/sched"
]
}Results: {
"Output": "kernel/sched/autogroup.c=87=static inline struct autogroup *autogroup_create(void)\n--\nkernel/sched/autogroup.c-94-\nkernel/sched/autogroup.c:95:\ttg = sched_create_group(\u0026root_task_group);\nkernel/sched/autogroup.c-96-\tif (IS_ERR(tg))\n--\nkernel/sched/autogroup.c-124-\t\tprintk(KERN_WARNING \"autogroup_create: %s failure.\\n\",\nkernel/sched/autogroup.c:125:\t\t\tag ? \"sched_create_group()\" : \"kzalloc()\");\nkernel/sched/autogroup.c-126-\t}\n--\nkernel/sched/core.c=9368=static void sched_unregister_group(struct task_group *tg)\n--\nkernel/sched/core.c-9379-/* allocate runqueue etc for a new task group */\nkernel/sched/core.c:9380:struct task_group *sched_create_group(struct task_group *parent)\nkernel/sched/core.c-9381-{\n--\nkernel/sched/core.c=9515=cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)\n--\nkernel/sched/core.c-9524-\nkernel/sched/core.c:9525:\ttg = sched_create_group(parent);\nkernel/sched/core.c-9526-\tif (IS_ERR(tg))\n--\nkernel/sched/sched.h=595=extern int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk);\nkernel/sched/sched.h-596-\nkernel/sched/sched.h:597:extern struct task_group *sched_create_group(struct task_group *parent);\nkernel/sched/sched.h-598-extern void sched_online_group(struct task_group *tg,\n"
} |
| 29/3 | 2026/11/13 14:25 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36277 output: 36 thoughts: 11 Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person: **Diving into `sched_create_group`** Alright, let's pull up the source for `sched_create_group`. I'm already anticipating some of the key areas of interest here. Given its name, I'm expecting this function to be the core of group scheduling within the kernel, likely responsible for setting up the fundamental data structures needed to manage a collection of processes as a single unit from a scheduling perspective. I'm keen to see the implications of this group creation. Does this create new scheduling entities? Does this link to the cgroup hierarchy directly? And most importantly, how do those scheduling parameters fit in? I'll be looking to see if it handles things like resource allocation, whether it deals with constraints or any kind of accounting. I'm also curious about the locking it employs, specifically around any updates to the scheduler data structures. What's the concurrency story here? I'm also expecting some kind of sanity checks and error handling, especially if there is a problem creating the associated structures. The typical failure scenario would be insufficient memory, I'll be looking for memory allocation code. I'm also thinking this could be a point of integration with other subsystems, like memory management or the task group hierarchy. What calls does it make into existing schedulers (CFS, RT, etc.) to integrate with their specific implementations? The main point here is: Does it affect resource sharing? What's the main function of the new group from a scheduling perspective? So, the real goal is to see exactly how this function establishes a scheduling context for a group, and how that context is integrated with the larger scheduler framework. Okay, let's see what's in there... |
| 30/3 | 2026/11/13 14:26 | tool | read-file |
0mArgs:{
"File": "kernel/sched/core.c",
"FirstLine": 9380,
"LineCount": 35
}Results: {
"Contents": "9380:\tstruct task_group *sched_create_group(struct task_group *parent)\n9381:\t{\n9382:\t\tstruct task_group *tg;\n9383:\t\n9384:\t\ttg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);\n9385:\t\tif (!tg)\n9386:\t\t\treturn ERR_PTR(-ENOMEM);\n9387:\t\n9388:\t\tif (!alloc_fair_sched_group(tg, parent))\n9389:\t\t\tgoto err;\n9390:\t\n9391:\t\tif (!alloc_rt_sched_group(tg, parent))\n9392:\t\t\tgoto err;\n9393:\t\n9394:\t\tscx_tg_init(tg);\n9395:\t\talloc_uclamp_sched_group(tg, parent);\n9396:\t\n9397:\t\treturn tg;\n9398:\t\n9399:\terr:\n9400:\t\tsched_free_group(tg);\n9401:\t\treturn ERR_PTR(-ENOMEM);\n9402:\t}\n9403:\t\n9404:\tvoid sched_online_group(struct task_group *tg, struct task_group *parent)\n9405:\t{\n9406:\t\tunsigned long flags;\n9407:\t\n9408:\t\tspin_lock_irqsave(\u0026task_group_lock, flags);\n9409:\t\tlist_add_tail_rcu(\u0026tg-\u003elist, \u0026task_groups);\n9410:\t\n9411:\t\t/* Root should already exist: */\n9412:\t\tWARN_ON(!parent);\n9413:\t\n9414:\t\ttg-\u003eparent = parent;\n"
} |
| 31/3 | 2026/11/13 14:26 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37185 output: 481 thoughts: 3395 Thoughts: **KMSAN Assessment: CFS Bandwidth Burst and Sched_ext Integration** Alright, let's break down this patch series and determine the `NeedsKMSAN` status. I've examined the code meticulously, focusing on potential uninitialized memory risks. First off, `tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO)` immediately initializes the allocated memory. The `root_task_group` is also zero-initialized. Therefore, the `cfs_b->debt` starts at zero, as it should. The core changes are centered around CFS bandwidth burst limits, the addition of a `cpu.max.runtime` cgroup v2 file, and integration with `sched_ext`. The cgroup file handler for `cpu.max.runtime` involves a standard `read_u64` handler. This handler retrieves the runtime and formats it as text. There is no raw structure copying to user space, so no uninitialized buffers are present. The write handler takes parsed u64 and sets runtime; similarly, no direct memory copy is involved. `scx_bpf_task_cpu_max_runtime` is a BPF kfunc returning a u64, and `scx_group_set_runtime` is BPF ops invocation with `(tg_cgrp(tg), runtime_us)`, also operating on scalar values and existing kernel objects. Inspecting `cfs_bandwidth_task_runtime` reveals proper initialization across all variables, including `runtime`, `cpu`, and `held`, with no uninitialized memory accessed. `cfs_bandwidth_charge_task`, `cfs_bandwidth_return_task`, `cfs_bandwidth_refilled`, `cfs_bandwidth_idle_periods`, and `cfs_bandwidth_refill_idle_periods` are also meticulously examined, confirming that all variables used are initialized. `cfs_bandwidth_set_runtime`, while containing conditional logic, ensures that the `throttled` variable is always initialized before use. The new `u64 debt` member in `struct cfs_bandwidth` is safe. The `cfs_bandwidth` is an internal struct, and `task_group` is allocated with `GFP_KERNEL | __GFP_ZERO`, ensuring the new member is initialized. Regarding `sched_ext`, the new `cgroup_set_runtime` callback in `struct sched_ext_ops` and `sched_ext_ops_cid` and the new kfunc `scx_bpf_task_cpu_max_runtime` all operate on scalar u64 values and pointers to existing kernel objects, not copying kernel data to userspace. Locking (mutexes and spinlocks, including `tg_bandwidth_mutex`, `cfs_b->lock`, and rq locks) is present, but any potential issues are likely to be detected by LOCKDEP. Memory safety concerns (out-of-bounds access, use-after-free, etc.) would be caught by KASAN. There is no uninitialized memory copied to user space, no info leaks. No new struct padding or kernel data is copied to user-space without initialization. No uninitialized heap or stack variables are read, and no control flow changes allow uninitialized memory to be accessed. In essence, this patch introduces no risks related to the reading or leaking of uninitialized memory. Therefore, considering the existing debugging tools (KASAN, LOCKDEP, UBSAN) that will catch any other bugs, **NeedsKMSAN = false.** The code changes primarily address bandwidth limitations, and sched_ext integration, which is within the scope of KASAN/LOCKDEP/UBSAN. |
| 32/3 | 2026/11/13 14:27 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series updates CFS bandwidth control (relaxing the burst limit cap to allow bursts exceeding quota and accumulating unused runtime during idle periods) and introduces the `cpu.max.runtime` cgroup v2 interface along with BPF sched_ext integration (`SCX_OPS_CHARGE_CPU_MAX`, `cgroup_set_runtime`, and `scx_bpf_task_cpu_max_runtime`).\n\nKMSAN vs KASAN/LOCKDEP applicability:\n1. No uninitialized memory or info-leak risk:\n - The newly introduced cgroup file `cpu.max.runtime` interacts with user space solely via scalar `u64` read/write handlers (`cpu_runtime_read_u64` and `cpu_runtime_write_u64`), which seq_printf/parse textual numbers without copying raw kernel memory, buffers, or structs with padding to user space.\n - The new field `debt` in `struct cfs_bandwidth` is embedded in `struct task_group`, which is allocated using `__GFP_ZERO` (`kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO)`), ensuring zero-initialization.\n - All stack variables added in the new/modified functions in `kernel/sched/fair.c`, `kernel/sched/core.c`, and `kernel/sched/ext/ext.c` (such as `throttled`, `snap`, `held`, `idle_periods`, `floor`, etc.) are explicitly initialized before any read.\n - The sched_ext BPF kfunc returns a scalar `u64` value, and the struct_ops callback passes standard pointers and scalar values.\n\n2. Bug surface:\n - The risks in this changeset primarily involve synchronization/locking ordering (`tg_bandwidth_mutex`, `cfs_b-\u003elock`, runqueue locks), arithmetic/underflow/overflow in bandwidth and debt tracking, or task reference lifecycles. These classes of bugs are already addressed by LOCKDEP, UBSAN, and KASAN.\n\nTherefore, dedicated KMSAN fuzzing is not warranted.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series updates CFS bandwidth control (relaxing the burst limit cap to allow bursts exceeding quota and accumulating unused runtime during idle periods) and introduces the `cpu.max.runtime` cgroup v2 interface along with BPF sched_ext integration (`SCX_OPS_CHARGE_CPU_MAX`, `cgroup_set_runtime`, and `scx_bpf_task_cpu_max_runtime`).\n\nKMSAN vs KASAN/LOCKDEP applicability:\n1. No uninitialized memory or info-leak risk:\n - The newly introduced cgroup file `cpu.max.runtime` interacts with user space solely via scalar `u64` read/write handlers (`cpu_runtime_read_u64` and `cpu_runtime_write_u64`), which seq_printf/parse textual numbers without copying raw kernel memory, buffers, or structs with padding to user space.\n - The new field `debt` in `struct cfs_bandwidth` is embedded in `struct task_group`, which is allocated using `__GFP_ZERO` (`kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO)`), ensuring zero-initialization.\n - All stack variables added in the new/modified functions in `kernel/sched/fair.c`, `kernel/sched/core.c`, and `kernel/sched/ext/ext.c` (such as `throttled`, `snap`, `held`, `idle_periods`, `floor`, etc.) are explicitly initialized before any read.\n - The sched_ext BPF kfunc returns a scalar `u64` value, and the struct_ops callback passes standard pointers and scalar values.\n\n2. Bug surface:\n - The risks in this changeset primarily involve synchronization/locking ordering (`tg_bandwidth_mutex`, `cfs_b-\u003elock`, runqueue locks), arithmetic/underflow/overflow in bandwidth and debt tracking, or task reference lifecycles. These classes of bugs are already addressed by LOCKDEP, UBSAN, and KASAN.\n\nTherefore, dedicated KMSAN fuzzing is not warranted.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|