From 7f1140b48b45060f4bc6e63458f2b025782d7036 Mon Sep 17 00:00:00 2001 From: John Slade Date: Thu, 28 Mar 2024 11:35:52 +0000 Subject: [PATCH] core: Add cgroupsv2 support to parallel.cpp The parallel code works out how many CPUs are on the system by checking the quota it has been assigned in the Linux cgroup. The existing code works under cgroups v1 but the file structure changed in cgroups v2. From [1]: "cpu.cfs_quota_us" and "cpu.cfs_period_us" are replaced by "cpu.max" which contains both quota and period. This commit add support to parallel so it will read from the cgroups v2 location. v1 support is still retained. Resolves #25284 [1] https://github.com/torvalds/linux/commit/0d5936344f30aba0f6ddb92b030cb6a05168efe6 --- modules/core/src/parallel.cpp | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/modules/core/src/parallel.cpp b/modules/core/src/parallel.cpp index 84e94da877..d81577cfed 100644 --- a/modules/core/src/parallel.cpp +++ b/modules/core/src/parallel.cpp @@ -870,7 +870,22 @@ int getNumberOfCPUsImpl(const char *filename) #if defined CV_HAVE_CGROUPS static inline -unsigned getNumberOfCPUsCFS() +unsigned getNumberOfCPUsCFSv2() +{ + int cfs_quota = 0; + int cfs_period = 0; + + std::ifstream ss_cpu_max("/sys/fs/cgroup/cpu.max", std::ios::in | std::ios::binary); + ss_cpu_max >> cfs_quota >> cfs_period; + + if (ss_cpu_max.fail() || cfs_quota < 1 || cfs_period < 1) /* values must not be 0 or negative */ + return 0; + + return (unsigned)max(1, cfs_quota/cfs_period); +} + +static inline +unsigned getNumberOfCPUsCFSv1() { int cfs_quota = 0; { @@ -966,8 +981,11 @@ int getNumberOfCPUs_() static unsigned ncpus_impl_cpuset = (unsigned)getNumberOfCPUsImpl("/sys/fs/cgroup/cpuset/cpuset.cpus"); ncpus = minNonZero(ncpus, ncpus_impl_cpuset); - static unsigned ncpus_impl_cfs = getNumberOfCPUsCFS(); - ncpus = minNonZero(ncpus, ncpus_impl_cfs); + static unsigned ncpus_impl_cfs_v1 = getNumberOfCPUsCFSv1(); + ncpus = minNonZero(ncpus, ncpus_impl_cfs_v1); + + static unsigned ncpus_impl_cfs_v2 = getNumberOfCPUsCFSv2(); + ncpus = minNonZero(ncpus, ncpus_impl_cfs_v2); #endif static unsigned ncpus_impl_devices = (unsigned)getNumberOfCPUsImpl("/sys/devices/system/cpu/online");