Skip to content

Commit 9b07115

Browse files
committed
nproc: honor cgroupv2 CPU quotas
cgroupv1 CPU quotas are not considered, as those are now legacy (RHEL7 era), and are more complex/inefficient to parse. Tested in coreutils on Fedora 42 as detailed in tests/test-nproc.c * lib/nproc.c (cgroup2_mount): Identify the cgroup2 mount point, first at the common location for efficiency, resorting to searching mount points otherwise. (get_cgroup2_cpu_quota): Walk cgroup2 quotas for the current process, returning the lowest integer number of CPUs configured. (cpu_quota): On Linux return the cgroupv2 CPU quota if the currrent scheduler honors it. Otherwise return ULONG_MAX. (num_processors): Clamp the return to <= quota. * m4/nproc.m4: Add a check for mntent.h. * tests/test-nproc.c: Document how cgroup CPU quotas were tested.
1 parent b9c324e commit 9b07115

4 files changed

Lines changed: 261 additions & 15 deletions

File tree

‎ChangeLog‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
2025-08-19 Pádraig Brady <[email protected]>
2+
3+
nproc: honor cgroupv2 CPU quotas
4+
* lib/nproc.c (cgroup2_mount): Identify the cgroup2 mount point,
5+
first at the common location for efficiency,
6+
resorting to searching mount points otherwise.
7+
(get_cgroup2_cpu_quota): Walk cgroup2 quotas for the current process,
8+
returning the lowest integer number of CPUs configured.
9+
(cpu_quota): On Linux return the cgroupv2 CPU quota if the
10+
current scheduler honors it. Otherwise return ULONG_MAX.
11+
(num_processors): Clamp the return to <= quota.
12+
* m4/nproc.m4: Add a check for mntent.h.
13+
* tests/test-nproc.c: Document how cgroup CPU quotas were tested.
14+
115
2025-08-19 Bruno Haible <[email protected]>
216

317
doc: Mention some musl libc stubs.

‎lib/nproc.c‎

Lines changed: 181 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,12 @@
2222

2323
#include <errno.h>
2424
#include <limits.h>
25+
#if HAVE_MNTENT_H
26+
# include <mntent.h>
27+
#endif
2528
#include <stdlib.h>
29+
#include <stdio.h>
30+
#include <string.h>
2631
#include <unistd.h>
2732

2833
#if HAVE_PTHREAD_GETAFFINITY_NP && 0
@@ -62,6 +67,8 @@
6267

6368
#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))
6469

70+
#define NPROC_MINIMUM 1
71+
6572
/* Return the number of processors available to the current process, based
6673
on a modern system call that returns the "affinity" between the current
6774
process and each CPU. Return 0 if unknown or if such a system call does
@@ -244,7 +251,7 @@ num_processors_via_affinity_mask (void)
244251
/* Return the total number of processors. Here QUERY must be one of
245252
NPROC_ALL, NPROC_CURRENT. The result is guaranteed to be at least 1. */
246253
static unsigned long int
247-
num_processors_ignoring_omp (enum nproc_query query)
254+
num_processors_available (enum nproc_query query)
248255
{
249256
/* On systems with a modern affinity mask system call, we have
250257
sysconf (_SC_NPROCESSORS_CONF)
@@ -377,7 +384,159 @@ num_processors_ignoring_omp (enum nproc_query query)
377384
}
378385
#endif
379386

380-
return 1;
387+
return NPROC_MINIMUM;
388+
}
389+
390+
#if defined __linux__ || defined __ANDROID__
391+
/* Identify the cgroup2 mount point,
392+
initially at the usual location for efficiency,
393+
resorting to searching mount points otherwise.
394+
Return NULL if the mount point is not found.
395+
The returned string can be freed. */
396+
static char *
397+
cgroup2_mount (void)
398+
{
399+
FILE *fp;
400+
char *ret = NULL;
401+
402+
/* Check the usual location first. */
403+
if (access ("/sys/fs/cgroup/cgroup.controllers", F_OK) == 0)
404+
return strdup ("/sys/fs/cgroup");
405+
406+
#if HAVE_MNTENT_H
407+
/* Otherwise look for the mount point. */
408+
struct mntent *mnt;
409+
if (! (fp = setmntent ("/proc/mounts", "r")))
410+
return NULL;
411+
while ((mnt = getmntent (fp)) != NULL)
412+
{
413+
if (strcmp (mnt->mnt_type, "cgroup2") == 0)
414+
{
415+
ret = strdup (mnt->mnt_dir);
416+
break;
417+
}
418+
}
419+
endmntent (fp);
420+
#endif
421+
422+
return ret;
423+
}
424+
425+
/* Return the minimum configured cgroupv2 CPU quota for the current process.
426+
Return ULONG_MAX if quota can't be read.
427+
Returned value will be >= 1. */
428+
static unsigned long int
429+
get_cgroup2_cpu_quota (void)
430+
{
431+
unsigned long int cpu_quota = ULONG_MAX;
432+
FILE *fp;
433+
434+
fp = fopen ("/proc/self/cgroup", "r");
435+
if (! fp)
436+
return cpu_quota;
437+
438+
/* Get our cgroupv2 (unififed) hierarchy. */
439+
char *cgroup = NULL;
440+
char *cgroup_str = NULL;
441+
size_t cgroup_size = 0;
442+
ssize_t read;
443+
while ((read = getline (&cgroup_str, &cgroup_size, fp)) != -1)
444+
{
445+
if (strncmp (cgroup_str, "0::/", 4) == 0)
446+
{
447+
char *end = cgroup_str + read - 1;
448+
if (*end == '\n')
449+
*end = '\0';
450+
cgroup = cgroup_str + 3;
451+
break;
452+
}
453+
}
454+
fclose (fp);
455+
456+
char *mount = NULL;
457+
if (cgroup && ! (mount = cgroup2_mount ()))
458+
cgroup = NULL;
459+
460+
/* Find the lowest quota in the hierarchy. */
461+
char *quota_str = NULL;
462+
size_t quota_size = 0;
463+
while (cgroup && *cgroup)
464+
{
465+
/* Walk back up the nested cgroup hierarchy
466+
to find the lowest cpu quota as defined in a cpu.max file.
467+
Note this file may not be present if the cpu controller
468+
is not enabled for that part of the hierarchy. */
469+
470+
char cpu_max_file[PATH_MAX];
471+
snprintf (cpu_max_file, sizeof (cpu_max_file),
472+
"%s%s/cpu.max", mount, cgroup);
473+
474+
if ((fp = fopen (cpu_max_file, "r"))
475+
&& getline (&quota_str, &quota_size, fp) != -1
476+
&& strncmp (quota_str, "max", 3) != 0)
477+
{
478+
long quota, period;
479+
if (sscanf (quota_str, "%ld %ld", &quota, &period) == 2 && period)
480+
{
481+
double ncpus = (double)quota / period;
482+
if (cpu_quota == ULONG_MAX || ncpus < cpu_quota)
483+
{
484+
cpu_quota = MAX (1, (long)(ncpus + 0.5));
485+
/* nproc will return 1 minimum, so no point going lower */
486+
if (cpu_quota == 1)
487+
*cgroup = '\0';
488+
}
489+
}
490+
}
491+
492+
if (fp)
493+
fclose (fp);
494+
495+
char *last_sep = strrchr (cgroup, '/');
496+
if (! last_sep)
497+
break;
498+
if (last_sep == cgroup && *(cgroup + 1))
499+
*(cgroup + 1) = '\0'; /* Iterate on "/" also. */
500+
else
501+
*last_sep = '\0';
502+
}
503+
504+
free (quota_str);
505+
free (mount);
506+
free (cgroup_str);
507+
508+
return cpu_quota;
509+
}
510+
#endif
511+
512+
513+
/* Return the cgroupv2 CPU quota if the current scheduler honors it.
514+
Otherwise return ULONG_MAX.
515+
Returned value will be >= 1. */
516+
static unsigned long int
517+
cpu_quota (void)
518+
{
519+
unsigned long int quota = ULONG_MAX;
520+
521+
#if defined __linux__ || defined __ANDROID__
522+
# if HAVE_SCHED_GETAFFINITY_LIKE_GLIBC && defined SCHED_DEADLINE
523+
/* We've a new enough sched.h */
524+
switch (sched_getscheduler (0))
525+
{
526+
case -1:
527+
case SCHED_FIFO:
528+
case SCHED_RR:
529+
case SCHED_DEADLINE:
530+
quota = ULONG_MAX;
531+
break;
532+
default:
533+
quota = get_cgroup2_cpu_quota ();
534+
break;
535+
}
536+
# endif
537+
#endif
538+
539+
return quota;
381540
}
382541

383542
/* Parse OMP environment variables without dependence on OMP.
@@ -416,13 +575,13 @@ parse_omp_threads (char const* threads)
416575
unsigned long int
417576
num_processors (enum nproc_query query)
418577
{
419-
unsigned long int omp_env_limit = ULONG_MAX;
578+
unsigned long int nproc_limit = ULONG_MAX;
420579

580+
/* Honor the OpenMP environment variables, recognized also by all
581+
programs that are based on OpenMP. */
421582
if (query == NPROC_CURRENT_OVERRIDABLE)
422583
{
423-
unsigned long int omp_env_threads;
424-
/* Honor the OpenMP environment variables, recognized also by all
425-
programs that are based on OpenMP. */
584+
unsigned long int omp_env_threads, omp_env_limit;
426585
omp_env_threads = parse_omp_threads (getenv ("OMP_NUM_THREADS"));
427586
omp_env_limit = parse_omp_threads (getenv ("OMP_THREAD_LIMIT"));
428587
if (! omp_env_limit)
@@ -431,14 +590,22 @@ num_processors (enum nproc_query query)
431590
if (omp_env_threads)
432591
return MIN (omp_env_threads, omp_env_limit);
433592

593+
nproc_limit = omp_env_limit;
434594
query = NPROC_CURRENT;
435595
}
436-
/* Here query is one of NPROC_ALL, NPROC_CURRENT. */
437-
if (omp_env_limit == 1)
438-
/* No need to even call num_processors_ignoring_omp (query). */
439-
return 1;
440-
{
441-
unsigned long nprocs = num_processors_ignoring_omp (query);
442-
return MIN (nprocs, omp_env_limit);
443-
}
596+
597+
/* Honor any CPU quotas. */
598+
if (query == NPROC_CURRENT && nproc_limit > NPROC_MINIMUM)
599+
{
600+
unsigned long int quota = cpu_quota ();
601+
nproc_limit = MIN (quota, nproc_limit);
602+
}
603+
604+
if (nproc_limit > NPROC_MINIMUM)
605+
{
606+
unsigned long nprocs = num_processors_available (query);
607+
nproc_limit = MIN (nprocs, nproc_limit);
608+
}
609+
610+
return nproc_limit;
444611
}

‎m4/nproc.m4‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ AC_DEFUN([gl_PREREQ_NPROC],
1717
dnl Persuade glibc <sched.h> to declare CPU_SETSIZE, CPU_ISSET etc.
1818
AC_REQUIRE([AC_USE_SYSTEM_EXTENSIONS])
1919
20-
AC_CHECK_HEADERS([sys/pstat.h sys/sysmp.h sys/param.h],,,
20+
AC_CHECK_HEADERS([mntent.h sys/pstat.h sys/sysmp.h sys/param.h],,,
2121
[AC_INCLUDES_DEFAULT])
2222
dnl <sys/sysctl.h> requires <sys/param.h> on OpenBSD 4.0.
2323
AC_CHECK_HEADERS([sys/sysctl.h],,,

‎tests/test-nproc.c‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
nproc honors cgroup v2 CPU quotas
3+
and was tested in coreutils on a Fedora 42 system as follows:
4+
5+
# Note we honor a limit anywhere in /proc/self/cgroup hierarchy
6+
# so apply settings below in the parent cgroup of the current process
7+
$ nested_cgroup=/sys/fs/cgroup/$(dirname $(cut -d/ -f2- /proc/self/cgroup))
8+
$ echo $nested_cgroup
9+
/sys/fs/cgroup/user.slice/user-1001.slice/[email protected]/app.slice
10+
11+
# This test system has 4 CPUs
12+
$ src/nproc
13+
4
14+
15+
# Behave like MAX (1, (int)round(quota/period))
16+
$ echo "100000 100000" > $nested_cgroup/cpu.max
17+
$ src/nproc
18+
1
19+
$ echo "90000 100000" > $nested_cgroup/cpu.max
20+
$ src/nproc
21+
1
22+
$ echo "140000 100000" > $nested_cgroup/cpu.max
23+
$ src/nproc
24+
1
25+
$ echo "150000 100000" > $nested_cgroup/cpu.max
26+
$ src/nproc
27+
2
28+
29+
# Ensure NPROC_ALL takes precedence
30+
$ echo "100000 100000" > $nested_cgroup/cpu.max
31+
$ src/nproc --all
32+
4
33+
34+
# Ensure OMP env vars have appropriate precedence
35+
$ echo "200000 100000" > $nested_cgroup/cpu.max
36+
$ OMP_NUM_THREADS=10 src/nproc
37+
10
38+
$ OMP_THREAD_LIMIT=10 src/nproc
39+
2
40+
41+
# Ensure quota only reduces
42+
$ echo "500000 100000" > $nested_cgroup/cpu.max
43+
$ src/nproc
44+
4
45+
46+
# Restore system to unlimited
47+
$ echo "max 100000" > $nested_cgroup/cpu.max
48+
49+
# Test quota in root hierarchy
50+
$ podman run --cpus=2 -i --rm fedora:latest /tmp/nproc
51+
2
52+
$ podman run --cpus=1.5 -i --rm fedora:latest /tmp/nproc
53+
2
54+
$ podman run --cpus=1.4 -i --rm fedora:latest /tmp/nproc
55+
1
56+
$ podman run --cpus=100 -i --rm fedora:latest /tmp/nproc
57+
4
58+
59+
# Docker is similar to podman, but explicitly limits max allowable
60+
$ docker run --cpus=1.4 -i --rm fedora:latest /tmp/nproc
61+
1
62+
$ docker run --cpus=100 -i --rm fedora:latest /tmp/nproc
63+
docker: Error response from daemon:
64+
range of CPUs is from 0.01 to 4.00, as there are only 4 CPUs
65+
*/

0 commit comments

Comments
 (0)