Skip to content

cgroup: make cpu.max parsing match the kernel - #2406

Open
harche wants to merge 3 commits into
containers:mainfrom
harche:fix-parse-cpu-max
Open

harche wants to merge 3 commits into
containers:mainfrom
harche:fix-parse-cpu-max

Conversation

@harche

@harche harche commented Oct 23, 2026 •

Copy link
Copy Markdown

parse_cpu_max() read some cpu.max values differently from the kernel. With the systemd driver, this could give the scope and the container different CPU limits, or make the container fail to start with an sd-bus error. Details are in #2405.

This fixes the cases where crun and the kernel read the value differently:

  • After the quota (a number or max), whitespace or the end of the string is required.
  • The period must be digits only, without a sign. A period of 0 is rejected, because systemd reads it as "no period".
  • Only whitespace may follow the values. A newline between the quota and the period is rejected, because write_unified_resources() writes each line separately, so the kernel would see "50000\n100000" as two writes.
  • Any whitespace is skipped before and after the values, so "\tmax" and "\nmax 100000" are accepted, as the kernel accepts them.
  • On crun update, when cpu.max has no period, the current period is read from the container's cpu.max, like the kernel does, instead of using the default to compute CPUQuotaPerSecUSec.

Other values that the kernel rejects, such as a quota or a period out of its range, are not checked here. They fail when cpu.max is written, as they do for cpu.quota and cpu.period.

Well-formed values are read as before, including what the kernel writes in cpu.max (max 100000\n), which complete_cpu_max() reads back.

Testing

On Fedora 44, kernel 6.19, systemd 259.

  • Unit tests in tests/tests_libcrun_cgroup.c: test_parse_cpu_max for valid values, test_parse_cpu_max_invalid for the malformed ones.
  • With the systemd driver, every value from cgroup-systemd: parse_cpu_max accepts malformed cpu.max values that the kernel reads differently #2405 ("2 -9", "50000+200000", "max5", "5100000\n0000", "50000 -1") is rejected with invalid value for cpu.max. So are "50000\n100000" and "max\n100000" (with the cgroupfs driver, the container ends up with quota 100000).
  • "\tmax", "\nmax 100000" and "50000 100000\n\n" give the scope and the container the same limits.
  • Values out of the kernel's range ("50000 999", "999 100000", "+50000 100000") fail at the write to cpu.max with both drivers, the same way typed cpu.quota / cpu.period do.
  • Update with the systemd driver: created a container with cpu.period 200000, then ran crun update with unified["cpu.max"] = "50000". Before, the container got 50000 200000 but systemd recorded CPUQuotaPerSecUSec=500ms. Now systemd records 250ms with a 200ms period, which matches.
  • tests/test_update.py passes with both CGROUP_MANAGER=cgroupfs and systemd. tests/test_cgroup_resources.py passes except cgroup-resources-hugetlb-limits, which fails the same way on main (no hugetlb controller in the VM).
  • make clang-format is clean.

@harche
harche force-pushed the fix-parse-cpu-max branch from 31326ad to d658210 Compare October 23, 2026 02:40
@harche

harche commented Oct 24, 2026

Copy link
Copy Markdown
Author

@kolyshkin, this fixes parsing in parse_cpu_max(), which was added in #2296. Could you take a look when you have a moment?

@kolyshkin

Copy link
Copy Markdown
Collaborator

So I think we should use the same validation rules as the kernel (i.e. writing to cpu.max).

The kernel reads sscanf(buf, "%20s %llu"):

  • The first word is cut at 20 characters and becomes the quota token.
  • The token must start with a digit; anything after the digits is ignored.
    A token that is not a number must be exactly max.
  • The period is optional. If it is missing or invalid, the cgroup's
    current period is kept.
  • Trailing garbage is ignored.
  • Numbers wrap around on overflow without an error.

After parsing, the values must satisfy:

  • 1000 ≤ quota ≤ 2^44−1, or max;
  • 1000 ≤ period ≤ 1000000.

1. The kernel accepts but parse_cpu_max() rejects

These work with the cgroupfs driver and fail with the systemd driver.

cpu.max Kernel result Why crun rejects it
"\tmax", "\nmax 100000" max / current period, max / 100000 only ' ' is skipped before max (a number may start with any whitespace, because strtoll() skips it)
"50000\n100000", "max\n100000" 50000 / 100000, max / 100000 a newline is not accepted as the separator
"50000 100000 1", "50000 100000x", "50000 100000\n1" 50000 / 100000 trailing garbage
"50000 -1", "50000 +100000", "50000 abc" 50000 / current period (the invalid period is ignored) invalid period
"50000+200000", "50000-1", "50000x 100000" 50000 / current period; 50000 / 100000 for the last one garbage attached to the quota
"18446744073709552616" (2^64 + 1000) quota 1000 (wraps around) ERANGE

2. parse_cpu_max() accepts but the kernel rejects

Both drivers fail. With systemd, the scope has already been set up when the
write to the container's cpu.max returns EINVAL, so the error shows up
later and is less clear.

cpu.max crun result Why the kernel rejects it
"+50000 100000" 50000 / 100000 %llu does not accept a + sign, and "+50000" is not "max"
"50000 0", "max 0" period 0. With systemd this silently means "no period", and the default is used period < 1000
"50000 999", "50000 1000001", "50000 18446744073709551615" period passed to systemd as is (UINT64_MAX is USEC_INFINITY) period out of [1000, 1000000]
"999 100000", "17592186044416 100000" quota passed to systemd as is quota out of [1000, 2^44−1]

3. Both accept, but with different values

cpu.max Kernel crun
"000000000000000500001000" (a 24-character word) quota token "00000000000000050000" is cut at 20 characters, and the remaining "1000" becomes the period: 50000 / 1000 500001000 / default period
"50000" (no period) keeps the cgroup's current period linux.resources.cpu.period if set, otherwise the systemd default (100000)

The last row only matters if the current period differs from what crun
sends to systemd, so in practice it probably does not.

Notes

  • Group 1 is the only one where the systemd driver fails and the cgroupfs
    driver works. Most of it is rejected on purpose by this PR, and runc
    rejects the same values. Only "\tmax" looks like an accidental
    inconsistency.
  • Group 2 is easiest to close with range checks in parse_cpu_max()
    itself.

Comment thread src/libcrun/cgroup-utils.c Resolved
@kolyshkin

Copy link
Copy Markdown
Collaborator

To clarify: I think our rules must be at least as strict as the kernel (say the kernel does not accept + and we currently do) and might be stricter (say we can error out on garbage at the end even if the kernel does not), but I would not error out on say \n (unless there's a good reason to do that, which I don't see now).

@harche
harche force-pushed the fix-parse-cpu-max branch from d658210 to 0dbc50c Compare October 24, 2026 23:21
@harche harche changed the title cgroup: reject malformed cpu.max values cgroup: make cpu.max parsing match the kernel Oct 24, 2026
@harche

harche commented Oct 24, 2026 •

Copy link
Copy Markdown
Author

Thanks for going through this so carefully. The tables made it easy to see what was off.

I agree with the rule: be at least as strict as the kernel, stricter is fine, but don't reject things like \n without a good reason. Here's what I changed:

Group 1. Tabs and other whitespace now work around and between the two values, and so do empty lines before or after the value, so "\tmax" and "\nmax 100000" are accepted. Trailing garbage, bad periods and garbage stuck to the quota are still rejected, as you suggested.

I kept rejecting a newline between the two values ("50000\n100000", "max\n100000"), though. The kernel would read them as quota and period if it got the whole string in one write, but crun doesn't write a unified value in one go: write_unified_resources() splits it on newlines and writes each line separately. So for "50000\n100000" the kernel first gets "50000" and then "100000". I tried it with the cgroupfs driver, starting from period 200000, and the container ended up with 100000 200000. Accepting it in parse_cpu_max() would have told systemd 50000/100000, which is exactly the kind of mismatch this PR is trying to fix.

Group 2. I added the same checks the kernel does: no sign on the quota, a period between 1000 and 1000000, and a quota between 1000 and 2^44−1. These values now fail early with invalid value for cpu.max, before anything is sent to systemd.

Group 3. The 24-character case is now rejected: a quota longer than 20 characters is an error.

I took a closer look at "50000" with no period. On create it's fine. crun first writes the period from the spec, or the new cgroup starts with 100000, which is what crun tells systemd anyway. On crun update it can go wrong, though. I tried it: I created a container with period 200000, then updated it with cpu.max set to "50000". The kernel kept period 200000, so the container got 25% of a CPU. But crun used 100000 to work out the value for systemd, so systemd recorded 50% (CPUQuotaPerSecUSec=500ms). Now, on update, when cpu.max has no period, crun reads the current period from the container's cpu.max, like the kernel does. After the change systemd records 250ms, which matches.

I also wrote each test value to a real cpu.max on kernel 6.19, to check that whatever crun accepts, the kernel accepts with the same numbers.

@harche
harche force-pushed the fix-parse-cpu-max branch from 0dbc50c to 8275681 Compare October 24, 2026 23:31
@harche

harche commented Oct 26, 2026

Copy link
Copy Markdown
Author

@kolyshkin while working on this, I looked for the same kind of problem in other parts of crun and found a few. I'm sharing them here so you know about them. I'll send fixes as separate PRs once this one is merged.

1. Other unified values with the systemd driver

get_value_from_unified_map() turns memory.max, memory.high, memory.low, memory.min, memory.swap.max, memory.zswap.max, pids.max, cpu.weight and cpu.idle into systemd properties, with the same kind of mismatch as cpu.max. I tested these on kernel 6.19 with systemd 259:

  • A leading zero means octal to the kernel but decimal to crun. With pids.max = "0100", systemd gets TasksMax=100 but the container gets 64. The same happens with cpu.weight and the memory files. The container starts fine, with different limits in the scope and the container.
  • An empty value becomes 0, while the cgroupfs driver skips it. With memory.swap.max = "", systemd gets MemorySwapMax=0, so the scope can't swap, but the container's cgroup still shows max.
  • Values the kernel rejects are still sent to systemd: "-1" (which becomes infinity), "+N", pids.max above 4194304, cpu.weight = "0" (which systemd reads as "make it idle"), and cpu.idle = "2". The error only comes later, at the raw write.

2. The systemd driver rejects values that cgroupfs accepts

This is allowed under the "stricter is fine" rule, but the two drivers behave differently:

  • memory.max = "512M" works with cgroupfs and fails with systemd.
  • cpuset_string_to_bitmask() rejects "0-3:1/2", "1-N" and "0, 2" for cpuset.cpus, which the kernel accepts.

I'm not sure these are worth supporting. What do you think?

3. The "memory limit could be too low" hint

is_memory_limit_too_low() reads unified memory.max with strtol and doesn't check where the number ends. So "max" reads as 0, and a typed limit: -1 also counts as too low. Any start failure then gets the "the memory limit could be too low" prefix, even when memory is unlimited.

@kolyshkin

Copy link
Copy Markdown
Collaborator

@harche this looks much better now, thanks! Can you split the reading of the missing period during update into a separate commit?

Also, read_cpu_max_period and complete_cpu_max look similar -- maybe split the common part into e.g. read_cpu_max (path, &quota, &period, &has_period, err)?

Other than that, LGTM

@kolyshkin

Copy link
Copy Markdown
Collaborator

@harche can you use your real email in signed-off-by please?

@harche

harche commented Nov 12, 2026

Copy link
Copy Markdown
Author

@kolyshkin that's the address I use to sign off everywhere, including my Kubernetes commits. It's my GitHub noreply address, and I use it to keep my email away from spammers, since commit history is public and gets scraped. It's tied to my GitHub account, the name is my real name, and the DCO check on this PR passes.

@harche

harche commented Nov 12, 2026

Copy link
Copy Markdown
Author

@kolyshkin thanks, both done:

  • Reading the current period on update is now its own commit (a898f35).
  • read_cpu_max (path, &quota, &period, &has_period, err) is shared by complete_cpu_max() and the systemd update path (16d6ae8). read_cpu_max_period is gone.

Also:

  • read_cpu_max() now ignores only ENOENT (ba90afb). With any other error, such as EIO, the systemd scope was changed before the update failed. I put this in its own commit since it also changes complete_cpu_max() on main.
  • An update to "max" no longer sends a period (a898f35).
  • New test: update-unified-cpu-max-keeps-period-systemd (a898f35).
  • Fixed the first commit's message (cf82b37): the kernel accepts "50000+200000" and "50000 -1", it doesn't reject them.

Each commit builds and passes the unit tests on its own.

@kolyshkin

Copy link
Copy Markdown
Collaborator

Thanks for the update. I think this is getting more complicated than it needs to be. The goal is to keep crun from misreading cpu.max in ways that make the systemd scope differ from what the kernel sets. It is not to copy every check the kernel does. Anything we leave out is still rejected by the kernel when the value is written, so the error just shows up a bit later which is OK because we get an error anyway and it rarely makes sense to optimize for faster errors.

  1. Hardcoded kernel limits (CPU_MAX_MIN_USEC, CPU_MAX_MAX_PERIOD_USEC, CPU_MAX_MAX_QUOTA_USEC). These copy the checks in tg_set_cfs_bandwidth(). If the kernel ever changes them, crun will reject valid values. We also don't check these ranges for the typed cpu.quota / cpu.period, so checking them only for the unified map is inconsistent. The one check worth keeping is that period must not be 0, since systemd reads 0 as "no period". The rest of the checks can be dropped.
  2. The 20-character quota limit (CPU_MAX_QUOTA_MAX_LEN). It only matters for a quota with 15+ leading zeros, which nobody writes. Please drop it.
  3. Leading tabs and empty lines ("\tmax", "\nmax 100000"). Until now only spaces were accepted there, and nobody has complained. Handling \n separately from other whitespace makes the parser harder to read. If you want to be lenient, skipping all whitespace with isspace() at the start and at the end is enough. A newline between quota and period must still be rejected.
  4. "cgroup: read_cpu_max: ignore only a missing cpu.max". The EIO scenario is hypothetical, and there's no reproducer for it. The commit also changes complete_cpu_max() for the cgroupfs driver: any error other than ENOENT now fails create/update, where it used to be ignored. I'd rather drop this commit, or maybe keep the code but drop the test case which is complicated.

What I think the parser needs:

  • after max or the quota number, require whitespace or the end of the string;
  • the period must be digits only, without a sign;
  • allow only whitespace after the values;
  • reject a period of 0.

That fixes everything listed in #2405 in a much smaller diff, and the unit test tables get shorter too.

The other two commits ("cgroup: add read_cpu_max()" and "cgroup-systemd: keep the current period on update") look good to me as they are.

@harche

harche commented Nov 20, 2026

Copy link
Copy Markdown
Author

@kolyshkin thanks, that makes sense. Done:

  1. Removed the kernel range checks. The parser only rejects a period of 0 now. The quota check is back to what main has (<= 0).
  2. Removed the 20-character limit.
  3. Whitespace is skipped with isspace() at the start and at the end. Between the quota and the period only spaces and tabs are accepted, so a newline there is still rejected.
  4. Dropped "cgroup: read_cpu_max: ignore only a missing cpu.max".

The parser now does what you listed: whitespace or the end of the string after the quota, a period of digits only, only whitespace after the values, and no period of 0. The other two commits are unchanged.

One thing to know about 3. A line with only whitespace is now accepted by the parser, for example " \nmax" or "50000 100000\n \n". write_unified_resources() skips empty lines but not these, so the kernel gets " " and returns EINVAL. The container fails with write to `cpu.max`: Invalid argument, with both drivers. Before, the parser rejected these values. I left it this way, since it is an error either way and not a mismatch. Tell me if you would rather reject them in the parser.

Tested on Fedora 44 (kernel 6.19, systemd 259):

  • Every value from cgroup-systemd: parse_cpu_max accepts malformed cpu.max values that the kernel reads differently #2405 is rejected with invalid value for `cpu.max` under the systemd driver.
  • "\tmax" and "\nmax 100000" run, with the same limits in the scope and the container.
  • Values out of the kernel's range ("50000 999", "999 100000", "+50000 100000", ...) fail at the write to cpu.max with both drivers, the same way typed cpu.quota / cpu.period do.
  • tests/test_update.py passes with both CGROUP_MANAGER=cgroupfs and systemd.

@kolyshkin kolyshkin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks

@mrunalp mrunalp left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested both cases with crun update --resources on Fedora 45 (kernel 7.3.3, systemd 262.1), comparing main at 26f0fcff with this PR at 258f9ee2. Each run started with cpu.max set to 50000 100000.

char *endptr = NULL;

while (*it == ' ')
while (isspace ((unsigned char) *it))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we reject a whitespace-only line before updating the systemd scope? This loop skips the space and newline in " \nmax 200000", but write_unified_resources() sends the space to the kernel as a separate write.

I ran a systemd container with {"unified":{"cpu.max":" \nmax 200000"}} as the update payload. On the PR, crun update exited 1 with Invalid argument. The container’s cpu.max stayed at 50000 100000, but systemctl show reported that CPUQuotaPerSecUSec went from 500ms to infinity and CPUQuotaPeriodUSec from 100ms to 200ms. Main rejected the value before either scope property changed. This would be worth covering with a failed-update test that checks the scope afterward.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 4f30a7e. The value must now be a single non-empty line, so a whitespace-only line is rejected before the scope is updated.

while (*it == '\n')
it++;
eol = it + strcspn (it, "\n");
if (UNLIKELY (eol[strspn (eol, "\n")] != '\0'))
return crun_make_error (err, 0, "invalid value for `cpu.max`: `%s`", value);

I also added update-unified-cpu-max-invalid-systemd, which runs failed updates and checks that the scope and the container's cpu.max are unchanged.

Comment thread src/libcrun/cgroup-utils.c Outdated

it = endptr;
while (*it == ' ')
while (*it == ' ' || *it == '\t')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this loop accept same-line whitespace such as \r, while still stopping at \n? I ran crun update --resources with {"unified":{"cpu.max":"50000\r200000"}}. On main, both cgroupfs and systemd applied 50000 200000. On the PR, cgroupfs still applied it, but systemd returned invalid value for `cpu.max` and left the container at 50000 100000.

write_unified_resources() splits only on \n, so the kernel receives the carriage return in a single write. Adding this input to the valid parser cases would cover the regression.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 4f30a7e. Any whitespace is accepted between the values now, so "50000\r200000" gives 50000 200000 with both drivers again. I added it to the valid parser cases.

it = endptr;
while (isspace ((unsigned char) *it))
it++;

With the systemd driver, parse_cpu_max() turns cpu.max from the unified
map into CPUQuotaPerSecUSec and CPUQuotaPeriodUSec, while the raw string
is still written to the container's cpu.max. When crun and the kernel
read the string differently, the scope and the container end up with
different limits, or the container fails to start with an sd-bus error.

- "50000+200000", "max5": no separator was required after the quota,
  so crun read "200000" and "5" as the period, which the kernel does
  not. Require whitespace or the end of the string after the quota.
- "50000 -1", "2 -9": strtoull() accepts a sign and wraps a negative
  period around, while the kernel ignores such a period. Accept only
  digits.
- "50000\n100000", "max\n100000": everything after the first newline
  was ignored, but write_unified_resources() writes each line
  separately, so the kernel gets "50000" and then "100000". Likewise,
  with " \n50000 100000" or "50000 100000\n " the kernel gets a lone
  " " and fails after the systemd scope was already changed. Require
  the value to be a single non-empty line, ignoring empty lines around
  it, and allow only whitespace after the values.
- "50000 0": systemd reads a period of 0 as not set. Reject it.
- "\tmax", "\nmax 100000": the kernel accepts them, but only spaces
  were skipped before the quota. Skip any whitespace around and
  between the values, so that "50000\r200000" keeps working.

Other values that the kernel rejects, such as a quota or a period out
of its range, are not checked here. They fail when cpu.max is written,
as they do for cpu.quota and cpu.period.

Closes: containers#2405

Signed-off-by: Harshal Patil <12152047+harche@users.noreply.github.com>
Assisted-by: Claude Code (claude-opus-5-5)
Assisted-by: Claude Code (claude-fable-5-2)
Move the reading of a cgroup's cpu.max out of complete_cpu_max(), so
that it can be used by the systemd driver too.

Signed-off-by: Harshal Patil <12152047+harche@users.noreply.github.com>
Assisted-by: Claude Code (claude-opus-5-5)
When cpu.max in the unified map has no period, the kernel keeps the
cgroup's current period, but on update crun computed CPUQuotaPerSecUSec
with the default period. For a container with a period of 200000,
updating cpu.max to "50000" gave the container "50000 200000", while
systemd recorded CPUQuotaPerSecUSec=500ms instead of 250ms.

Read the current period from the container's cpu.max instead.

Only do this when systemd supports CPUQuotaPeriodUSec. Older systemd
always applies its default period, so the quota must be computed with
that period.

Signed-off-by: Harshal Patil <12152047+harche@users.noreply.github.com>
Assisted-by: Claude Code (claude-opus-5-5)
*has_period = false;
if (*it && *it != '\n')
/* strtoull() would also accept a sign, and wrap a negative value. */
if (isdigit ((unsigned char) *it))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need the same check for quota (line 1480)? Does the kernel complain in this case or a trailing + is fine?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd also suggest adding some tests with +QUOTA and +PERIOD


ret = append_resources (m, true, state_dir, resources, cgroup_mode, cgroup_status->scope, &cgroup_status->bpf_dev_set,
&devices_map, err);
ret = append_resources (m, true, state_dir, resources, cgroup_mode, cgroup_status->scope, cgroup_status->path,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's use the systemd scope cgroup (could be different if using a subcgroup for the container).

You can just move the definition at line 2462 earlier and use it here

return ret;
if (has_period)
period = max_period;
else if (period == 0 && quota > 0 && cgroup_path && ! property_missing_p (missing_properties, "CPUQuotaPeriodUSec"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we read the container’s current period here even when CPUQuotaPeriodUSec is unavailable? A quota-only cpu.max write keeps the container’s period, so we still need that period to calculate the requested CPU rate for CPUQuotaPerSecUSec.

I checked append_cpu_quota() with a C harness that supplied a current cpu.max of 25000 50000 and a quota-only update of 50000. With the period property available, crun emitted CPUQuotaPerSecUSec=1000000, matching the requested one CPU. Marking just CPUQuotaPeriodUSec missing made crun emit CPUQuotaPerSecUSec=500000. That would cap the parent scope at half a CPU even though the container requests one.

Removing the property check from this condition would preserve the rate calculation. The check below already handles whether to send CPUQuotaPeriodUSec to systemd.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants