]> git.ipfire.org Git - thirdparty/squid.git/blob - src/CpuAffinitySet.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / CpuAffinitySet.cc
1 /*
2 * $Id$
3 *
4 * DEBUG: section 54 Interprocess Communication
5 *
6 */
7
8 #include "squid.h"
9 #include "base/TextException.h"
10 #include "CpuAffinitySet.h"
11 #include "Debug.h"
12 #include "util.h"
13
14 #if HAVE_ERRNO_H
15 #include <errno.h>
16 #endif
17 #if HAVE_STRING_H
18 #include <string.h>
19 #endif
20
21 CpuAffinitySet::CpuAffinitySet()
22 {
23 CPU_ZERO(&theCpuSet);
24 CPU_ZERO(&theOrigCpuSet);
25 }
26
27 void
28 CpuAffinitySet::apply()
29 {
30 Must(CPU_COUNT(&theCpuSet) > 0); // CPU affinity mask set
31 Must(!applied());
32
33 bool success = false;
34 if (sched_getaffinity(0, sizeof(theOrigCpuSet), &theOrigCpuSet)) {
35 debugs(54, DBG_IMPORTANT, "ERROR: failed to get CPU affinity for "
36 "process PID " << getpid() << ", ignoring CPU affinity for "
37 "this process: " << xstrerror());
38 } else {
39 cpu_set_t cpuSet;
40 memcpy(&cpuSet, &theCpuSet, sizeof(cpuSet));
41 (void) CPU_AND(&cpuSet, &cpuSet, &theOrigCpuSet);
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)) {
47 debugs(54, DBG_IMPORTANT, "ERROR: failed to set CPU affinity for "
48 "process PID " << getpid() << ": " << xstrerror());
49 } else
50 success = true;
51 }
52 if (!success)
53 CPU_ZERO(&theOrigCpuSet);
54 }
55
56 void
57 CpuAffinitySet::undo()
58 {
59 if (applied()) {
60 if (sched_setaffinity(0, sizeof(theOrigCpuSet), &theOrigCpuSet)) {
61 debugs(54, DBG_IMPORTANT, "ERROR: failed to restore original CPU "
62 "affinity for process PID " << getpid() << ": " <<
63 xstrerror());
64 }
65 CPU_ZERO(&theOrigCpuSet);
66 }
67 }
68
69 bool
70 CpuAffinitySet::applied() const
71 {
72 return (CPU_COUNT(&theOrigCpuSet) > 0);
73 }
74
75 void
76 CpuAffinitySet::set(const cpu_set_t &aCpuSet)
77 {
78 memcpy(&theCpuSet, &aCpuSet, sizeof(theCpuSet));
79 }