]> git.ipfire.org Git - thirdparty/squid.git/blame - src/CpuAffinitySet.cc
Source Format Enforcement (#763)
[thirdparty/squid.git] / src / CpuAffinitySet.cc
CommitLineData
96c2bb61 1/*
f70aedc4 2 * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
96c2bb61 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
96c2bb61
AR
7 */
8
bbc27441
AJ
9/* DEBUG: section 54 Interprocess Communication */
10
f7f3304a 11#include "squid.h"
96c2bb61
AR
12#include "base/TextException.h"
13#include "CpuAffinitySet.h"
14#include "Debug.h"
15#include "util.h"
16
074d6a40
AJ
17#include <cerrno>
18#include <cstring>
96c2bb61 19
96c2bb61
AR
20CpuAffinitySet::CpuAffinitySet()
21{
22 CPU_ZERO(&theCpuSet);
23 CPU_ZERO(&theOrigCpuSet);
24}
25
26void
27CpuAffinitySet::apply()
28{
29 Must(CPU_COUNT(&theCpuSet) > 0); // CPU affinity mask set
30 Must(!applied());
31
32 bool success = false;
33 if (sched_getaffinity(0, sizeof(theOrigCpuSet), &theOrigCpuSet)) {
b69e9ffa 34 int xerrno = errno;
96c2bb61
AR
35 debugs(54, DBG_IMPORTANT, "ERROR: failed to get CPU affinity for "
36 "process PID " << getpid() << ", ignoring CPU affinity for "
b69e9ffa 37 "this process: " << xstrerr(xerrno));
96c2bb61
AR
38 } else {
39 cpu_set_t cpuSet;
41d00cd3 40 memcpy(&cpuSet, &theCpuSet, sizeof(cpuSet));
6d03885d 41 (void) CPU_AND(&cpuSet, &cpuSet, &theOrigCpuSet);
96c2bb61
AR
42 if (CPU_COUNT(&cpuSet) <= 0) {
43 debugs(54, DBG_IMPORTANT, "ERROR: invalid CPU affinity for process "
44 "PID " << getpid() << ", may be caused by an invalid core in "
45 "'cpu_affinity_map' or by external affinity restrictions");
46 } else if (sched_setaffinity(0, sizeof(cpuSet), &cpuSet)) {
b69e9ffa 47 int xerrno = errno;
96c2bb61 48 debugs(54, DBG_IMPORTANT, "ERROR: failed to set CPU affinity for "
b69e9ffa 49 "process PID " << getpid() << ": " << xstrerr(xerrno));
96c2bb61
AR
50 } else
51 success = true;
52 }
53 if (!success)
54 CPU_ZERO(&theOrigCpuSet);
55}
56
57void
58CpuAffinitySet::undo()
59{
60 if (applied()) {
61 if (sched_setaffinity(0, sizeof(theOrigCpuSet), &theOrigCpuSet)) {
b69e9ffa 62 int xerrno = errno;
96c2bb61
AR
63 debugs(54, DBG_IMPORTANT, "ERROR: failed to restore original CPU "
64 "affinity for process PID " << getpid() << ": " <<
b69e9ffa 65 xstrerr(xerrno));
96c2bb61
AR
66 }
67 CPU_ZERO(&theOrigCpuSet);
68 }
69}
70
71bool
5ffe1090 72CpuAffinitySet::applied()
96c2bb61 73{
5ffe1090
DK
74 // NOTE: cannot be const.
75 // According to CPU_SET(3) and, apparently, on some systems (e.g.,
76 // OpenSuSE 10.3) CPU_COUNT macro expects a non-const argument.
96c2bb61
AR
77 return (CPU_COUNT(&theOrigCpuSet) > 0);
78}
79
80void
81CpuAffinitySet::set(const cpu_set_t &aCpuSet)
82{
41d00cd3 83 memcpy(&theCpuSet, &aCpuSet, sizeof(theCpuSet));
96c2bb61 84}
f53969cc 85