/* * fh_cpu_getaffinity * * Return the CPU affinity of the running thread. */ FH_STATUS fh_cpu_getaffinity(uint32_t *cpu_mask) { cpu_set_t cpu_set; unsigned int len = sizeof(cpu_set_t); uint32_t i, mask = 0, pid; __CPU_ZERO(&cpu_set); pid = gettid(); if (num_cpus == 0) { num_cpus = fh_cpu_count(); } if (sched_getaffinity(pid, len, &cpu_set) < 0) { FH_LOG(CSI, ERR, ("sched_getaffinity failed: %s (%d)", strerror(errno), errno)); return FH_ERROR; } for (i=0; i<num_cpus; i++) { FH_LOG(CSI, INFO, (" %d: %s", i, __CPU_ISSET(i, &cpu_set) ? "set" : "noset")); if (__CPU_ISSET(i, &cpu_set)) { mask |= (1<<i); } } *cpu_mask = mask; return FH_OK; }
/* * fh_cpu_setaffinity * * Set CPU affinity for the running thread to the provided CPU mask. */ FH_STATUS fh_cpu_setaffinity(int cpu_mask) { cpu_set_t cpu_set; int i = 0, pid; pid = gettid(); __CPU_ZERO(&cpu_set); while (cpu_mask) { if (cpu_mask & 0x1) { FH_LOG(CSI, INFO, ("set affinity on cpu %d", i)); __CPU_SET(i, &cpu_set); } i++; cpu_mask >>= 1; } if (sched_setaffinity(pid, sizeof(cpu_set_t), &cpu_set)) { FH_LOG(CSI, WARN, ("sched_setaffinity failed: %s (%d)", strerror(errno), errno)); return FH_ERROR; } return FH_OK; }
JNIEXPORT jint JNICALL Java_com_ibm_tuningfork_tracegen_impl_OSBridge_setProcessorAffinityViaNative (JNIEnv *env, jclass ignore, jint cpu) { #ifdef LINUX cpu_set_t cpumask; __CPU_ZERO(&cpumask); __CPU_SET(cpu, &cpumask); int rc = sched_setaffinity(0, sizeof(cpumask), &cpumask); return rc; #else return -1; #endif }
static void INIT_FOR_DEBUG ( struct mon_t *mon ) { #ifdef ENABLE_AFFINITY #if 1 cpu_set_t mask; const unsigned long LEN = sizeof ( mask ); __CPU_ZERO ( &mask ); __CPU_SET ( ( mon->cpuid * 2 ), &mask ); /* bind individual virtual CPUs to different physical CPUs */ Sched_setaffinity ( 0, LEN, &mask ); Sched_setaffinity ( mon->pid, LEN, &mask ); #else int mask = 1; Sched_setaffinity ( mon->pid, LEN, &mask ); #endif #endif /* ENABLE_AFFINITY */ }
static void __binding_cpu(void) { int curr_cpu_max = __cpus_nums(); srand(time(NULL)); int num = rand() % curr_cpu_max; while(!num) { num = rand() % curr_cpu_max; } log_debug("CPU: %d\n", num); cpu_set_t mask; __CPU_ZERO(&mask); __CPU_SET(num, &mask); sched_setaffinity(0,sizeof(cpu_set_t),&mask); }