2013-08-07 11:51:55 +00:00
|
|
|
#include "types.hh"
|
|
|
|
#include "util.hh"
|
|
|
|
#include "affinity.hh"
|
|
|
|
|
2015-12-03 15:30:19 +00:00
|
|
|
#if __linux__
|
2013-08-07 11:51:55 +00:00
|
|
|
#include <sched.h>
|
|
|
|
#endif
|
|
|
|
|
|
|
|
namespace nix {
|
|
|
|
|
|
|
|
|
2015-12-03 15:30:19 +00:00
|
|
|
#if __linux__
|
2013-08-07 11:51:55 +00:00
|
|
|
static bool didSaveAffinity = false;
|
|
|
|
static cpu_set_t savedAffinity;
|
2013-08-07 15:26:41 +00:00
|
|
|
#endif
|
2013-08-07 11:51:55 +00:00
|
|
|
|
|
|
|
|
|
|
|
void setAffinityTo(int cpu)
|
|
|
|
{
|
2015-12-03 15:30:19 +00:00
|
|
|
#if __linux__
|
2013-08-07 11:51:55 +00:00
|
|
|
if (sched_getaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1) return;
|
|
|
|
didSaveAffinity = true;
|
2016-09-21 14:11:01 +00:00
|
|
|
debug(format("locking this thread to CPU %1%") % cpu);
|
2013-08-07 11:51:55 +00:00
|
|
|
cpu_set_t newAffinity;
|
|
|
|
CPU_ZERO(&newAffinity);
|
|
|
|
CPU_SET(cpu, &newAffinity);
|
|
|
|
if (sched_setaffinity(0, sizeof(cpu_set_t), &newAffinity) == -1)
|
2016-09-21 14:11:01 +00:00
|
|
|
printError(format("failed to lock thread to CPU %1%") % cpu);
|
2013-08-07 11:51:55 +00:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
int lockToCurrentCPU()
|
|
|
|
{
|
2015-12-03 15:30:19 +00:00
|
|
|
#if __linux__
|
2013-09-06 14:36:56 +00:00
|
|
|
int cpu = sched_getcpu();
|
|
|
|
if (cpu != -1) setAffinityTo(cpu);
|
|
|
|
return cpu;
|
|
|
|
#else
|
2013-08-07 11:51:55 +00:00
|
|
|
return -1;
|
2013-09-06 14:36:56 +00:00
|
|
|
#endif
|
2013-08-07 11:51:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void restoreAffinity()
|
|
|
|
{
|
2015-12-03 15:30:19 +00:00
|
|
|
#if __linux__
|
2013-08-07 11:51:55 +00:00
|
|
|
if (!didSaveAffinity) return;
|
|
|
|
if (sched_setaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1)
|
2016-09-21 14:11:01 +00:00
|
|
|
printError("failed to restore affinity %1%");
|
2013-08-07 11:51:55 +00:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|