Debian Codegraph @

numad.c

raw symbols SCIP
1 /*
2
3 numad - NUMA Daemon to automatically bind processes to NUMA nodes
4 Copyright (C) 2012 Bill Gray ([email protected]), Red Hat Inc
5
6 numad is free software; you can redistribute it and/or modify it under the
7 terms of the GNU Lesser General Public License as published by the Free
8 Software Foundation; version 2.1.
9
10 numad is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
12 PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
13 details.
14
15 You should find a copy of v2.1 of the GNU Lesser General Public License
16 somewhere on your Linux system; if not, write to the Free Software Foundation,
17 Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19 */
20
21
22 // Compile with: gcc -std=gnu99 -g -Wall -pthread -o numad numad.c -lrt -lm
23
24
25 #define _GNU_SOURCE
26
27 #include <assert.h>
28 #include <ctype.h>
29 #include <dirent.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <getopt.h>
33 #include <limits.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sched.h>
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45 #include <values.h>
46
47 #include <sys/ipc.h>
48 #include <sys/mman.h>
49 #include <sys/msg.h>
50 #include <sys/sem.h>
51 #include <sys/shm.h>
52 #include <sys/stat.h>
53 #include <sys/syslog.h>
54 #include <sys/time.h>
55 #include <sys/types.h>
56
57 #include <asm/unistd.h>
58
59 #define VERSION_STRING "numad 20251104"
60
61 #define VAR_RUN_DIR_ADMIN "/var/run"
62 #define VAR_LOG_DIR_ADMIN "/var/log"
63 #define VAR_RUN_FILE "numad.pid"
64 #define VAR_LOG_FILE "numad.log"
65
66 #define KILOBYTE (1024)
67 #define MEGABYTE (1024 * 1024)
68
69 #define FNAME_SIZE 192
70 #define BUF_SIZE 1024
71 #define BIG_BUF_SIZE 4096
72
73 // The ONE_HUNDRED factor is used to scale time and CPU usage units.
74 // Several CPU quantities are measured in percents of a CPU; and
75 // several time values are counted in hundreths of a second.
76 #define ONE_HUNDRED 100
77
78
79 #define MIN_INTERVAL 5
80 #define MAX_INTERVAL 15
81 #define CPU_THRESHOLD 50
82 #define MEMORY_THRESHOLD 300
83 #define DEFAULT_HTT_PERCENT 20
84 #define DEFAULT_THP_SCAN_SLEEP_MS 1000
85 #define DEFAULT_UTILIZATION_PERCENT 90
86 #define DEFAULT_MEMLOCALITY_PERCENT 90
87 #define MIN_DELAY_FOR_REEVALUATION (300 * ONE_HUNDRED)
88
89 #define MIN(a, b) ((a) < (b) ? (a) : (b))
90
91 #define CONVERT_DIGITS_TO_NUM(p, n) \
92 n = *p++ - '0'; \
93 while (isdigit(*p)) { \
94 n *= 10; \
95 n += (*p++ - '0'); \
96 }
97
98 char var_run_file[BUFSIZ], var_log_file[BUFSIZ];
99 int num_cpus = 0;
100 int num_nodes = 0;
101 int threads_per_core = 0;
102 uint64_t page_size_in_bytes = 0;
103 uint64_t huge_page_size_in_bytes = 0;
104
105 int min_interval = MIN_INTERVAL;
106 int max_interval = MAX_INTERVAL;
107 int htt_percent = DEFAULT_HTT_PERCENT;
108 int thp_scan_sleep_ms = DEFAULT_THP_SCAN_SLEEP_MS;
109 int target_utilization = DEFAULT_UTILIZATION_PERCENT;
110 int target_memlocality = DEFAULT_MEMLOCALITY_PERCENT;
111 int scan_all_processes = 1;
112 int keep_interleaved_memory = 0;
113 int use_inactive_file_cache = 1;
114
115 pthread_mutex_t pid_list_mutex;
116 pthread_mutex_t node_info_mutex;
117 long sum_MBs_total = 0;
118 long sum_CPUs_total = 0;
119 int requested_mbs = 0;
120 int requested_cpus = 0;
121 int got_sighup = 0;
122 int got_sigterm = 0;
123 int got_sigquit = 0;
124
125 int get_daemon_pid(int inited);
126
127 void sig_handler(int signum) {
128 switch (signum) {
129 case SIGHUP: got_sighup = 1; break;
130 case SIGTERM: got_sigterm = 1; break;
131 case SIGQUIT: got_sigquit = 1; break;
132 }
133 }
134
135
136
137 FILE *log_fs = NULL;
138 int log_level = LOG_NOTICE;
139
140 void numad_log(int level, const char *fmt, ...) {
141 if (level > log_level) {
142 return;
143 // Logging levels (from sys/syslog.h)
144 // #define LOG_EMERG 0 /* system is unusable */
145 // #define LOG_ALERT 1 /* action must be taken immediately */
146 // #define LOG_CRIT 2 /* critical conditions */
147 // #define LOG_ERR 3 /* error conditions */
148 // #define LOG_WARNING 4 /* warning conditions */
149 // #define LOG_NOTICE 5 /* normal but significant condition */
150 // #define LOG_INFO 6 /* informational */
151 // #define LOG_DEBUG 7 /* debug-level messages */
152 }
153 char buf[BIG_BUF_SIZE];
154 time_t ts = time(NULL);
155 strncpy(buf, ctime(&ts), sizeof(buf));
156 char *p = &buf[strlen(buf) - 1];
157 *p++ = ':';
158 *p++ = ' ';
159 va_list ap;
160 va_start(ap, fmt);
161 vsnprintf(p, BIG_BUF_SIZE - strlen(buf) , fmt, ap);
162 va_end(ap);
163 fprintf(log_fs, "%s", buf);
164 fflush(log_fs);
165 }
166
167 void init_run_file() {
168 uid_t uid = getuid();
169 gid_t gid = getgid();
170 snprintf(var_run_file, BUFSIZ-1, "%s/%s", VAR_RUN_DIR_ADMIN, VAR_RUN_FILE);
171 snprintf(var_log_file, BUFSIZ-1, "%s/%s", VAR_LOG_DIR_ADMIN, VAR_LOG_FILE);
172 if (get_daemon_pid(0) == 0 && uid != 0 && gid != 0) {
173 //char *homedir = getenv("HOME");
174 //snprintf(var_run_file, BUFSIZ-1, "%s/%s", (homedir ? homedir : "/tmp"), VAR_RUN_FILE);
175 //snprintf(var_log_file, BUFSIZ-1, "%s/%s", (homedir ? homedir : "/tmp"), VAR_LOG_FILE);
176 snprintf(var_run_file, BUFSIZ-1, "%s/%s", "/tmp", VAR_RUN_FILE);
177 snprintf(var_log_file, BUFSIZ-1, "%s/%s", "/tmp", VAR_LOG_FILE);
178 }
179 }
180
181 void open_log_file() {
182 log_fs = fopen(var_log_file, "a");
183 if (log_fs == NULL) {
184 log_fs = stderr;
185 numad_log(LOG_ERR, "Cannot open numad log file (errno: %d) -- using stderr\n", errno);
186 } else {
187 fchmod(fileno(log_fs), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
188 }
189 }
190
191
192 void close_log_file() {
193 if (log_fs != NULL) {
194 if (log_fs != stderr) {
195 fclose(log_fs);
196 }
197 log_fs = NULL;
198 }
199 }
200
201
202
203 #define MSG_BODY_TEXT_SIZE 96
204
205 typedef struct msg_body {
206 long src_pid;
207 long cmd;
208 long arg1;
209 long arg2;
210 char text[MSG_BODY_TEXT_SIZE];
211 } msg_body_t, *msg_body_p;
212
213 typedef struct msg {
214 long dst_pid; // msg mtype is dest PID
215 msg_body_t body;
216 } msg_t, *msg_p;
217
218 int msg_qid;
219
220 void flush_msg_queue() {
221 msg_t msg;
222 do {
223 msgrcv(msg_qid, &msg, sizeof(msg_body_t), 0, IPC_NOWAIT);
224 } while (errno != ENOMSG);
225 }
226
227 void init_msg_queue() {
228 //key_t msg_key = 0xdeadbeef;
229 key_t msg_key = 0xaddaadda;
230 int msg_flg = 0660 | IPC_CREAT;
231 msg_qid = msgget(msg_key, msg_flg);
232 if (msg_qid < 0) {
233 numad_log(LOG_CRIT, "msgget failed (errno: %d)\n", errno);
234 exit(EXIT_FAILURE);
235 }
236 flush_msg_queue();
237 }
238
239 void recv_msg(msg_p m) {
240 if (msgrcv(msg_qid, m, sizeof(msg_body_t), getpid(), 0) < 0) {
241 numad_log(LOG_CRIT, "msgrcv failed\n");
242 exit(EXIT_FAILURE);
243 }
244 // printf("Received: >>%s<< from process %d\n", m->body.text, m->body.src_pid);
245 }
246
247 void send_msg(long dst_pid, long cmd, long arg1, long arg2, char *s) {
248 msg_t msg;
249 msg.dst_pid = dst_pid;
250 msg.body.src_pid = getpid();
251 msg.body.cmd = cmd;
252 msg.body.arg1 = arg1;
253 msg.body.arg2 = arg2;
254 int s_len = strlen(s);
255 if (s_len >= MSG_BODY_TEXT_SIZE) {
256 numad_log(LOG_CRIT, "msgsnd text too big\n");
257 exit(EXIT_FAILURE);
258 }
259 strcpy(msg.body.text, s);
260 size_t m_len = sizeof(msg_body_t) - MSG_BODY_TEXT_SIZE + s_len + 1;
261 if (msgsnd(msg_qid, &msg, m_len, IPC_NOWAIT) < 0) {
262 numad_log(LOG_CRIT, "msgsnd failed\n");
263 exit(EXIT_FAILURE);
264 }
265 // printf("Sent: >>%s<< to process %d\n", msg.body.text, msg.dst_pid);
266 }
267
268
269
270 typedef struct id_list {
271 // Use CPU_SET(3) <sched.h> bitmasks,
272 // but bundle size and pointer together
273 // and genericize for both CPU and Node IDs
274 cpu_set_t *set_p;
275 size_t bytes;
276 } id_list_t, *id_list_p;
277
278 #define ID_LIST_SET_P(list_p) (list_p->set_p)
279 #define ID_LIST_BYTES(list_p) (list_p->bytes)
280
281 #define INIT_ID_LIST(list_p, num_elements) \
282 list_p = malloc(sizeof(id_list_t)); \
283 if (list_p == NULL) { numad_log(LOG_CRIT, "INIT_ID_LIST malloc failed\n"); exit(EXIT_FAILURE); } \
284 list_p->set_p = CPU_ALLOC(num_elements); \
285 if (list_p->set_p == NULL) { numad_log(LOG_CRIT, "CPU_ALLOC failed\n"); exit(EXIT_FAILURE); } \
286 list_p->bytes = CPU_ALLOC_SIZE(num_elements);
287
288 #define CLEAR_CPU_LIST(list_p) \
289 if (list_p == NULL) { \
290 INIT_ID_LIST(list_p, num_cpus); \
291 } \
292 CPU_ZERO_S(list_p->bytes, list_p->set_p)
293
294 #define CLEAR_NODE_LIST(list_p) \
295 if (list_p == NULL) { \
296 INIT_ID_LIST(list_p, num_nodes); \
297 } \
298 CPU_ZERO_S(list_p->bytes, list_p->set_p)
299
300 #define FREE_LIST(list_p) \
301 if (list_p != NULL) { \
302 if (list_p->set_p != NULL) { CPU_FREE(list_p->set_p); } \
303 free(list_p); \
304 list_p = NULL; \
305 }
306
307 #define COPY_LIST(orig_list_p, copy_list_p) \
308 memcpy(copy_list_p->set_p, orig_list_p->set_p, orig_list_p->bytes)
309
310 #define NUM_IDS_IN_LIST(list_p) CPU_COUNT_S(list_p->bytes, list_p->set_p)
311 #define ADD_ID_TO_LIST(k, list_p) CPU_SET_S(k, list_p->bytes, list_p->set_p)
312 #define CLR_ID_IN_LIST(k, list_p) CPU_CLR_S(k, list_p->bytes, list_p->set_p)
313 #define ID_IS_IN_LIST(k, list_p) CPU_ISSET_S(k, list_p->bytes, list_p->set_p)
314
315 #define EQUAL_LISTS(list_1_p, list_2_p) CPU_EQUAL_S(list_1_p->bytes, list_1_p->set_p, list_2_p->set_p)
316 #define AND_LISTS(and_list_p, list_1_p, list_2_p) CPU_AND_S(and_list_p->bytes, and_list_p->set_p, list_1_p->set_p, list_2_p->set_p)
317 #define OR_LISTS( or_list_p, list_1_p, list_2_p) CPU_OR_S( or_list_p->bytes, or_list_p->set_p, list_1_p->set_p, list_2_p->set_p)
318 #define XOR_LISTS(xor_list_p, list_1_p, list_2_p) CPU_XOR_S(xor_list_p->bytes, xor_list_p->set_p, list_1_p->set_p, list_2_p->set_p)
319
320 int negate_cpu_list(id_list_p list_p) {
321 if (list_p == NULL) {
322 numad_log(LOG_CRIT, "Cannot negate a NULL list\n");
323 exit(EXIT_FAILURE);
324 }
325 if (num_cpus < 1) {
326 numad_log(LOG_CRIT, "No CPUs to negate in list!\n");
327 exit(EXIT_FAILURE);
328 }
329 for (int ix = 0; (ix < num_cpus); ix++) {
330 if (ID_IS_IN_LIST(ix, list_p)) {
331 CLR_ID_IN_LIST(ix, list_p);
332 } else {
333 ADD_ID_TO_LIST(ix, list_p);
334 }
335 }
336 return NUM_IDS_IN_LIST(list_p);
337 }
338
339 int add_ids_to_list_from_str(id_list_p list_p, char *s) {
340 if (list_p == NULL) {
341 numad_log(LOG_CRIT, "Cannot add to NULL list\n");
342 exit(EXIT_FAILURE);
343 }
344 if ((s == NULL) || (strlen(s) == 0)) {
345 goto return_list;
346 }
347 int in_range = 0;
348 int next_id = 0;
349 for (;;) {
350 // skip over non-digits
351 while (!isdigit(*s)) {
352 if ((*s == '\n') || (*s == '\0')) {
353 goto return_list;
354 }
355 if (*s++ == '-') {
356 in_range = 1;
357 }
358 }
359 int id;
360 CONVERT_DIGITS_TO_NUM(s, id);
361 if (!in_range) {
362 next_id = id;
363 }
364 for (; (next_id <= id); next_id++) {
365 ADD_ID_TO_LIST(next_id, list_p);
366 }
367 in_range = 0;
368 }
369 return_list:
370 return NUM_IDS_IN_LIST(list_p);
371 }
372
373 int str_from_id_list(char *str_p, int str_size, id_list_p list_p) {
374 char *p = str_p;
375 if ((p == NULL) || (str_size < 3)) {
376 numad_log(LOG_CRIT, "Bad string for ID listing\n");
377 exit(EXIT_FAILURE);
378 }
379 int n;
380 if ((list_p == NULL) || ((n = NUM_IDS_IN_LIST(list_p)) == 0)) {
381 goto terminate_string;
382 }
383 int id_range_start = -1;
384 for (int id = 0; ; id++) {
385 int id_in_list = (ID_IS_IN_LIST(id, list_p) != 0);
386 if ((id_in_list) && (id_range_start < 0)) {
387 id_range_start = id; // beginning an ID range
388 } else if ((!id_in_list) && (id_range_start >= 0)) {
389 // convert the range that just ended...
390 p += snprintf(p, (str_p + str_size - p - 1), "%d", id_range_start);
391 if (id - id_range_start > 1) {
392 *p++ = '-';
393 p += snprintf(p, (str_p + str_size - p - 1), "%d", (id - 1));
394 }
395 *p++ = ',';
396 id_range_start = -1; // no longer in a range
397 if (n <= 0) { break; } // exit only after finishing a range
398 }
399 n -= id_in_list;
400 }
401 p -= 1; // eliminate trailing ','
402 terminate_string:
403 *p = '\0';
404 return (p - str_p);
405 }
406
407
408 typedef struct node_data {
409 uint64_t node_id;
410 uint64_t MBs_total;
411 uint64_t MBs_free;
412 uint64_t active_threads;
413 uint64_t CPUs_total; // scaled * ONE_HUNDRED
414 uint64_t CPUs_free; // scaled * ONE_HUNDRED
415 uint64_t magnitude; // Free MBs * Free CPUs
416 uint8_t *distance;
417 id_list_p cpu_list_p;
418 } node_data_t, *node_data_p;
419 node_data_p node = NULL;
420
421
422 int min_node_CPUs_free_id = -1;
423 int min_node_MBs_free_id = -1;
424 long min_node_CPUs_free = MAXINT;
425 long min_node_MBs_free = MAXINT;
426 long max_node_CPUs_free = 0;
427 long max_node_MBs_free = 0;
428 long avg_node_CPUs_free = 0;
429 long avg_node_MBs_free = 0;
430 double stddev_node_CPUs_free = 0.0;
431 double stddev_node_MBs_free = 0.0;
432
433
434
435 // RING_BUF_SIZE must be a power of two
436 #define RING_BUF_SIZE 4
437
438 #define PROCESS_FLAG_INTERLEAVED (1 << 0)
439 #define PROCESS_FLAG_CHECK_THREADS (1 << 1)
440
441
442 typedef struct process_data {
443 int pid;
444 unsigned int flags;
445 uint64_t data_time_stamp; // hundredths of seconds
446 uint64_t bind_time_stamp;
447 uint64_t num_threads;
448 uint64_t num_active_threads;
449 uint64_t MBs_size;
450 uint64_t MBs_used;
451 uint64_t cpu_util;
452 uint64_t CPUs_used; // scaled * ONE_HUNDRED
453 uint64_t CPUs_used_ring_buf[RING_BUF_SIZE];
454 char *comm;
455 id_list_p node_list_p;
456 uint64_t *process_MBs;
457 int ring_buf_ix;
458 } process_data_t, *process_data_p;
459
460
461
462 // Hash table size must always be a power of two
463 #define MIN_PROCESS_HASH_TABLE_SIZE 32
464 int process_hash_table_size = 0;
465 int process_hash_collisions = 0;
466 process_data_p process_hash_table = NULL;
467
468 int process_hash_ix(int pid) {
469 unsigned ix = pid;
470 ix *= 717;
471 ix >>= 8;
472 ix &= (process_hash_table_size - 1);
473 return ix;
474 }
475
476 int process_hash_lookup(int pid) {
477 int ix = process_hash_ix(pid);
478 int starting_ix = ix;
479 while (process_hash_table[ix].pid) {
480 // Assumes table with some blank entries...
481 if (pid == process_hash_table[ix].pid) {
482 return ix; // found it
483 }
484 ix += 1;
485 ix &= (process_hash_table_size - 1);
486 if (ix == starting_ix) {
487 // Table full and pid not found.
488 // This "should never happen"...
489 break;
490 }
491 }
492 return -1;
493 }
494
495 int process_hash_insert(int pid) {
496 // This reserves the hash table slot, but initializes only the pid field
497 int ix = process_hash_ix(pid);
498 int starting_ix = ix;
499 while (process_hash_table[ix].pid) {
500 if (pid == process_hash_table[ix].pid) {
501 return ix; // found it
502 }
503 process_hash_collisions += 1;
504 ix += 1;
505 ix &= (process_hash_table_size - 1);
506 if (ix == starting_ix) {
507 // This "should never happen"...
508 numad_log(LOG_ERR, "Process hash table is full\n");
509 return -1;
510 }
511 }
512 process_hash_table[ix].pid = pid;
513 return ix;
514 }
515
516 int process_hash_update(process_data_p newp) {
517 // This updates hash table stats for processes we are monitoring. Only the
518 // scalar resource consumption stats need to be updated here.
519 int new_hash_table_entry = 1;
520 int ix = process_hash_insert(newp->pid);
521 if (ix >= 0) {
522 process_data_p p = &process_hash_table[ix];
523 if (p->data_time_stamp) {
524 new_hash_table_entry = 0;
525 p->ring_buf_ix += 1;
526 p->ring_buf_ix &= (RING_BUF_SIZE - 1);
527 uint64_t cpu_util_diff = newp->cpu_util - p->cpu_util;
528 uint64_t time_diff = newp->data_time_stamp - p->data_time_stamp;
529 if (time_diff == 0) {
530 numad_log(LOG_WARNING, "Forcing time_diff to be 1\n");
531 time_diff = 1;
532 }
533 p->CPUs_used_ring_buf[p->ring_buf_ix] = 100 * (cpu_util_diff) / time_diff;
534 // Use largest CPU utilization currently in ring buffer
535 uint64_t max_CPUs_used = p->CPUs_used_ring_buf[0];
536 for (int ix = 1; (ix < RING_BUF_SIZE); ix++) {
537 if (max_CPUs_used < p->CPUs_used_ring_buf[ix]) {
538 max_CPUs_used = p->CPUs_used_ring_buf[ix];
539 }
540 }
541 p->CPUs_used = max_CPUs_used;
542 }
543 if ((!p->comm) || (strcmp(p->comm, newp->comm))) {
544 if (p->comm) {
545 free(p->comm);
546 }
547 p->comm = strdup(newp->comm);
548 }
549 p->MBs_size = newp->MBs_size;
550 p->MBs_used = newp->MBs_used;
551 p->cpu_util = newp->cpu_util;
552 p->num_threads = newp->num_threads;
553 p->num_active_threads = newp->num_active_threads;
554 p->data_time_stamp = newp->data_time_stamp;
555 CLEAR_NODE_LIST(p->node_list_p);
556 COPY_LIST(newp->node_list_p, p->node_list_p);
557 }
558 return new_hash_table_entry;
559 }
560
561 void process_hash_clear_all_bind_time_stamps() {
562 for (int ix = 0; (ix < process_hash_table_size); ix++) {
563 process_hash_table[ix].bind_time_stamp = 0;
564 }
565 }
566
567 int process_hash_rehash(int old_ix) {
568 // Given the index of a table entry that would otherwise be orphaned by
569 // process_hash_remove(), reinsert into table using PID from existing record.
570 process_data_p op = &process_hash_table[old_ix];
571 int new_ix = process_hash_insert(op->pid);
572 if (new_ix >= 0) {
573 // Copy old slot to new slot, and zero old slot
574 process_data_p np = &process_hash_table[new_ix];
575 memcpy(np, op, sizeof(process_data_t));
576 memset(op, 0, sizeof(process_data_t));
577 }
578 return new_ix;
579 }
580
581 int process_hash_remove(int pid) {
582 int ix = process_hash_lookup(pid);
583 if (ix >= 0) {
584 // remove the target
585 process_data_p dp = &process_hash_table[ix];
586 if (dp->comm) { free(dp->comm); }
587 if (dp->process_MBs) { free(dp->process_MBs); }
588 FREE_LIST(dp->node_list_p);
589 memset(dp, 0, sizeof(process_data_t));
590 // bubble up the collision chain and rehash if neeeded
591 for (;;) {
592 ix += 1;
593 ix &= (process_hash_table_size - 1);
594 if ((pid = process_hash_table[ix].pid) <= 0) {
595 break;
596 }
597 if (process_hash_lookup(pid) < 0) {
598 if (process_hash_rehash(ix) < 0) {
599 numad_log(LOG_ERR, "rehash fail\n");
600 }
601 }
602 }
603 }
604 return ix;
605 }
606
607 void process_hash_table_expand() {
608 // Save old table size and address
609 int old_size = process_hash_table_size;
610 process_data_p old_table = process_hash_table;
611 // Double size of table and allocate new space
612 if (old_size > 0) {
613 process_hash_table_size *= 2;
614 } else {
615 process_hash_table_size = MIN_PROCESS_HASH_TABLE_SIZE;
616 }
617 numad_log(LOG_DEBUG, "Expanding hash table size: %d\n", process_hash_table_size);
618 process_hash_table = malloc(process_hash_table_size * sizeof(process_data_t));
619 if (process_hash_table == NULL) {
620 numad_log(LOG_CRIT, "hash table malloc failed\n");
621 exit(EXIT_FAILURE);
622 }
623 // Clear the new table, and copy valid entries from old table
624 memset(process_hash_table, 0, process_hash_table_size * sizeof(process_data_t));
625 for (int ix = 0; (ix < old_size); ix++) {
626 process_data_p p = &old_table[ix];
627 if (p->pid) {
628 int new_table_ix = process_hash_insert(p->pid);
629 memcpy(&process_hash_table[new_table_ix], p, sizeof(process_data_t));
630 }
631 }
632 if (old_table != NULL) {
633 free(old_table);
634 }
635 }
636
637
638 void process_hash_table_cleanup(uint64_t update_time) {
639 int num_hash_entries_used = 0;
640 for (int ix = 0; (ix < process_hash_table_size); ix++) {
641 process_data_p p = &process_hash_table[ix];
642 if (p->pid) {
643 num_hash_entries_used += 1;
644 if (p->data_time_stamp < update_time) {
645 // Mark as old, and zero CPU utilization
646 p->data_time_stamp = 0;
647 p->CPUs_used = 0;
648 // Check for dead pids and remove them...
649 if ((kill(p->pid, 0) == -1) && (errno == ESRCH)) {
650 // Seems dead. Forget this pid
651 process_hash_remove(p->pid);
652 num_hash_entries_used -= 1;
653 }
654 }
655 }
656 }
657 // Keep hash table approximately half empty
658 if ((num_hash_entries_used * 7) / 4 > process_hash_table_size) {
659 process_hash_table_expand();
660 }
661 }
662
663
664 void show_processes(int processes) {
665 fprintf(log_fs, "\n");
666 fprintf(log_fs, "Processes: looked at %d processes.\n", processes);
667 for (int ix = 0; (ix < process_hash_table_size); ix++) {
668 process_data_p p = &process_hash_table[ix];
669 if (p->pid) {
670 fprintf(log_fs,
671 "ix: %d PID: %d %s Threads: %ld/%ld CPU: %ld MBs: %ld/%ld DataTS: %ld BindTS: %ld ",
672 ix, p->pid, ((p->comm != NULL) ? p->comm : "(Null)"), p->num_active_threads, p->num_threads,
673 p->CPUs_used, p->MBs_used, p->MBs_size, p->data_time_stamp, p->bind_time_stamp);
674 char buf[BUF_SIZE];
675 str_from_id_list(buf, BUF_SIZE, p->node_list_p);
676 fprintf(log_fs, " Node(s) %s\n", buf);
677 fflush(log_fs);
678 }
679 }
680 }
681
682
683 typedef struct pid_list {
684 long pid;
685 struct pid_list* next;
686 } pid_list_t, *pid_list_p;
687
688 pid_list_p include_pid_list = NULL;
689 pid_list_p exclude_pid_list = NULL;
690
691 pid_list_p insert_pid_into_pid_list(pid_list_p list_ptr, long pid) {
692 if (process_hash_table != NULL) {
693 int hash_ix = process_hash_lookup(pid);
694 if ((hash_ix >= 0) && (list_ptr == include_pid_list)) {
695 // Clear interleaved flag, in case user wants it to be re-evaluated
696 process_hash_table[hash_ix].flags &= ~PROCESS_FLAG_INTERLEAVED;
697 }
698 }
699 // Check for duplicate pid first
700 pid_list_p pid_ptr = list_ptr;
701 while (pid_ptr != NULL) {
702 if (pid_ptr->pid == pid) {
703 // pid already in list
704 return list_ptr;
705 }
706 pid_ptr = pid_ptr->next;
707 }
708 // pid not yet in list -- insert new node
709 pid_ptr = malloc(sizeof(pid_list_t));
710 if (pid_ptr == NULL) {
711 numad_log(LOG_CRIT, "pid_list malloc failed\n");
712 exit(EXIT_FAILURE);
713 }
714 pid_ptr->pid = pid;
715 pid_ptr->next = list_ptr;
716 list_ptr = pid_ptr;
717 return list_ptr;
718 }
719
720 pid_list_p remove_pid_from_pid_list(pid_list_p list_ptr, long pid) {
721 pid_list_p last_pid_ptr = NULL;
722 pid_list_p pid_ptr = list_ptr;
723 while (pid_ptr != NULL) {
724 if (pid_ptr->pid == pid) {
725 if (pid_ptr == list_ptr) {
726 list_ptr = list_ptr->next;
727 free(pid_ptr);
728 pid_ptr = list_ptr;
729 continue;
730 } else {
731 last_pid_ptr->next = pid_ptr->next;
732 free(pid_ptr);
733 pid_ptr = last_pid_ptr;
734 }
735 }
736 last_pid_ptr = pid_ptr;
737 pid_ptr = pid_ptr->next;
738 }
739 return list_ptr;
740 }
741
742
743
744 void shut_down_numad() {
745 numad_log(LOG_NOTICE, "Shutting down numad\n");
746 flush_msg_queue();
747 unlink(var_run_file);
748 close_log_file();
749 exit(EXIT_SUCCESS);
750 }
751
752
753 void print_version_and_exit(char *prog_name) {
754 fprintf(stdout, "%s version: %s: compiled %s\n", prog_name, VERSION_STRING, __DATE__);
755 exit(EXIT_SUCCESS);
756 }
757
758
759 void print_usage_and_exit(char *prog_name) {
760 fprintf(stderr, "Usage: %s <options> ...\n", prog_name);
761 fprintf(stderr, "-C 1 to count inactive file cache as available memory (default 1)\n");
762 fprintf(stderr, "-C 0 to count inactive file cache memory as unavailable (default 1)\n");
763 fprintf(stderr, "-d for debug logging (same effect as '-l 7')\n");
764 fprintf(stderr, "-h to print this usage info\n");
765 fprintf(stderr, "-H <N> to set THP scan_sleep_ms (default %d)\n", DEFAULT_THP_SCAN_SLEEP_MS);
766 fprintf(stderr, "-i [<MIN>:]<MAX> to specify interval seconds\n");
767 fprintf(stderr, "-K 1 to keep interleaved memory spread across nodes (default 0)\n");
768 fprintf(stderr, "-K 0 to merge interleaved memory to local NUMA nodes (default 0)\n");
769 fprintf(stderr, "-l <N> to specify logging level (usually 5, 6, or 7 -- default 5)\n");
770 fprintf(stderr, "-m <N> to specify memory locality target percent (default %d)\n", DEFAULT_MEMLOCALITY_PERCENT);
771 fprintf(stderr, "-p <PID> to add PID to inclusion pid list\n");
772 fprintf(stderr, "-r <PID> to remove PID from explicit pid lists\n");
773 fprintf(stderr, "-R <CPU_LIST> to reserve some CPUs for non-numad use\n");
774 fprintf(stderr, "-S 1 to scan all processes (default 1)\n");
775 fprintf(stderr, "-S 0 to scan only explicit PID list processes (default 1)\n");
776 fprintf(stderr, "-t <N> to specify thread / logical CPU valuation percent (default %d)\n", DEFAULT_HTT_PERCENT);
777 fprintf(stderr, "-u <N> to specify utilization target percent (default %d)\n", DEFAULT_UTILIZATION_PERCENT);
778 fprintf(stderr, "-v for verbose (same effect as '-l 6')\n");
779 fprintf(stderr, "-V to show version info\n");
780 fprintf(stderr, "-w <CPUs>[:<MBs>] for NUMA node suggestions\n");
781 fprintf(stderr, "-x <PID> to add PID to exclusion pid list\n");
782 exit(EXIT_FAILURE);
783 }
784
785
786 void set_thp_scan_sleep_ms(int new_ms) {
787 if (new_ms < 1) {
788 // 0 means do not change the system default
789 return;
790 }
791 char *thp_scan_fname = "/sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs";
792 int fd = open(thp_scan_fname, O_RDWR, 0);
793 if (fd >= 0) {
794 char buf[BUF_SIZE];
795 int bytes = read(fd, buf, BUF_SIZE);
796 if (bytes > 0) {
797 buf[bytes] = '\0';
798 int cur_ms;
799 char *p = buf;
800 CONVERT_DIGITS_TO_NUM(p, cur_ms);
801 if (cur_ms != new_ms) {
802 lseek(fd, 0, SEEK_SET);
803 numad_log(LOG_NOTICE, "Changing THP scan time in %s from %d to %d ms.\n", thp_scan_fname, cur_ms, new_ms);
804 snprintf(buf, BUF_SIZE, "%d\n", new_ms);
805 write(fd, buf, strlen(buf));
806 }
807 }
808 close(fd);
809 }
810 }
811
812 void check_prereqs(char *prog_name) {
813 // Adjust kernel tunable to scan for THP more frequently...
814 set_thp_scan_sleep_ms(thp_scan_sleep_ms);
815 }
816
817
818 int get_daemon_pid(int inited) {
819 int fd = open(var_run_file, O_RDONLY, 0);
820 if (fd < 0) {
821 return 0;
822 }
823 char buf[BUF_SIZE];
824 int bytes = read(fd, buf, BUF_SIZE);
825 close(fd);
826 if (bytes <= 0) {
827 return 0;
828 }
829 int pid;
830 char *p = buf;
831 CONVERT_DIGITS_TO_NUM(p, pid);
832 // Check run file pid still active
833 char fname[FNAME_SIZE];
834 snprintf(fname, FNAME_SIZE, "/proc/%d", pid);
835 if (access(fname, F_OK) < 0) {
836 if (inited && errno == ENOENT) {
837 numad_log(LOG_NOTICE, "Removing out-of-date numad run file because %s doesn't exist\n", fname);
838 unlink(var_run_file);
839 }
840 return 0;
841 }
842 // Daemon must be running already.
843 return pid;
844 }
845
846 int register_numad_pid() {
847 int pid;
848 char buf[BUF_SIZE];
849 int fd;
850 create_run_file:
851 fd = open(var_run_file, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
852 if (fd >= 0) {
853 pid = getpid();
854 snprintf(buf, BUF_SIZE, "%d\n", pid);
855 write(fd, buf, strlen(buf));
856 close(fd);
857 numad_log(LOG_NOTICE, "Registering numad version %s PID %d\n", VERSION_STRING, pid);
858 return pid;
859 }
860 if (errno == EEXIST) {
861 fd = open(var_run_file, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
862 if (fd < 0) {
863 goto fail_numad_run_file;
864 }
865 int bytes = read(fd, buf, BUF_SIZE);
866 close(fd);
867 if (bytes > 0) {
868 char *p = buf;
869 CONVERT_DIGITS_TO_NUM(p, pid);
870 // Check pid in run file still active
871 char fname[FNAME_SIZE];
872 snprintf(fname, FNAME_SIZE, "/proc/%d", pid);
873 if (access(fname, F_OK) < 0) {
874 if (errno == ENOENT) {
875 // Assume run file is out-of-date...
876 numad_log(LOG_NOTICE, "Removing out-of-date numad run file because %s doesn't exist\n", fname);
877 unlink(var_run_file);
878 goto create_run_file;
879 }
880 }
881 // Daemon must be running already.
882 return pid;
883 }
884 }
885 fail_numad_run_file:
886 numad_log(LOG_CRIT, "Cannot open numad.pid file\n");
887 exit(EXIT_FAILURE);
888 }
889
890
891 int count_set_bits_in_hex_list_file(char *fname) {
892 int sum = 0;
893 int fd = open(fname, O_RDONLY, 0);
894 if (fd >= 0) {
895 char buf[BUF_SIZE];
896 int bytes = read(fd, buf, BUF_SIZE);
897 close(fd);
898 for (int ix = 0; (ix < bytes); ix++) {
899 char c = tolower(buf[ix]);
900 switch (c) {
901 case '0' : sum += 0; break;
902 case '1' : sum += 1; break;
903 case '2' : sum += 1; break;
904 case '3' : sum += 2; break;
905 case '4' : sum += 1; break;
906 case '5' : sum += 2; break;
907 case '6' : sum += 2; break;
908 case '7' : sum += 3; break;
909 case '8' : sum += 1; break;
910 case '9' : sum += 2; break;
911 case 'a' : sum += 2; break;
912 case 'b' : sum += 3; break;
913 case 'c' : sum += 2; break;
914 case 'd' : sum += 3; break;
915 case 'e' : sum += 3; break;
916 case 'f' : sum += 4; break;
917 case ' ' : sum += 0; break;
918 case ',' : sum += 0; break;
919 case '\n' : sum += 0; break;
920 default : numad_log(LOG_CRIT, "Unexpected character in list\n"); exit(EXIT_FAILURE);
921 }
922 }
923 }
924 return sum;
925 }
926
927
928 int get_num_cpus() {
929 int n1 = sysconf(_SC_NPROCESSORS_ONLN);
930 // int n2 = sysconf(_SC_NPROCESSORS_CONF);
931 // if (n1 < n2) {
932 // n1 = n2;
933 // }
934 if (n1 < 0) {
935 numad_log(LOG_CRIT, "Cannot count number of processors\n");
936 exit(EXIT_FAILURE);
937 }
938 return n1;
939 }
940
941
942 int get_num_kvm_vcpu_threads(int pid) {
943 // Try to return the number of vCPU threads for this VM guest,
944 // excluding the IO threads. All failures return MAXINT.
945 // FIXME: someday figure out some better way to do this...
946 char fname[FNAME_SIZE];
947 snprintf(fname, FNAME_SIZE, "/proc/%d/cmdline", pid);
948 int fd = open(fname, O_RDONLY, 0);
949 if (fd >= 0) {
950 char buf[BUF_SIZE];
951 int bytes = read(fd, buf, BUF_SIZE);
952 close(fd);
953 if (bytes > 0) {
954 char *p = memmem(buf, bytes, "smp", 3);
955 if (p != NULL) {
956 while (!isdigit(*p) && (p - buf < bytes - 2)) {
957 p++;
958 }
959 if (isdigit(*p)) {
960 int vcpu_threads;
961 CONVERT_DIGITS_TO_NUM(p, vcpu_threads);
962 if ((vcpu_threads > 0) && (vcpu_threads <= num_cpus)) {
963 return vcpu_threads;
964 }
965 }
966 }
967 }
968 }
969 return MAXINT;
970 }
971
972
973 uint64_t get_huge_page_size_in_bytes() {
974 uint64_t huge_page_size = 0;;
975 FILE *fs = fopen("/proc/meminfo", "r");
976 if (!fs) {
977 numad_log(LOG_CRIT, "Can't open /proc/meminfo\n");
978 exit(EXIT_FAILURE);
979 }
980 char buf[BUF_SIZE];
981 while (fgets(buf, BUF_SIZE, fs)) {
982 if (!strncmp("Hugepagesize", buf, 12)) {
983 char *p = &buf[12];
984 while ((!isdigit(*p)) && (p < buf + BUF_SIZE)) {
985 p++;
986 }
987 huge_page_size = atol(p);
988 break;
989 }
990 }
991 fclose(fs);
992 return huge_page_size * KILOBYTE;
993 }
994
995
996 uint64_t get_time_stamp() {
997 // Return time stamp in hundredths of a second
998 struct timespec ts;
999 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) {
1000 numad_log(LOG_CRIT, "Cannot get clock_gettime()\n");
1001 exit(EXIT_FAILURE);
1002 }
1003 return (ts.tv_sec * ONE_HUNDRED) +
1004 (ts.tv_nsec / (1000000000 / ONE_HUNDRED));
1005 }
1006
1007
1008 static int name_starts_with_digit(const struct dirent *dptr) {
1009 return (isdigit(dptr->d_name[0]));
1010 }
1011
1012
1013
1014 #define BITS_IN_LONG (CHAR_BIT * sizeof(unsigned long))
1015 #define SET_BIT(i,a) (a)[(i) / BITS_IN_LONG] |= (1u << ((i) % BITS_IN_LONG))
1016 #define TEST_BIT(i,a) (((a)[(i) / BITS_IN_LONG] & (1u << ((i) % BITS_IN_LONG))) != 0)
1017 #define CLEAR_BIT(i,a) (a)[(i) / BITS_IN_LONG] &= ~(1u << ((i) % BITS_IN_LONG))
1018
1019
1020 typedef struct cpu_data {
1021 uint64_t time_stamp;
1022 uint64_t *idle;
1023 } cpu_data_t, *cpu_data_p;
1024
1025 cpu_data_t cpu_data_buf[2]; // Two sets, to calc deltas
1026 int cur_cpu_data_buf = 0;
1027
1028 void update_cpu_data() {
1029 // Parse idle percents from CPU stats in /proc/stat cpu<N> lines
1030 static FILE *fs;
1031 if (fs != NULL) {
1032 rewind(fs);
1033 } else {
1034 fs = fopen("/proc/stat", "r");
1035 if (!fs) {
1036 numad_log(LOG_CRIT, "Cannot get /proc/stat contents\n");
1037 exit(EXIT_FAILURE);
1038 }
1039 cpu_data_buf[0].idle = malloc(num_cpus * sizeof(uint64_t));
1040 cpu_data_buf[1].idle = malloc(num_cpus * sizeof(uint64_t));
1041 if ((cpu_data_buf[0].idle == NULL) || (cpu_data_buf[1].idle == NULL)) {
1042 numad_log(LOG_CRIT, "cpu_data_buf malloc failed\n");
1043 exit(EXIT_FAILURE);
1044 }
1045 }
1046 // Use the other cpu_data buffer...
1047 int new = 1 - cur_cpu_data_buf;
1048 // First get the current time stamp
1049 cpu_data_buf[new].time_stamp = get_time_stamp();
1050 // Now pull the idle stat from each cpu<N> line
1051 char buf[BUF_SIZE];
1052 while (fgets(buf, BUF_SIZE, fs)) {
1053 /*
1054 * Lines are of the form:
1055 *
1056 * cpu<N> user nice system idle iowait irq softirq steal guest guest_nice
1057 *
1058 * # cat /proc/stat
1059 * cpu 11105906 0 78639 3359578423 24607 151679 322319 0 0 0
1060 * cpu0 190540 0 1071 52232942 39 7538 234039 0 0 0
1061 * cpu1 124519 0 50 52545188 0 1443 6267 0 0 0
1062 * cpu2 143133 0 452 52531440 36 1573 834 0 0 0
1063 * . . . .
1064 */
1065 if ( (buf[0] == 'c') && (buf[1] == 'p') && (buf[2] == 'u') && (isdigit(buf[3])) ) {
1066 char *p = &buf[3];
1067 int cpu_id = *p++ - '0'; while (isdigit(*p)) { cpu_id *= 10; cpu_id += (*p++ - '0'); }
1068 while (!isdigit(*p)) { p++; } while (isdigit(*p)) { p++; } // skip user
1069 while (!isdigit(*p)) { p++; } while (isdigit(*p)) { p++; } // skip nice
1070 while (!isdigit(*p)) { p++; } while (isdigit(*p)) { p++; } // skip system
1071 while (!isdigit(*p)) { p++; }
1072 uint64_t idle;
1073 CONVERT_DIGITS_TO_NUM(p, idle);
1074 cpu_data_buf[new].idle[cpu_id] = idle;
1075 }
1076 }
1077 cur_cpu_data_buf = new;
1078 }
1079
1080
1081 int node_and_digits(const struct dirent *dptr) {
1082 char *p = (char *)(dptr->d_name);
1083 if (*p++ != 'n') return 0;
1084 if (*p++ != 'o') return 0;
1085 if (*p++ != 'd') return 0;
1086 if (*p++ != 'e') return 0;
1087 do {
1088 if (!isdigit(*p++))
1089 return 0;
1090 } while (*p != '\0');
1091 return 1;
1092 }
1093
1094
1095 uint64_t node_info_time_stamp = 0;
1096 id_list_p all_cpus_list_p = NULL;
1097 id_list_p all_nodes_list_p = NULL;
1098 id_list_p reserved_cpu_mask_list_p = NULL;
1099 char *reserved_cpu_str = NULL;
1100
1101
1102 void show_nodes(int nodes) {
1103 assert(nodes == num_nodes);
1104 fprintf(log_fs, "\n");
1105 fprintf(log_fs, "Nodes: %d\n", num_nodes);
1106 for (int ix = 0; (ix < num_nodes); ix++) {
1107 fprintf(log_fs, "Node[%d] ID %ld, MBs_tot %ld, MBs_free %ld, CPUs_tot %ld, CPUs_free %ld, Dist ",
1108 ix, node[ix].node_id, node[ix].MBs_total, node[ix].MBs_free, node[ix].CPUs_total, node[ix].CPUs_free);
1109 for (int d = 0; (d < num_nodes); d++) {
1110 fprintf(log_fs, "%d ", node[ix].distance[d]);
1111 }
1112 char buf[BUF_SIZE];
1113 str_from_id_list(buf, BUF_SIZE, node[ix].cpu_list_p);
1114 fprintf(log_fs, " CPUs %s\n", buf);
1115 }
1116 fprintf(log_fs, "Min CPUs free: %ld, Max CPUs: %ld, Avg CPUs: %ld, StdDev: %.2lf\n",
1117 min_node_CPUs_free, max_node_CPUs_free, avg_node_CPUs_free, stddev_node_CPUs_free);
1118 fprintf(log_fs, "Min MBs free: %ld, Max MBs: %ld, Avg MBs: %ld, StdDev: %.2lf\n",
1119 min_node_MBs_free, max_node_MBs_free, avg_node_MBs_free, stddev_node_MBs_free);
1120 fflush(log_fs);
1121 }
1122
1123
1124 int update_nodes() {
1125 char fname[FNAME_SIZE];
1126 char buf[BIG_BUF_SIZE];
1127 // First, check to see if we should refresh basic node info that probably never changes...
1128 uint64_t time_stamp = get_time_stamp();
1129 #define STATIC_NODE_INFO_DELAY (600 * ONE_HUNDRED)
1130 if ((num_nodes == 0) || (node_info_time_stamp + STATIC_NODE_INFO_DELAY < time_stamp)) {
1131 node_info_time_stamp = time_stamp;
1132 // Count directory names of the form: /sys/devices/system/node/node<N>
1133 struct dirent **namelist;
1134 int num_files = scandir ("/sys/devices/system/node", &namelist, node_and_digits, versionsort);
1135 if (num_files < 1) {
1136 numad_log(LOG_CRIT, "Could not get NUMA node info\n");
1137 exit(EXIT_FAILURE);
1138 }
1139 int need_to_realloc = (num_files != num_nodes);
1140 if (need_to_realloc) {
1141 for (int ix = num_files; (ix < num_nodes); ix++) {
1142 // If new < old, free old node_data pointers
1143 free(node[ix].distance);
1144 FREE_LIST(node[ix].cpu_list_p);
1145 }
1146 node = realloc(node, (num_files * sizeof(node_data_t)));
1147 if (node == NULL) {
1148 numad_log(LOG_CRIT, "node realloc failed\n");
1149 exit(EXIT_FAILURE);
1150 }
1151 for (int ix = num_nodes; (ix < num_files); ix++) {
1152 // If new > old, nullify new node_data pointers
1153 node[ix].distance = NULL;
1154 node[ix].cpu_list_p = NULL;
1155 }
1156 num_nodes = num_files;
1157 }
1158 sum_MBs_total = 0;
1159 sum_CPUs_total = 0;
1160 CLEAR_CPU_LIST(all_cpus_list_p);
1161 CLEAR_NODE_LIST(all_nodes_list_p);
1162 // Figure out how many threads per core there are (for later discounting of hyper-threads)
1163 threads_per_core = count_set_bits_in_hex_list_file("/sys/devices/system/cpu/cpu0/topology/thread_siblings");
1164 if (threads_per_core < 1) {
1165 numad_log(LOG_CRIT, "Could not count threads per core\n");
1166 exit(EXIT_FAILURE);
1167 }
1168 // For each "node<N>" filename present, save <N> in node[ix].node_id
1169 // Note that the node id might not necessarily match the node ix.
1170 // Also populate the cpu lists and distance vectors for this node.
1171 for (int node_ix = 0; (node_ix < num_nodes); node_ix++) {
1172 char *p = &namelist[node_ix]->d_name[4];
1173 int node_id;
1174 CONVERT_DIGITS_TO_NUM(p, node_id);
1175 node[node_ix].node_id = node_id;
1176 free(namelist[node_ix]);
1177 ADD_ID_TO_LIST(node_id, all_nodes_list_p);
1178 // Get all the CPU IDs in this node... Read lines from node<N>/cpulist
1179 // file, and set the corresponding bits in the node cpu list.
1180 snprintf(fname, FNAME_SIZE, "/sys/devices/system/node/node%d/cpulist", node_id);
1181 int fd = open(fname, O_RDONLY, 0);
1182 if ((fd >= 0) && (read(fd, buf, BIG_BUF_SIZE) > 0)) {
1183 buf[BIG_BUF_SIZE - 1] = '\0';
1184 // get cpulist from the cpulist string
1185 CLEAR_CPU_LIST(node[node_ix].cpu_list_p);
1186 int n = add_ids_to_list_from_str(node[node_ix].cpu_list_p, buf);
1187 if (reserved_cpu_str != NULL) {
1188 AND_LISTS(node[node_ix].cpu_list_p, node[node_ix].cpu_list_p, reserved_cpu_mask_list_p);
1189 n = NUM_IDS_IN_LIST(node[node_ix].cpu_list_p);
1190 }
1191 OR_LISTS(all_cpus_list_p, all_cpus_list_p, node[node_ix].cpu_list_p);
1192 // Calculate total CPUs, but possibly discount hyper-threads
1193 if ((threads_per_core == 1) || (htt_percent >= 100)) {
1194 node[node_ix].CPUs_total = n * ONE_HUNDRED;
1195 } else {
1196 n /= threads_per_core;
1197 node[node_ix].CPUs_total = n * ONE_HUNDRED;
1198 node[node_ix].CPUs_total += n * (threads_per_core - 1) * htt_percent;
1199 }
1200 sum_MBs_total += node[node_ix].MBs_total;
1201 sum_CPUs_total += node[node_ix].CPUs_total;
1202 close(fd);
1203 } else {
1204 numad_log(LOG_CRIT, "Could not get node cpu list\n");
1205 exit(EXIT_FAILURE);
1206 }
1207 // Get distance vector of ACPI SLIT data from node<N>/distance file
1208 if (need_to_realloc) {
1209 node[node_ix].distance = realloc(node[node_ix].distance, (num_nodes * sizeof(uint8_t)));
1210 if (node[node_ix].distance == NULL) {
1211 numad_log(LOG_CRIT, "node distance realloc failed\n");
1212 exit(EXIT_FAILURE);
1213 }
1214 }
1215 snprintf(fname, FNAME_SIZE, "/sys/devices/system/node/node%d/distance", node_id);
1216 fd = open(fname, O_RDONLY, 0);
1217 if ((fd >= 0) && (read(fd, buf, BIG_BUF_SIZE) > 0)) {
1218 int rnode = 0;
1219 for (char *p = buf; (*p != '\n'); ) {
1220 int lat;
1221 CONVERT_DIGITS_TO_NUM(p, lat);
1222 node[node_ix].distance[rnode++] = lat;
1223 while (*p == ' ') { p++; }
1224 }
1225 close(fd);
1226 } else {
1227 numad_log(LOG_CRIT, "Could not get node distance data\n");
1228 exit(EXIT_FAILURE);
1229 }
1230 }
1231 free(namelist);
1232 }
1233 // Second, update the dynamic free memory and available CPU capacity
1234 while (cpu_data_buf[cur_cpu_data_buf].time_stamp + 7 >= time_stamp) {
1235 // Make sure at least 7/100 of a second has passed.
1236 // Otherwise sleep for 1/10 second.
1237 struct timespec ts = { 0, 100000000 };
1238 nanosleep(&ts, &ts);
1239 time_stamp = get_time_stamp();
1240 }
1241 update_cpu_data();
1242 max_node_MBs_free = 0;
1243 max_node_CPUs_free = 0;
1244 min_node_MBs_free = MAXINT;
1245 min_node_CPUs_free = MAXINT;
1246 uint64_t sum_of_node_MBs_free = 0;
1247 uint64_t sum_of_node_CPUs_free = 0;
1248 for (int node_ix = 0; (node_ix < num_nodes); node_ix++) {
1249 int node_id = node[node_ix].node_id;
1250 // Get available memory info from node<N>/meminfo file
1251 snprintf(fname, FNAME_SIZE, "/sys/devices/system/node/node%d/meminfo", node_id);
1252 int fd = open(fname, O_RDONLY, 0);
1253 if ((fd >= 0) && (read(fd, buf, BIG_BUF_SIZE) > 0)) {
1254 close(fd);
1255 uint64_t KB;
1256 buf[BIG_BUF_SIZE - 1] = '\0';
1257 char *p = strstr(buf, "MemTotal:");
1258 if (p != NULL) {
1259 p += 9;
1260 } else {
1261 numad_log(LOG_CRIT, "Could not get node MemTotal\n");
1262 exit(EXIT_FAILURE);
1263 }
1264 while (!isdigit(*p)) { p++; }
1265 CONVERT_DIGITS_TO_NUM(p, KB);
1266 node[node_ix].MBs_total = (KB / KILOBYTE);
1267 /*
1268 if (node[node_ix].MBs_total < 1) {
1269 // If a node has zero memory, remove it from the all_nodes_list...
1270 CLR_ID_IN_LIST(node_id, all_nodes_list_p);
1271 }
1272 */
1273 p = strstr(p, "MemFree:");
1274 if (p != NULL) {
1275 p += 8;
1276 } else {
1277 numad_log(LOG_CRIT, "Could not get node MemFree\n");
1278 exit(EXIT_FAILURE);
1279 }
1280 while (!isdigit(*p)) { p++; }
1281 CONVERT_DIGITS_TO_NUM(p, KB);
1282 node[node_ix].MBs_free = (KB / KILOBYTE);
1283 if (use_inactive_file_cache) {
1284 // Add inactive file cache quantity to "free" memory
1285 p = strstr(p, "Inactive(file):");
1286 if (p != NULL) {
1287 p += 15;
1288 } else {
1289 numad_log(LOG_CRIT, "Could not get node Inactive(file)\n");
1290 exit(EXIT_FAILURE);
1291 }
1292 while (!isdigit(*p)) { p++; }
1293 CONVERT_DIGITS_TO_NUM(p, KB);
1294 node[node_ix].MBs_free += (KB / KILOBYTE);
1295 }
1296 sum_of_node_MBs_free += node[node_ix].MBs_free;
1297 if (min_node_MBs_free > node[node_ix].MBs_free) {
1298 min_node_MBs_free = node[node_ix].MBs_free;
1299 min_node_MBs_free_id = node[node_ix].node_id;
1300 }
1301 if (max_node_MBs_free < node[node_ix].MBs_free) {
1302 max_node_MBs_free = node[node_ix].MBs_free;
1303 }
1304 } else {
1305 numad_log(LOG_CRIT, "Could not get node meminfo\n");
1306 exit(EXIT_FAILURE);
1307 }
1308 // If both buffers have been populated by now, sum CPU idle data
1309 // for each node in order to calculate available capacity
1310 int old_cpu_data_buf = 1 - cur_cpu_data_buf;
1311 if (cpu_data_buf[old_cpu_data_buf].time_stamp > 0) {
1312 uint64_t idle_ticks = 0;
1313 int cpu = 0;
1314 int num_lcpus = NUM_IDS_IN_LIST(node[node_ix].cpu_list_p);
1315 int num_cpus_to_process = num_lcpus;
1316 while (num_cpus_to_process) {
1317 if (ID_IS_IN_LIST(cpu, node[node_ix].cpu_list_p)) {
1318 idle_ticks += cpu_data_buf[cur_cpu_data_buf].idle[cpu]
1319 - cpu_data_buf[old_cpu_data_buf].idle[cpu];
1320 num_cpus_to_process -= 1;
1321 }
1322 cpu += 1;
1323 }
1324 uint64_t time_diff = cpu_data_buf[cur_cpu_data_buf].time_stamp
1325 - cpu_data_buf[old_cpu_data_buf].time_stamp;
1326 // printf("Node: %d CPUs: %ld time diff %ld Idle ticks %ld\n", node_id, node[node_ix].CPUs_total, time_diff, idle_ticks);
1327 if (time_diff == 0) {
1328 numad_log(LOG_WARNING, "Forcing time_diff to be 1\n");
1329 time_diff = 1;
1330 }
1331 node[node_ix].CPUs_free = (idle_ticks * ONE_HUNDRED) / time_diff;
1332 // Possibly discount hyper-threads
1333 if ((threads_per_core > 1) && (htt_percent < 100)) {
1334 uint64_t htt_discount = (num_lcpus - (num_lcpus / threads_per_core)) * (100 - htt_percent);
1335 if (node[node_ix].CPUs_free > htt_discount) {
1336 node[node_ix].CPUs_free -= htt_discount;
1337 } else {
1338 node[node_ix].CPUs_free = 0;
1339 }
1340 }
1341 if (node[node_ix].CPUs_free > node[node_ix].CPUs_total) {
1342 node[node_ix].CPUs_free = node[node_ix].CPUs_total;
1343 }
1344 sum_of_node_CPUs_free += node[node_ix].CPUs_free;
1345 if (min_node_CPUs_free > node[node_ix].CPUs_free) {
1346 min_node_CPUs_free = node[node_ix].CPUs_free;
1347 min_node_CPUs_free_id = node[node_ix].node_id;
1348 }
1349 if (max_node_CPUs_free < node[node_ix].CPUs_free) {
1350 max_node_CPUs_free = node[node_ix].CPUs_free;
1351 }
1352 node[node_ix].magnitude = node[node_ix].CPUs_free * node[node_ix].MBs_free;
1353 } else {
1354 node[node_ix].CPUs_free = 0;
1355 node[node_ix].magnitude = 0;
1356 }
1357 }
1358 avg_node_MBs_free = sum_of_node_MBs_free / num_nodes;
1359 avg_node_CPUs_free = sum_of_node_CPUs_free / num_nodes;
1360 double MBs_variance_sum = 0.0;
1361 double CPUs_variance_sum = 0.0;
1362 for (int node_ix = 0; (node_ix < num_nodes); node_ix++) {
1363 double MBs_diff = (double)node[node_ix].MBs_free - (double)avg_node_MBs_free;
1364 double CPUs_diff = (double)node[node_ix].CPUs_free - (double)avg_node_CPUs_free;
1365 MBs_variance_sum += MBs_diff * MBs_diff;
1366 CPUs_variance_sum += CPUs_diff * CPUs_diff;
1367 }
1368 double MBs_variance = MBs_variance_sum / (num_nodes);
1369 double CPUs_variance = CPUs_variance_sum / (num_nodes);
1370 stddev_node_MBs_free = sqrt(MBs_variance);
1371 stddev_node_CPUs_free = sqrt(CPUs_variance);
1372 return num_nodes;
1373 }
1374
1375
1376 int all_digits(const struct dirent *dptr) {
1377 char *p = (char *)(dptr->d_name);
1378 if (p == NULL) {
1379 return 0;
1380 }
1381 while (*p != '\0') {
1382 if (!isdigit(*p++)) return 0;
1383 }
1384 return 1;
1385 }
1386
1387
1388 typedef struct stat_data {
1389 // This structure isn't actually used in numad -- it is here just to
1390 // document the field type and order of the /proc/<PID>/stat items, some of
1391 // which are used in the process_data_t structure.
1392 int pid; // 0
1393 char *comm; // 1
1394 char state; // 2
1395 int ppid;
1396 int pgrp;
1397 int session;
1398 int tty_nr;
1399 int tpgid;
1400 unsigned flags;
1401 #define PF_VCPU 0x00000001 /* I'm a virtual CPU */
1402 #define PF_IDLE 0x00000002 /* I am an IDLE thread */
1403 #define PF_EXITING 0x00000004 /* Getting shut down */
1404 #define PF_POSTCOREDUMP 0x00000008 /* Coredumps should ignore this task */
1405 #define PF_IO_WORKER 0x00000010 /* Task is an IO worker */
1406 #define PF_WQ_WORKER 0x00000020 /* I'm a workqueue worker */
1407 #define PF_FORKNOEXEC 0x00000040 /* Forked but didn't exec */
1408 #define PF_MCE_PROCESS 0x00000080 /* Process policy on mce errors */
1409 #define PF_SUPERPRIV 0x00000100 /* Used super-user privileges */
1410 uint64_t minflt;
1411 uint64_t cminflt;
1412 uint64_t majflt;
1413 uint64_t cmajflt;
1414 uint64_t utime; // 13
1415 uint64_t stime; // 14
1416 int64_t cutime;
1417 int64_t cstime;
1418 int64_t priority; // 17
1419 int64_t nice;
1420 int64_t num_threads; // 19
1421 int64_t itrealvalue;
1422 uint64_t starttime;
1423 uint64_t vsize; // 22
1424 int64_t rss; // 23
1425 uint64_t rsslim;
1426 uint64_t startcode;
1427 uint64_t endcode;
1428 uint64_t startstack;
1429 uint64_t kstkesp;
1430 uint64_t kstkeip;
1431 uint64_t signal;
1432 uint64_t blocked;
1433 uint64_t sigignore;
1434 uint64_t sigcatch;
1435 uint64_t wchan;
1436 uint64_t nswap;
1437 uint64_t cnswap;
1438 int exit_signal;
1439 int processor; // 38
1440 unsigned rt_priority;
1441 unsigned policy; // 40
1442 uint64_t delayacct_blkio_ticks;
1443 uint64_t guest_time; // 42
1444 int64_t cguest_time;
1445 uint64_t start_data;
1446 uint64_t end_data;
1447 uint64_t start_brk;
1448 uint64_t arg_start;
1449 uint64_t arg_end;
1450 uint64_t env_start;
1451 uint64_t env_end;
1452 int exit_code;
1453 } stat_data_t, *stat_data_p;
1454
1455
1456 process_data_p get_stat_data_for_pid(int pid) {
1457 // Note: This function uses static data buffers and is not thread safe.
1458 char fname[FNAME_SIZE];
1459 snprintf(fname, FNAME_SIZE, "/proc/%d/stat", pid);
1460 int fd = open(fname, O_RDONLY, 0);
1461 if (fd < 0) {
1462 numad_log(LOG_WARNING, "Could not open stat file: %s\n", fname);
1463 return NULL;
1464 }
1465 static char buf[BUF_SIZE];
1466 int bytes = read(fd, buf, BUF_SIZE);
1467 close(fd);
1468 if (bytes < 50) {
1469 numad_log(LOG_WARNING, "Could not read stat file: %s\n", fname);
1470 return NULL;
1471 }
1472 uint64_t val;
1473 char *p = buf;
1474 static process_data_t data;
1475 // Get PID from field 0
1476 CONVERT_DIGITS_TO_NUM(p, val);
1477 data.pid = val;
1478 // Alias comm from field 1 -- buf must be preserved
1479 while (*p == ' ') { p++; }
1480 data.comm = p; while (*p != ' ') { p++; }
1481 *p++ = '\0'; // replacing the presumed single ' ' before next field
1482 // Skip fields 2 through 12
1483 for (int ix = 0; (ix < 11); ix++) { while (*p != ' ') { p++; } while (*p == ' ') { p++; } }
1484 // Get utime from field 13 for cpu_util
1485 CONVERT_DIGITS_TO_NUM(p, val);
1486 data.cpu_util = val;
1487 // Get stime from field 14 to add on to cpu_util (which already has utime)
1488 while (*p == ' ') { p++; }
1489 CONVERT_DIGITS_TO_NUM(p, val);
1490 data.cpu_util += val;
1491 // Skip fields 15 through 18
1492 while (*p == ' ') { p++; }
1493 for (int ix = 0; (ix < 4); ix++) { while (*p != ' ') { p++; } while (*p == ' ') { p++; } }
1494 // Get num_threads from field 19
1495 CONVERT_DIGITS_TO_NUM(p, val);
1496 data.num_threads = val;
1497 // Skip fields 20 through 21
1498 while (*p == ' ') { p++; }
1499 for (int ix = 0; (ix < 2); ix++) { while (*p != ' ') { p++; } while (*p == ' ') { p++; } }
1500 // Get vsize from field 22 to compute MBs_size
1501 CONVERT_DIGITS_TO_NUM(p, val);
1502 data.MBs_size = val / MEGABYTE;
1503 // Get rss from field 23 to compute MBs_used
1504 while (*p == ' ') { p++; }
1505 CONVERT_DIGITS_TO_NUM(p, val);
1506 data.MBs_used = (val * page_size_in_bytes) / MEGABYTE;
1507 // Get num_active_threads
1508 static char bigbuf[BIG_BUF_SIZE];
1509 if (data.num_threads == 1) {
1510 data.num_active_threads = 1;
1511 } else {
1512 data.num_active_threads = 0;
1513 struct dirent **namelist;
1514 snprintf(fname, FNAME_SIZE, "/proc/%d/task", pid);
1515 int tasks = scandir(fname, &namelist, all_digits, NULL);
1516 if (tasks < 1) {
1517 perror("Couldn't open /proc/PID/task");
1518 exit(EXIT_FAILURE);
1519 } else {
1520 for (int ix = 0; (ix < tasks); ix++) {
1521 snprintf(bigbuf, BIG_BUF_SIZE, "%s/%s/stat", fname, namelist[ix]->d_name);
1522 free(namelist[ix]);
1523 fd = open(bigbuf, O_RDONLY, 0);
1524 if (fd < 0) {
1525 numad_log(LOG_WARNING, "Could not open /proc/PID/task/TID/stat: %s\n", fname);
1526 continue;
1527 }
1528 bytes = read(fd, bigbuf, BIG_BUF_SIZE);
1529 close(fd);
1530 if (bytes < 50) {
1531 numad_log(LOG_WARNING, "Could not read /proc/PID/task/TID/stat: %s\n", fname);
1532 continue;
1533 }
1534 p = bigbuf;
1535 // Skip the first two fields: TID comm
1536 for (int ij = 0; (ij < 2); ij++) { while (*p != ' ') { p++; } while (*p == ' ') { p++; } }
1537 data.num_active_threads += (*p == 'R');
1538 }
1539 // printf("pid %d threads %ld active %ld\n", pid, data.num_threads, data.num_active_threads);
1540 }
1541 free(namelist);
1542 }
1543 static uint16_t *cpu_to_node;
1544 if (cpu_to_node == NULL) {
1545 cpu_to_node = realloc(cpu_to_node, (num_cpus * sizeof(uint16_t)));
1546 if (cpu_to_node == NULL) {
1547 numad_log(LOG_CRIT, "cpu_to_node realloc failed\n");
1548 exit(EXIT_FAILURE);
1549 }
1550 for (int ix = 0; (ix < num_cpus); ix++) {
1551 for (int ij = 0; (ij < num_nodes); ij++) {
1552 if (ID_IS_IN_LIST(ix, node[ij].cpu_list_p)) {
1553 cpu_to_node[ix] = node[ij].node_id;
1554 break;
1555 }
1556 }
1557 }
1558 }
1559 static id_list_p tmp_cpu_list_p;
1560 CLEAR_CPU_LIST(tmp_cpu_list_p);
1561 snprintf(fname, FNAME_SIZE, "/proc/%d/status", pid);
1562 fd = open(fname, O_RDONLY, 0);
1563 if (fd < 0) {
1564 numad_log(LOG_WARNING, "Could not open %s\n", fname);
1565 goto return_pointer_to_data;
1566 }
1567 bytes = read(fd, bigbuf, BIG_BUF_SIZE);
1568 close(fd);
1569 if (bytes <= 0) {
1570 numad_log(LOG_WARNING, "Could not read status file %s.\n", fname);
1571 goto return_pointer_to_data;
1572 } else if (bytes >= BIG_BUF_SIZE) {
1573 bigbuf[BIG_BUF_SIZE - 1] = '\0';
1574 } else {
1575 bigbuf[bytes] = '\0';
1576 }
1577 p = strstr(bigbuf, "Cpus_allowed_list:");
1578 if (!p) {
1579 numad_log(LOG_WARNING, "Could not get node Cpus_allowed_list\n");
1580 goto return_pointer_to_data;
1581 }
1582 p += 18;
1583 while (!isdigit(*p)) { p++; }
1584 val = add_ids_to_list_from_str(tmp_cpu_list_p, p);
1585 CLEAR_NODE_LIST(data.node_list_p);
1586 for (int ix = 0; (ix < num_cpus); ix++) {
1587 if (ID_IS_IN_LIST(ix, tmp_cpu_list_p)) {
1588 ADD_ID_TO_LIST(cpu_to_node[ix], data.node_list_p);
1589 }
1590 }
1591 return_pointer_to_data:
1592 return &data;
1593 }
1594
1595
1596 int update_processes() {
1597 // Conditionally scan /proc/<PID>/stat files for processes we should
1598 // perhaps manage. For all processes, evaluate whether or not they should
1599 // be added to our hash table of managed processes candidates. If so,
1600 // update the statistics, time stamp and utilization numbers for the select
1601 // processes in the hash table.
1602 uint64_t this_update_time = get_time_stamp();
1603 int new_candidates = 0; // limit number of new candidates per update
1604 int files = 0;
1605 if (scan_all_processes) {
1606 struct dirent **namelist;
1607 files = scandir("/proc", &namelist, name_starts_with_digit, NULL);
1608 if (files < 0) {
1609 numad_log(LOG_CRIT, "Could not open /proc\n");
1610 exit(EXIT_FAILURE);
1611 }
1612 for (int ix = 0; (ix < files); ix++) {
1613 process_data_p data_p;
1614 int pid = atoi(namelist[ix]->d_name);
1615 if ((data_p = get_stat_data_for_pid(pid)) != NULL) {
1616 // See if this process uses enough memory to be managed.
1617 // Cannot check CPUs_used here because that is not calculated yet
1618 if ( (data_p->MBs_used > MEMORY_THRESHOLD)
1619 && (new_candidates < process_hash_table_size / 3) ) {
1620 data_p->data_time_stamp = get_time_stamp();
1621 new_candidates += process_hash_update(data_p);
1622 }
1623 }
1624 free(namelist[ix]);
1625 }
1626 free(namelist);
1627 } // scan_all_processes
1628 // Process explicit inclusion and exclusion pid lists
1629 pthread_mutex_lock(&pid_list_mutex);
1630 // Include candidate processes from the explicit include pid list
1631 pid_list_p pid_ptr = include_pid_list;
1632 while ((pid_ptr != NULL) && (new_candidates < process_hash_table_size / 3)) {
1633 int hash_ix = process_hash_lookup(pid_ptr->pid);
1634 if ( (hash_ix >= 0) && (process_hash_table[hash_ix].data_time_stamp > this_update_time)) {
1635 // Already in hash table, and recently updated...
1636 pid_ptr = pid_ptr->next;
1637 continue;
1638 }
1639 process_data_p data_p;
1640 if ((data_p = get_stat_data_for_pid(pid_ptr->pid)) != NULL) {
1641 data_p->data_time_stamp = get_time_stamp();
1642 new_candidates += process_hash_update(data_p);
1643 if (!scan_all_processes) {
1644 files += 1;
1645 }
1646 pid_ptr = pid_ptr->next;
1647 } else {
1648 // no stat file so assume pid dead -- remove it from pid list
1649 include_pid_list = remove_pid_from_pid_list(include_pid_list, pid_ptr->pid);
1650 pid_ptr = include_pid_list; // just restart from list beginning
1651 continue;
1652 }
1653 }
1654 // Zero CPU utilization for processes on the explicit exclude pid list
1655 pid_ptr = exclude_pid_list;
1656 while (pid_ptr != NULL) {
1657 int hash_ix = process_hash_lookup(pid_ptr->pid);
1658 if (hash_ix >= 0) {
1659 process_hash_table[hash_ix].CPUs_used = 0;
1660 }
1661 pid_ptr = pid_ptr->next;
1662 }
1663 pthread_mutex_unlock(&pid_list_mutex);
1664 // Now go through all managed processes to cleanup out-of-date and dead ones.
1665 process_hash_table_cleanup(this_update_time);
1666 return files;
1667 }
1668
1669
1670 /*
1671 static int cmp_ints_by_ref(const void *p1, const void *p2) {
1672 if (*(int *)p1 < *(int *)p2) {
1673 return 1;
1674 } else if (*(int *)p1 > *(int *)p2) {
1675 return -1;
1676 } else {
1677 return 0;
1678 }
1679 }
1680 */
1681
1682
1683 int bind_process_and_maybe_migrate_memory(process_data_p p, int migrate_memory) {
1684 uint64_t t0 = get_time_stamp();
1685 // Parameter p is a pointer to an element in the hash table
1686 if ((!p) || (p->pid < 1)) {
1687 numad_log(LOG_CRIT, "Bad PID to bind\n");
1688 exit(EXIT_FAILURE);
1689 }
1690 if ((!p->node_list_p) || (NUM_IDS_IN_LIST(p->node_list_p) == 0))
1691 {
1692 numad_log(LOG_CRIT, "Cannot bind to unspecified node(s)\n");
1693 exit(EXIT_FAILURE);
1694 }
1695 // Generate CPU list derived from target node list.
1696 static id_list_p cpu_bind_list_p;
1697 CLEAR_CPU_LIST(cpu_bind_list_p);
1698 for (int node_ix =0; (node_ix < num_nodes); node_ix++) {
1699 if (ID_IS_IN_LIST(node_ix, p->node_list_p)) {
1700 OR_LISTS(cpu_bind_list_p, cpu_bind_list_p, node[node_ix].cpu_list_p);
1701 }
1702 }
1703 char fname[FNAME_SIZE];
1704 struct dirent **namelist;
1705 snprintf(fname, FNAME_SIZE, "/proc/%d/task", p->pid);
1706 int num_tasks = scandir(fname, &namelist, name_starts_with_digit, NULL);
1707 if (num_tasks <= 0) {
1708 numad_log(LOG_WARNING, "Could not scandir task list for PID: %d\n", p->pid);
1709 return 0; // Assume the process terminated
1710 }
1711 // Set the affinity of each task in the process...
1712 for (int namelist_ix = 0; (namelist_ix < num_tasks); namelist_ix++) {
1713 int tid = atoi(namelist[namelist_ix]->d_name);
1714 int rc = sched_setaffinity(tid, ID_LIST_BYTES(cpu_bind_list_p), ID_LIST_SET_P(cpu_bind_list_p));
1715 if (rc < 0) {
1716 if (errno == ESRCH) {
1717 numad_log(LOG_WARNING, "Tried to bind PID %d, TID %d, but it apparently went away.\n", p->pid, tid);
1718 }
1719 numad_log(LOG_ERR, "Bad sched_setaffinity() on PID %d, TID %d -- errno: %d\n", p->pid, tid, errno);
1720 }
1721 free(namelist[namelist_ix]);
1722 }
1723 free(namelist);
1724 if (migrate_memory) {
1725 // Now move the memory to the target nodes....
1726 static unsigned long *dest_mask;
1727 static unsigned long *from_mask;
1728 static int allocated_bytes_in_masks;
1729 // Lie about num_nodes being one bigger because of kernel bug...
1730 int num_bytes_in_masks = (1 + ((num_nodes + 1) / BITS_IN_LONG)) * sizeof(unsigned long);
1731 if (allocated_bytes_in_masks < num_bytes_in_masks) {
1732 allocated_bytes_in_masks = num_bytes_in_masks;
1733 dest_mask = realloc(dest_mask, num_bytes_in_masks);
1734 from_mask = realloc(from_mask, num_bytes_in_masks);
1735 if ((dest_mask == NULL) || (from_mask == NULL)) {
1736 numad_log(LOG_CRIT, "bit mask malloc failed\n");
1737 exit(EXIT_FAILURE);
1738 }
1739 }
1740 // In an effort to put semi-balanced memory in each target node, move the
1741 // contents from the source node with the max amount of memory to the
1742 // destination node with the least amount of memory. Repeat until done.
1743 int prev_from_node_id = -1;
1744 for (;;) {
1745 int min_dest_node_id = -1;
1746 int max_from_node_id = -1;
1747 for (int node_ix = 0; (node_ix < num_nodes); node_ix++) {
1748 int node_id = node[node_ix].node_id;
1749 if (ID_IS_IN_LIST(node_id, p->node_list_p)) {
1750 if ((min_dest_node_id < 0) || (p->process_MBs[min_dest_node_id] >= p->process_MBs[node_id])) {
1751 // The ">=" above is intentional, so we tend to move memory to higher numbered nodes
1752 min_dest_node_id = node_id;
1753 }
1754 } else {
1755 if ((max_from_node_id < 0) || (p->process_MBs[max_from_node_id] < p->process_MBs[node_id])) {
1756 max_from_node_id = node_id;
1757 }
1758 }
1759 }
1760 if ((p->process_MBs[max_from_node_id] == 0) || (max_from_node_id == prev_from_node_id)) {
1761 break;
1762 }
1763 memset(dest_mask, 0, num_bytes_in_masks);
1764 memset(from_mask, 0, num_bytes_in_masks);
1765 SET_BIT(max_from_node_id, from_mask);
1766 SET_BIT(min_dest_node_id, dest_mask);
1767 #if defined(__NR_migrate_pages)
1768 numad_log(LOG_DEBUG, "Moving memory from node: %d to node %d\n", max_from_node_id, min_dest_node_id);
1769 // Lie about num_nodes being one bigger because of kernel bug...
1770 int rc = syscall(__NR_migrate_pages, p->pid, num_nodes + 1, from_mask, dest_mask);
1771 numad_log(LOG_DEBUG, "Syscall migrate pages on PID %d, return code %d \n", p->pid, rc);
1772 if (rc > 2) {
1773 // rc == the number of pages that could not be moved.
1774 // A couple pages not moving is probably not a problem, hence ignoring rc == 1 or 2.
1775 numad_log(LOG_WARNING, "Tried to move PID %d, but %d pages would not move.\n", p->pid, rc);
1776 } else if (rc < 0) {
1777 // Check errno
1778 if (errno == ESRCH) {
1779 numad_log(LOG_WARNING, "Tried to move PID %d, but it apparently went away.\n", p->pid);
1780 return 0; // Assume the process terminated
1781 }
1782 if (errno == EFAULT) {
1783 numad_log(LOG_WARNING, "Tried to move PID %d, but some memory was out of range.\n", p->pid);
1784 return 0; // Assume the process terminated
1785 }
1786 if (errno == EINVAL) {
1787 numad_log(LOG_WARNING, "Tried to move PID %d, but there are bad parameters.\n", p->pid);
1788 return 0; // Assume the process terminated
1789 }
1790 if (errno == EPERM) {
1791 numad_log(LOG_WARNING, "Tried to move PID %d, but there is insufficient privilege.\n", p->pid);
1792 return 0; // Assume the process terminated
1793 }
1794 }
1795 #else
1796 numad_log(LOG_WARNING, "Would move memory from node %d to node %d, but __NR_migrate_pages undefined\n",
1797 max_from_node_id, min_dest_node_id);
1798 #endif
1799 // Assume memory did move for current accounting purposes...
1800 p->process_MBs[min_dest_node_id] += p->process_MBs[max_from_node_id];
1801 p->process_MBs[max_from_node_id] = 0;
1802 prev_from_node_id = max_from_node_id;
1803 }
1804 }
1805 // Check pid still active
1806 snprintf(fname, FNAME_SIZE, "/proc/%d", p->pid);
1807 if (access(fname, F_OK) < 0) {
1808 numad_log(LOG_WARNING, "Could not migrate pid %d. Apparently it went away.\n", p->pid);
1809 return 0;
1810 } else {
1811 uint64_t t1 = get_time_stamp();
1812 p->bind_time_stamp = t1;
1813 char node_list_str[BUF_SIZE];
1814 str_from_id_list(node_list_str, BUF_SIZE, p->node_list_p);
1815 numad_log(LOG_NOTICE, "PID %d moved to node(s) %s in %d.%d seconds\n", p->pid, node_list_str, (t1-t0)/100, (t1-t0)%100);
1816 return 1;
1817 }
1818 }
1819
1820
1821 id_list_p pick_numa_nodes(int pid, int cpus, int mbs, int assume_enough_cpus) {
1822 if (log_level >= LOG_DEBUG) {
1823 numad_log(LOG_DEBUG, "PICK NODES FOR: PID: %d, CPUs %d, MBs %d\n", pid, cpus, mbs);
1824 }
1825 char buf[BUF_SIZE];
1826 uint64_t proc_avg_node_CPUs_free = 0;
1827 // For existing processes, get miscellaneous process specific details
1828 int pid_ix;
1829 process_data_p p = NULL;
1830 if ((pid > 0) && ((pid_ix = process_hash_lookup(pid)) >= 0)) {
1831 p = &process_hash_table[pid_ix];
1832 // Add up per-node memory in use by this process.
1833 // This scanning is expensive and should be minimized.
1834 char fname[FNAME_SIZE];
1835 snprintf(fname, FNAME_SIZE, "/proc/%d/numa_maps", pid);
1836 FILE *fs = fopen(fname, "r");
1837 if (!fs) {
1838 numad_log(LOG_WARNING, "Tried to research PID %d numamaps, but it apparently went away.\n", p->pid);
1839 return NULL; // Assume the process terminated
1840 }
1841 // Allocate and zero per node memory array.
1842 // The "+1 node" is for accumulating interleaved memory
1843 p->process_MBs = realloc(p->process_MBs, (num_nodes + 1) * sizeof(uint64_t));
1844 if (p->process_MBs == NULL) {
1845 numad_log(LOG_CRIT, "p->process_MBs realloc failed\n");
1846 exit(EXIT_FAILURE);
1847 }
1848 memset(p->process_MBs, 0, (num_nodes + 1) * sizeof(uint64_t));
1849 int process_has_interleaved_memory = 0;
1850 while (fgets(buf, BUF_SIZE, fs)) {
1851 int interleaved_memory = 0;
1852 uint64_t page_size = page_size_in_bytes;
1853 const char *delimiters = " \n";
1854 char *str_p = strtok(buf, delimiters);
1855 while (str_p) {
1856 if (!strncmp(str_p, "interleave", 10)) {
1857 interleaved_memory = 1;
1858 process_has_interleaved_memory = 1;
1859 } else if (!strcmp(str_p, "huge")) {
1860 page_size = huge_page_size_in_bytes;
1861 } else if (*str_p++ == 'N') {
1862 int node;
1863 uint64_t pages;
1864 CONVERT_DIGITS_TO_NUM(str_p, node);
1865 if (*str_p++ != '=') {
1866 numad_log(LOG_CRIT, "numa_maps node number parse error\n");
1867 exit(EXIT_FAILURE);
1868 }
1869 CONVERT_DIGITS_TO_NUM(str_p, pages);
1870 p->process_MBs[node] += (pages * page_size);
1871 if (interleaved_memory) {
1872 // sum interleaved quantity in "extra node"
1873 p->process_MBs[num_nodes] += (pages * page_size);
1874 }
1875 }
1876 // Get next token on the line
1877 str_p = strtok(NULL, delimiters);
1878 }
1879 }
1880 fclose(fs);
1881 // Start with CPUs already used by process
1882 // proc_avg_node_CPUs_free = p->CPUs_used;
1883 proc_avg_node_CPUs_free = ((p->CPUs_used + 35) / 100) * 100 ;
1884 if (proc_avg_node_CPUs_free < p->CPUs_used) {
1885 proc_avg_node_CPUs_free = p->CPUs_used;
1886 }
1887 for (int ix = 0; (ix <= num_nodes); ix++) {
1888 p->process_MBs[ix] /= MEGABYTE;
1889 if ((log_level >= LOG_DEBUG) && (p->process_MBs[ix] > 0)) {
1890 if (ix == num_nodes) {
1891 numad_log(LOG_DEBUG, "Interleaved MBs: %ld\n", ix, p->process_MBs[ix]);
1892 } else {
1893 numad_log(LOG_DEBUG, "PROCESS_MBs[%d]: %ld\n", ix, p->process_MBs[ix]);
1894 }
1895 }
1896 if (ID_IS_IN_LIST(ix, p->node_list_p)) {
1897 proc_avg_node_CPUs_free += node[ix].CPUs_free;
1898 }
1899 }
1900 proc_avg_node_CPUs_free /= NUM_IDS_IN_LIST(p->node_list_p);
1901 if ((process_has_interleaved_memory) && (keep_interleaved_memory)) {
1902 // Mark this process as having interleaved memory so we do not
1903 // merge the interleaved memory. Time stamp it as done and return.
1904 p->flags |= PROCESS_FLAG_INTERLEAVED;
1905 p->bind_time_stamp = get_time_stamp();
1906 if (log_level >= LOG_DEBUG) {
1907 numad_log(LOG_DEBUG, "Skipping evaluation of PID %d because of interleaved memory.\n", p->pid);
1908 }
1909 return NULL;
1910 }
1911 } // end of existing PID conditional
1912 // Make a copy of node available resources array. Add in info specific to
1913 // this process to equalize available resource quantities wrt locations of
1914 // resources already in use by this process.
1915 static node_data_p tmp_node;
1916 tmp_node = realloc(tmp_node, num_nodes * sizeof(node_data_t) );
1917 if (tmp_node == NULL) {
1918 numad_log(LOG_CRIT, "tmp_node realloc failed\n");
1919 exit(EXIT_FAILURE);
1920 }
1921 memcpy(tmp_node, node, num_nodes * sizeof(node_data_t) );
1922 // Adjust how many MBs and CPUs are available per node and calculate the node magnitude
1923 uint64_t sum_of_node_CPUs_free = 0;
1924 for (int ix = 0; (ix < num_nodes); ix++) {
1925 if (pid > 0) {
1926 if (NUM_IDS_IN_LIST(p->node_list_p) < num_nodes) {
1927 // If the process is currently bound running on less than all the
1928 // nodes, first add back (biased) memory already used by this
1929 // process on this node, then assign average process CPU / node
1930 // for this process iff the process is present on this node.
1931 tmp_node[ix].MBs_free += ((p->process_MBs[ix] * 11) / 8); // Apply heavy mem bias
1932 if (ID_IS_IN_LIST(ix, p->node_list_p)) {
1933 tmp_node[ix].CPUs_free = proc_avg_node_CPUs_free;
1934 if (assume_enough_cpus) {
1935 long overage = ((tmp_node[ix].active_threads * 100) - tmp_node[ix].CPUs_total);
1936 if (overage > 0) {
1937 if (log_level >= LOG_DEBUG) {
1938 numad_log(LOG_DEBUG, "Reducing Node[%d] CPUs_free by %ld.\n", ix, overage);
1939 }
1940 if (overage > tmp_node[ix].CPUs_free) {
1941 tmp_node[ix].CPUs_free = 0;
1942 } else {
1943 tmp_node[ix].CPUs_free -= overage;
1944 }
1945 }
1946 }
1947 }
1948 } else {
1949 // Process not yet bound to a subset of nodes.
1950 // Add back memory used by this process on this node.
1951 tmp_node[ix].MBs_free += ((p->process_MBs[ix] * 17) / 16); // Apply light mem bias
1952 // Add back CPU used by this process in proportion to the memory used on this node.
1953 tmp_node[ix].CPUs_free += ((p->CPUs_used * p->process_MBs[ix]) / p->MBs_used);
1954 }
1955 if (tmp_node[ix].CPUs_free > tmp_node[ix].CPUs_total) {
1956 tmp_node[ix].CPUs_free = tmp_node[ix].CPUs_total;
1957 }
1958 sum_of_node_CPUs_free += tmp_node[ix].CPUs_free;
1959 if (tmp_node[ix].MBs_free > tmp_node[ix].MBs_total) {
1960 tmp_node[ix].MBs_free = tmp_node[ix].MBs_total;
1961 }
1962 }
1963 // Enforce 1/100th CPU minimum
1964 if (tmp_node[ix].CPUs_free < 1) {
1965 tmp_node[ix].CPUs_free = 1;
1966 }
1967 tmp_node[ix].magnitude = (tmp_node[ix].MBs_free * tmp_node[ix].CPUs_free);
1968 numad_log(LOG_DEBUG, "Node[%d]: MBs_free: %ld CPUs_free: %ld Magnitude: %ld\n",
1969 ix, tmp_node[ix].MBs_free, tmp_node[ix].CPUs_free, tmp_node[ix].magnitude);
1970 }
1971
1972 // Now figure out where to get resources for this request....
1973 static id_list_p target_node_list_p;
1974 CLEAR_NODE_LIST(target_node_list_p);
1975 // Establish a CPU flex fudge factor, on the presumption it is OK if not
1976 // quite all the CPU request is met. However, if trying to find resources
1977 // for pre-placement advice request, do not underestimate the amount of
1978 // CPUs needed. Instead, err on the side of providing too many resources.
1979 int cpu_flex = 0;
1980 if (pid > 0) {
1981 if (target_utilization < 100) {
1982 // Is half of the utilization margin a good amount of CPU flexing?
1983 cpu_flex = ((100 - target_utilization) * node[0].CPUs_total) / 200;
1984 } else {
1985 cpu_flex = 50; // Just use half a CPU for cpu_flex
1986 }
1987 }
1988
1989 // Use an index to sort NUMA connected resource chain for each node
1990 int index[num_nodes];
1991 uint64_t totmag[num_nodes];
1992 for (int ix = 0; (ix < num_nodes); ix++) {
1993 // Reset the index each time
1994 for (int n = 0; (n < num_nodes); n++) {
1995 index[n] = n;
1996 }
1997 // Sort by minimum relative NUMA distance from node[ix],
1998 // breaking distance ties with magnitude of available resources
1999 for (int ij = 0; (ij < num_nodes); ij++) {
2000 int best_ix = ij;
2001 for (int ik = ij + 1; (ik < num_nodes); ik++) {
2002 int ik_dist = tmp_node[index[ik]].distance[ix];
2003 int best_ix_dist = tmp_node[index[best_ix]].distance[ix];
2004 if (best_ix_dist > ik_dist) {
2005 best_ix = ik;
2006 } else if (best_ix_dist == ik_dist) {
2007 if (tmp_node[index[best_ix]].magnitude < tmp_node[index[ik]].magnitude ) {
2008 best_ix = ik;
2009 }
2010 }
2011 }
2012 if (best_ix != ij) {
2013 int tmp = index[ij];
2014 index[ij] = index[best_ix];
2015 index[best_ix] = tmp;
2016 }
2017 }
2018
2019 #if 0
2020 if (log_level >= LOG_DEBUG) {
2021 for (int iq = 0; (iq < num_nodes); iq++) {
2022 numad_log(LOG_DEBUG, "Node: %d Dist: %d Magnitude: %ld\n",
2023 tmp_node[index[iq]].node_id, tmp_node[index[iq]].distance[ix], tmp_node[index[iq]].magnitude);
2024 }
2025 }
2026 #endif
2027
2028 // Save the totmag[] sum of the magnitudes of expected needed nodes,
2029 // "normalized" by NUMA distance (by dividing each magnitude by the
2030 // relative distance squared).
2031 totmag[ix] = 0;
2032 for (int ij = 0; (ij < num_nodes); ij++) {
2033 int dist = tmp_node[index[ij]].distance[ix];
2034 totmag[ix] += (tmp_node[index[ij]].magnitude / (dist * dist));
2035 }
2036 numad_log(LOG_DEBUG, "Totmag[%d]: %ld\n", ix, totmag[ix]);
2037 }
2038
2039 // Now find the best NUMA node based on the normalized sum of node
2040 // magnitudes expected to be used.
2041 int best_node_ix = 0;
2042 for (int ix = 0; (ix < num_nodes); ix++) {
2043 if (totmag[best_node_ix] < totmag[ix]) {
2044 best_node_ix = ix;
2045 }
2046 }
2047 numad_log(LOG_DEBUG, "best_node_ix: %d\n", best_node_ix);
2048 // Reset sorting index again
2049 for (int n = 0; (n < num_nodes); n++) {
2050 index[n] = n;
2051 }
2052 // Sort index by distance from node[best_node_ix],
2053 // breaking distance ties with magnitude
2054 for (int ij = 0; (ij < num_nodes); ij++) {
2055 int best_ix = ij;
2056 for (int ik = ij + 1; (ik < num_nodes); ik++) {
2057 int ik_dist = tmp_node[index[ik]].distance[best_node_ix];
2058 int best_ix_dist = tmp_node[index[best_ix]].distance[best_node_ix];
2059 if (best_ix_dist > ik_dist) {
2060 best_ix = ik;
2061 } else if (best_ix_dist == ik_dist) {
2062 if (tmp_node[index[best_ix]].magnitude < tmp_node[index[ik]].magnitude ) {
2063 best_ix = ik;
2064 }
2065 }
2066 }
2067 if (best_ix != ij) {
2068 int tmp = index[ij];
2069 index[ij] = index[best_ix];
2070 index[best_ix] = tmp;
2071 }
2072 }
2073
2074 #if 0
2075 if (log_level >= LOG_DEBUG) {
2076 for (int iq = 0; (iq < num_nodes); iq++) {
2077 numad_log(LOG_DEBUG, "Node: %d Dist: %d Magnitude: %ld\n",
2078 tmp_node[index[iq]].node_id, tmp_node[index[iq]].distance[best_node_ix], tmp_node[index[iq]].magnitude);
2079 }
2080 }
2081 #endif
2082
2083 // Allocate more resources until request is met.
2084 for (int ix = 0; (ix < num_nodes); ix++) {
2085 if (log_level >= LOG_DEBUG) {
2086 numad_log(LOG_DEBUG, "MBs: %d, CPUs: %d\n", mbs, cpus);
2087 }
2088 if (tmp_node[index[ix]].CPUs_free > 10) {
2089 numad_log(LOG_DEBUG, "Assigning resources from node %d\n", tmp_node[index[ix]].node_id);
2090 ADD_ID_TO_LIST(tmp_node[index[ix]].node_id, target_node_list_p);
2091 }
2092 if (EQUAL_LISTS(target_node_list_p, all_nodes_list_p)) {
2093 // Apparently we must use all resource nodes...
2094 break;
2095 }
2096 // "Consume" the resources on this node
2097 #define CPUS_MARGIN 0
2098 #define MBS_MARGIN 100
2099 if (tmp_node[index[ix]].MBs_free >= (mbs + MBS_MARGIN)) {
2100 tmp_node[index[ix]].MBs_free -= mbs;
2101 mbs = 0;
2102 } else {
2103 if (tmp_node[index[ix]].MBs_free > MBS_MARGIN) {
2104 mbs -= (tmp_node[index[ix]].MBs_free - MBS_MARGIN);
2105 }
2106 tmp_node[index[ix]].MBs_free = MBS_MARGIN;
2107 }
2108 if (tmp_node[index[ix]].CPUs_free >= (cpus + CPUS_MARGIN)) {
2109 tmp_node[index[ix]].CPUs_free -= cpus;
2110 cpus = 0;
2111 } else {
2112 if (tmp_node[index[ix]].CPUs_free > CPUS_MARGIN) {
2113 cpus -= (tmp_node[index[ix]].CPUs_free - CPUS_MARGIN);
2114 }
2115 tmp_node[index[ix]].CPUs_free = CPUS_MARGIN;
2116 }
2117 if ((mbs <= 0) && ((cpus <= cpu_flex) || (assume_enough_cpus))) {
2118 break;
2119 }
2120 }
2121 // int avg_mbs_per_node = p->MBs_used / NUM_IDS_IN_LIST(target_node_list_p);
2122
2123 // For existing processes, calculate the non-local memory percent to see if
2124 // process is already in the right place.
2125 if ((pid > 0) && (p != NULL)) {
2126 uint64_t nonlocal_memory = 0;
2127 for (int ix = 0; (ix < num_nodes); ix++) {
2128 if (!ID_IS_IN_LIST(ix, target_node_list_p)) {
2129 // Accumulate total of nonlocal memory
2130 nonlocal_memory += p->process_MBs[ix];
2131 }
2132 }
2133 int disp_percent = (100 * nonlocal_memory) / p->MBs_used;
2134 // If this existing process is already located where we want it, then just
2135 // return NULL indicating no need to change binding this time. Check the
2136 // ammount of nonlocal memory against the target_memlocality_perecent.
2137 if ((disp_percent <= (100 - target_memlocality)) && (p->bind_time_stamp) && (EQUAL_LISTS(target_node_list_p, p->node_list_p))) {
2138 // Already bound to targets, and enough of the memory is located where we want it, so no need to rebind
2139 if (log_level >= LOG_DEBUG) {
2140 numad_log(LOG_DEBUG, "Process %d already %d percent localized to target nodes.\n", p->pid, 100 - disp_percent);
2141 }
2142 p->bind_time_stamp = get_time_stamp();
2143 return NULL;
2144 }
2145 }
2146 // Must always provide at least one node for pre-placement advice.
2147 // And hack to unbind when apparently no resources.
2148 if (NUM_IDS_IN_LIST(target_node_list_p) <= 0) {
2149 numad_log(LOG_WARNING, "Empty target node list -- using all nodes.\n");
2150 COPY_LIST(all_nodes_list_p, target_node_list_p);
2151 }
2152
2153 // Log advice, and return target node list
2154 if ((pid > 0) && (p->bind_time_stamp)) {
2155 str_from_id_list(buf, BUF_SIZE, p->node_list_p);
2156 } else {
2157 str_from_id_list(buf, BUF_SIZE, all_nodes_list_p);
2158 }
2159 char buf2[BUF_SIZE];
2160 str_from_id_list(buf2, BUF_SIZE, target_node_list_p);
2161 char *cmd_name = "(unknown)";
2162 if ((p) && (p->comm)) {
2163 cmd_name = p->comm;
2164 }
2165 numad_log(LOG_NOTICE, "Advising pid %d %s move from nodes (%s) to nodes (%s)\n", pid, cmd_name, buf, buf2);
2166 if (pid > 0) {
2167 COPY_LIST(target_node_list_p, p->node_list_p);
2168 }
2169 return target_node_list_p;
2170 }
2171
2172
2173
2174 int manage_loads() {
2175 uint64_t time_stamp = get_time_stamp();
2176 // Use temporary index to access and sort hash table entries
2177 static process_data_p *pindex;
2178 static int pindex_size;
2179
2180 // Update pindex[] with active candidates. First, check if we need to resize.
2181 if (pindex_size < process_hash_table_size) {
2182 pindex_size = process_hash_table_size;
2183 pindex = realloc(pindex, pindex_size * sizeof(process_data_p));
2184 if (pindex == NULL) {
2185 numad_log(LOG_CRIT, "pindex realloc failed\n");
2186 exit(EXIT_FAILURE);
2187 }
2188 // Quick round trip whenever we resize the hash table.
2189 // This is mostly to avoid max_interval wait at start up.
2190 return (min_interval);
2191 }
2192 memset(pindex, 0, pindex_size * sizeof(process_data_p));
2193 // Use pindex to access and sort hash table entries.
2194 // Copy live candidate pointers to the index for sorting
2195 // if they meet the threshold for memory usage and CPU usage.
2196 int nprocs = 0;
2197 static int old_nprocs;
2198 static int quick_turn_around;
2199 long sum_active_threads = 0;
2200 static long old_sum_active_threads;
2201 for (int ix = 0; (ix < process_hash_table_size); ix++) {
2202 process_data_p p = &process_hash_table[ix];
2203 if ((p->pid) && (p->CPUs_used > CPU_THRESHOLD) && (p->MBs_used > MEMORY_THRESHOLD)) {
2204 pindex[nprocs] = p;
2205 nprocs += 1;
2206 sum_active_threads += p->num_active_threads;
2207 }
2208 }
2209 int nprocs_changed = (nprocs != old_nprocs);
2210 int active_threads_changed = (sum_active_threads != old_sum_active_threads);
2211 old_nprocs = nprocs;
2212 old_sum_active_threads = sum_active_threads;
2213 if (active_threads_changed || nprocs_changed) {
2214 quick_turn_around += 3;
2215 }
2216 // Order candidate considerations using timestamps and magnitude: amount of
2217 // CPU used * amount of memory used. Not expecting a long list here. Use
2218 // a simplistic sort -- however move all not yet bound to front of list and
2219 // order by decreasing magnitude. Previously bound processes follow in
2220 // bins of increasing magnitude treating values within 20% as aquivalent.
2221 // Within bins, order by bind_time_stamp so oldest bound will be higher
2222 // priority to evaluate. Start by moving all never bound to beginning.
2223 // FIXME: should num_unbound here include those set to all cpus?
2224 int num_unbound = 0;
2225 for (int ij = 0; (ij < nprocs); ij++) {
2226 if (pindex[ij]->bind_time_stamp == 0) {
2227 process_data_p tmp = pindex[num_unbound];
2228 pindex[num_unbound++] = pindex[ij];
2229 pindex[ij] = tmp;
2230 }
2231 }
2232 // Sort all unbound so biggest magnitude comes first
2233 for (int ij = 0; (ij < num_unbound); ij++) {
2234 int best = ij;
2235 for (int ik = ij + 1; (ik < num_unbound); ik++) {
2236 uint64_t ik_mag = (pindex[ ik]->CPUs_used * pindex[ ik]->MBs_used);
2237 uint64_t best_mag = (pindex[best]->CPUs_used * pindex[best]->MBs_used);
2238 if (ik_mag <= best_mag) continue;
2239 best = ik;
2240 }
2241 if (best != ij) {
2242 process_data_p tmp = pindex[ij];
2243 pindex[ij] = pindex[best];
2244 pindex[best] = tmp;
2245 }
2246 }
2247 // Sort the remaining candidates into bins of increasting magnitude, and by
2248 // timestamp within bins.
2249 for (int ij = num_unbound; (ij < nprocs); ij++) {
2250 int best = ij;
2251 for (int ik = ij + 1; (ik < nprocs); ik++) {
2252 uint64_t ik_mag = (pindex[ ik]->CPUs_used * pindex[ ik]->MBs_used);
2253 uint64_t best_mag = (pindex[best]->CPUs_used * pindex[best]->MBs_used);
2254 uint64_t min_mag = ik_mag;
2255 uint64_t diff_mag = best_mag - ik_mag;
2256 if (diff_mag < 0) {
2257 diff_mag = -(diff_mag);
2258 min_mag = best_mag;
2259 }
2260 if ((diff_mag > 0) && (min_mag / diff_mag < 5)) {
2261 // difference > 20 percent. Use magnitude ordering
2262 if (ik_mag <= best_mag) continue;
2263 } else {
2264 // difference within 20 percent. Sort these by bind_time_stamp.
2265 if (pindex[ik]->bind_time_stamp > pindex[best]->bind_time_stamp) continue;
2266 }
2267 best = ik;
2268 }
2269 if (best != ij) {
2270 process_data_p tmp = pindex[ij];
2271 pindex[ij] = pindex[best];
2272 pindex[best] = tmp;
2273 }
2274 }
2275 // Show the candidate processes in the log file
2276 if ((log_level >= LOG_INFO) && (nprocs > 0)) {
2277 numad_log(LOG_INFO, "Candidates: %d\n", nprocs);
2278 for (int ix = 0; (ix < nprocs); ix++) {
2279 process_data_p p = pindex[ix];
2280 char buf[BUF_SIZE];
2281 str_from_id_list(buf, BUF_SIZE, p->node_list_p);
2282 fprintf(log_fs, "Timestamp %ld PID %d %s, Flags %x, Threads %ld/%ld, CPU %ld, MBs %ld/%ld, Magnitude %ld, Node(s) %s\n",
2283 p->data_time_stamp, p->pid, p->comm, p->flags, p->num_active_threads, p->num_threads,
2284 p->CPUs_used, p->MBs_used, p->MBs_size, p->MBs_used * p->CPUs_used, buf);
2285 }
2286 fflush(log_fs);
2287 }
2288
2289 // Calculate per node active_threads;
2290 for (int ix = 0; (ix < num_nodes); ix++) {
2291 node[ix].active_threads = 0;
2292 }
2293 for (int ij = 0; (ij < nprocs); ij++) {
2294 process_data_p p = pindex[ij];
2295 if (NUM_IDS_IN_LIST(p->node_list_p) < num_nodes) {
2296 for (int ix = 0; (ix < num_nodes); ix++) {
2297 if (ID_IS_IN_LIST(ix, p->node_list_p)) {
2298 node[ix].active_threads += (p->num_active_threads / NUM_IDS_IN_LIST(p->node_list_p));
2299 }
2300 }
2301 }
2302 }
2303
2304 // Estimate desired size (+ margin capacity) and
2305 // make resource requests for each candidate process
2306 for (int ix = 0; (ix < nprocs); ix++) {
2307 process_data_p p = pindex[ix];
2308 // If this process has interleaved memory, recheck it only every 30 minutes...
2309 #define MIN_DELAY_FOR_INTERLEAVE (1800 * ONE_HUNDRED)
2310 if (((p->flags & PROCESS_FLAG_INTERLEAVED) > 0)
2311 && (p->bind_time_stamp + MIN_DELAY_FOR_INTERLEAVE > time_stamp)) {
2312 if (log_level >= LOG_DEBUG) {
2313 numad_log(LOG_DEBUG, "Skipping evaluation of PID %d because of interleaved memory.\n", p->pid);
2314 }
2315 continue;
2316 }
2317
2318 // Expand resources needed estimate using target_utilization factor.
2319 // Start with the CPUs actually used (capped by number of threads) for
2320 // CPUs required, and the RSS MBs actually used for the MBs
2321 // requirement, but try to anticipate growing processes, and make sure
2322 // they are not artificially constrained by the current node bindings.
2323 int mem_target_utilization = target_utilization;
2324 int cpu_target_utilization = target_utilization;
2325 // Cap memory utilization at 100 percent (but allow CPUs to oversubscribe)
2326 if (mem_target_utilization > 100) {
2327 mem_target_utilization = 100;
2328 }
2329 int mb_request = (p->MBs_used * 100) / mem_target_utilization;
2330 int cpu_request = (p->CPUs_used * 100) / cpu_target_utilization;
2331 if (cpu_request > p->num_active_threads * 100) {
2332 cpu_request = p->num_active_threads * 100;
2333 }
2334 int boosted = 0;
2335 int kvm_vcpu_threads = 0;
2336 // If process looks like a KVM guest, try to limit thread count to the
2337 // number of vCPU threads. FIXME: Opportunity for IO thread alignment?
2338 if ((p->comm) && (p->comm[0] == '(') && (p->comm[1] == 'q') && (strcmp(p->comm, "(qemu-kvm)") == 0)) {
2339 kvm_vcpu_threads = get_num_kvm_vcpu_threads(p->pid);
2340 if (cpu_request > kvm_vcpu_threads * 100) {
2341 cpu_request = kvm_vcpu_threads * 100;
2342 }
2343 }
2344
2345 // Check RAM and CPU margin on nodes where PID currently bound
2346 uint64_t node_MBs_free = 0;
2347 uint64_t node_MBs_total = 0;
2348 uint64_t node_CPUs_free = 0;
2349 uint64_t node_CPUs_total = 0;
2350 uint64_t other_node_CPUs_free = 0;
2351 for (int ix = 0; (ix < num_nodes); ix++) {
2352 if (ID_IS_IN_LIST(ix, p->node_list_p)) {
2353 node_MBs_free += node[ix].MBs_free;
2354 node_MBs_total += node[ix].MBs_total;
2355 node_CPUs_free += node[ix].CPUs_free;
2356 node_CPUs_total += node[ix].CPUs_total;
2357 } else {
2358 other_node_CPUs_free += node[ix].CPUs_free;
2359 }
2360 }
2361 if (log_level >= LOG_DEBUG) {
2362 numad_log(LOG_DEBUG,
2363 "NODE RESOURCES for PID %d: node_MBs_tot %ld node_MBs_free %ld node_CPUs_tot %ld node_CPUs_free %ld Other_node_CPUs_Free %ld\n",
2364 p->pid, node_MBs_total, node_MBs_free, node_CPUs_total, node_CPUs_free, other_node_CPUs_free );
2365 }
2366
2367 // If unbound go ahead and try to get resources and bind.
2368 // Otherwise, if bound, do some extra steps to see if about to run out of resources on node.
2369 if (NUM_IDS_IN_LIST(p->node_list_p) < num_nodes) {
2370
2371 // If the process virtual memory size is bigger than the currently
2372 // assigned node resources, and we already used approximately 95% of
2373 // the target utilization percent of node memory, then request the
2374 // potential memory size of the process regardless of current usage.
2375 if ((p->MBs_size > (p->MBs_used + node_MBs_free)) &&
2376 ((node_MBs_total - node_MBs_free) * 105 > (node_MBs_total * mem_target_utilization))) {
2377 mb_request = (p->MBs_size * 100) / mem_target_utilization;
2378 } else {
2379 mb_request = (p->MBs_used * 100) / mem_target_utilization;
2380 }
2381 // If not a KVM guest and process might be artificially constrained
2382 if ( (kvm_vcpu_threads == 0)
2383 && (cpu_request < p->num_active_threads * 100)
2384 && (node_CPUs_free < 80) ) {
2385 boosted = 1;
2386 cpu_request = p->num_active_threads * 100;
2387 }
2388
2389 // FIXME: worry about balance here?
2390 // if (ID_IS_IN_LIST(min_node_CPUs_free_id, p->node_list_p) || ID_IS_IN_LIST(min_node_MBs_free_id, p->node_list_p))
2391
2392 } // bound process
2393
2394 // See if there should be enough cores
2395 int assume_enough_cpus = ((sum_active_threads * 100) <= sum_CPUs_total);
2396 for (int ix = 0; (ix < num_nodes); ix++) {
2397 assume_enough_cpus &= ((p->num_active_threads * 100) <= node[ix].CPUs_total);
2398 }
2399 if (assume_enough_cpus) {
2400 if ((NUM_IDS_IN_LIST(p->node_list_p) > 1)
2401 || ((node_CPUs_free < 75) && (other_node_CPUs_free >= p->num_active_threads * 100))) {
2402 boosted = 1;
2403 }
2404 }
2405
2406 // If this process was recently bound, enforce a minimum delay
2407 // between repeated attempts to potentially move the process.
2408 if ((!quick_turn_around) && (!boosted) && (p->bind_time_stamp + MIN_DELAY_FOR_REEVALUATION > time_stamp)) {
2409 // Skip re-evaluation because we just did it recently,
2410 if (log_level >= LOG_DEBUG) {
2411 numad_log(LOG_DEBUG, "Skipping evaluation of PID %d because done too recently.\n", p->pid);
2412 }
2413 continue;
2414 }
2415
2416 // OK, now pick NUMA nodes for this process and bind it!
2417 if (log_level >= LOG_DEBUG) {
2418 numad_log(LOG_DEBUG, "Picking NUMA nodes for PID %d: cpu_reqest %d, mb_request %d, enough_cpus %d\n",
2419 p->pid, cpu_request, mb_request, assume_enough_cpus);
2420 }
2421 pthread_mutex_lock(&node_info_mutex);
2422 id_list_p node_list_p = pick_numa_nodes(p->pid, cpu_request, mb_request, assume_enough_cpus);
2423 // check return value same as p->node_list_p
2424 int rc = 0;
2425 if ((node_list_p != NULL) && (NUM_IDS_IN_LIST(node_list_p) > 0)) {
2426 rc = bind_process_and_maybe_migrate_memory(p, 1);
2427 }
2428 pthread_mutex_unlock(&node_info_mutex);
2429 // Return minimum interval when actively moving processes
2430 if (rc > 0) {
2431 return min_interval;
2432 }
2433
2434 }
2435
2436 // Return maximum interval when no process movement
2437 if (quick_turn_around) {
2438 quick_turn_around -= 1;
2439 return (2 * min_interval);
2440 }
2441 return max_interval;
2442 }
2443
2444
2445
2446
2447
2448
2449
2450 void *set_dynamic_options(void *arg) {
2451 // int arg_value = *(int *)arg;
2452 char buf[BUF_SIZE];
2453 for (;;) {
2454 // Loop here forever waiting for a msg to do something...
2455 msg_t msg;
2456 recv_msg(&msg);
2457 switch (msg.body.cmd) {
2458 case 'C':
2459 use_inactive_file_cache = (msg.body.arg1 != 0);
2460 if (use_inactive_file_cache) {
2461 numad_log(LOG_NOTICE, "Counting inactive file cache as available\n");
2462 } else {
2463 numad_log(LOG_NOTICE, "Counting inactive file cache as unavailable\n");
2464 }
2465 break;
2466 case 'H':
2467 thp_scan_sleep_ms = msg.body.arg1;
2468 set_thp_scan_sleep_ms(thp_scan_sleep_ms);
2469 break;
2470 case 'i':
2471 min_interval = msg.body.arg1;
2472 max_interval = msg.body.arg2;
2473 if (max_interval <= 0) {
2474 shut_down_numad();
2475 }
2476 numad_log(LOG_NOTICE, "Changing interval to %d:%d\n", msg.body.arg1, msg.body.arg2);
2477 break;
2478 case 'K':
2479 keep_interleaved_memory = (msg.body.arg1 != 0);
2480 if (keep_interleaved_memory) {
2481 numad_log(LOG_NOTICE, "Keeping interleaved memory spread across nodes\n");
2482 } else {
2483 numad_log(LOG_NOTICE, "Merging interleaved memory to localized NUMA nodes\n");
2484 }
2485 break;
2486 case 'l':
2487 numad_log(LOG_NOTICE, "Changing log level to %d\n", msg.body.arg1);
2488 log_level = msg.body.arg1;
2489 break;
2490 case 'm':
2491 numad_log(LOG_NOTICE, "Changing target memory locality to %d\n", msg.body.arg1);
2492 target_memlocality = msg.body.arg1;
2493 break;
2494 case 'p':
2495 numad_log(LOG_NOTICE, "Adding PID %d to inclusion PID list\n", msg.body.arg1);
2496 pthread_mutex_lock(&pid_list_mutex);
2497 exclude_pid_list = remove_pid_from_pid_list(exclude_pid_list, msg.body.arg1);
2498 include_pid_list = insert_pid_into_pid_list(include_pid_list, msg.body.arg1);
2499 pthread_mutex_unlock(&pid_list_mutex);
2500 break;
2501 case 'r':
2502 numad_log(LOG_NOTICE, "Removing PID %d from explicit PID lists\n", msg.body.arg1);
2503 pthread_mutex_lock(&pid_list_mutex);
2504 include_pid_list = remove_pid_from_pid_list(include_pid_list, msg.body.arg1);
2505 exclude_pid_list = remove_pid_from_pid_list(exclude_pid_list, msg.body.arg1);
2506 pthread_mutex_unlock(&pid_list_mutex);
2507 break;
2508 case 'S':
2509 scan_all_processes = (msg.body.arg1 != 0);
2510 if (scan_all_processes) {
2511 numad_log(LOG_NOTICE, "Scanning all processes\n");
2512 } else {
2513 numad_log(LOG_NOTICE, "Scanning only explicit PID list processes\n");
2514 }
2515 break;
2516 case 't':
2517 numad_log(LOG_NOTICE, "Changing logical CPU thread percent to %d\n", msg.body.arg1);
2518 htt_percent = msg.body.arg1;
2519 node_info_time_stamp = 0; // to force rescan of nodes/cpus soon
2520 break;
2521 case 'u':
2522 numad_log(LOG_NOTICE, "Changing target utilization to %d\n", msg.body.arg1);
2523 target_utilization = msg.body.arg1;
2524 break;
2525 case 'w':
2526 numad_log(LOG_NOTICE, "Getting NUMA pre-placement advice for %d CPUs and %d MBs\n",
2527 msg.body.arg1, msg.body.arg2);
2528 pthread_mutex_lock(&node_info_mutex);
2529 update_nodes();
2530 id_list_p node_list_p = pick_numa_nodes(-1, msg.body.arg1, msg.body.arg2, 0);
2531 str_from_id_list(buf, BUF_SIZE, node_list_p);
2532 pthread_mutex_unlock(&node_info_mutex);
2533 send_msg(msg.body.src_pid, 'w', 0, 0, buf);
2534 break;
2535 case 'x':
2536 numad_log(LOG_NOTICE, "Adding PID %d to exclusion PID list\n", msg.body.arg1);
2537 pthread_mutex_lock(&pid_list_mutex);
2538 include_pid_list = remove_pid_from_pid_list(include_pid_list, msg.body.arg1);
2539 exclude_pid_list = insert_pid_into_pid_list(exclude_pid_list, msg.body.arg1);
2540 pthread_mutex_unlock(&pid_list_mutex);
2541 break;
2542 default:
2543 numad_log(LOG_WARNING, "Unexpected msg command: %c %d %d %s from PID %d\n",
2544 msg.body.cmd, msg.body.arg1, msg.body.arg1, msg.body.text,
2545 msg.body.src_pid);
2546 break;
2547 }
2548 } // for (;;)
2549 }
2550
2551
2552
2553 void parse_two_arg_values(char *p, int *first_ptr, int *second_ptr, int first_is_optional, int first_scale_digits) {
2554 char *orig_p = p;
2555 char *q = NULL;
2556 int second = -1;
2557 errno = 0;
2558 int first = (int) strtol(p, &p, 10);
2559 if ((errno != 0) || (p == orig_p) || (first < 0)) {
2560 fprintf(stderr, "Can't parse arg value(s): %s\n", orig_p);
2561 exit(EXIT_FAILURE);
2562 }
2563 if (*p == '.') {
2564 p++;
2565 while ((first_scale_digits > 0) && (isdigit(*p))) {
2566 first *= 10;
2567 first += (*p++ - '0');
2568 first_scale_digits -= 1;
2569 }
2570 while (isdigit(*p)) { p++; }
2571 }
2572 while (first_scale_digits > 0) {
2573 first *= 10;
2574 first_scale_digits -= 1;
2575 }
2576 if (*p == ':') {
2577 q = p + 1;
2578 errno = 0;
2579 second = (int) strtol(q, &p, 10);
2580 if ((errno != 0) || (p == q) || (second < 0)) {
2581 fprintf(stderr, "Can't parse arg value(s): %s\n", orig_p);
2582 exit(EXIT_FAILURE);
2583 }
2584 }
2585 if (q != NULL) {
2586 // Two numbers are present
2587 if (first_ptr != NULL) *first_ptr = first;
2588 if (second_ptr != NULL) *second_ptr = second;
2589 } else if (first_is_optional) {
2590 if (second_ptr != NULL) *second_ptr = first;
2591 } else {
2592 if (first_ptr != NULL) *first_ptr = first;
2593 }
2594 }
2595
2596
2597
2598 int main(int argc, char *argv[]) {
2599 int opt;
2600 int C_flag = 0;
2601 int d_flag = 0;
2602 int H_flag = 0;
2603 int i_flag = 0;
2604 int K_flag = 0;
2605 int l_flag = 0;
2606 int m_flag = 0;
2607 int p_flag = 0;
2608 int r_flag = 0;
2609 int S_flag = 0;
2610 int t_flag = 0;
2611 int u_flag = 0;
2612 int v_flag = 0;
2613 int w_flag = 0;
2614 int x_flag = 0;
2615 int tmp_int = 0;
2616 long list_pid = 0;
2617 while ((opt = getopt(argc, argv, "C:dD:hH:i:K:l:m:p:r:R:S:t:u:vVw:x:")) != -1) {
2618 switch (opt) {
2619 case 'C':
2620 C_flag = 1;
2621 use_inactive_file_cache = (atoi(optarg) != 0);
2622 break;
2623 case 'd':
2624 d_flag = 1;
2625 log_level = LOG_DEBUG;
2626 break;
2627 case 'D':
2628 // obsoleted
2629 break;
2630 case 'h':
2631 print_usage_and_exit(argv[0]);
2632 break;
2633 case 'H':
2634 tmp_int = atoi(optarg);
2635 if ((tmp_int == 0) || ((tmp_int > 9) && (tmp_int < 1000001))) {
2636 // 0 means do not change the system default value
2637 H_flag = 1;
2638 thp_scan_sleep_ms = tmp_int;
2639 } else {
2640 fprintf(stderr, "THP scan_sleep_ms must be > 9 and < 1000001\n");
2641 exit(EXIT_FAILURE);
2642 }
2643 break;
2644 case 'i':
2645 i_flag = 1;
2646 parse_two_arg_values(optarg, &min_interval, &max_interval, 1, 0);
2647 break;
2648 case 'K':
2649 K_flag = 1;
2650 keep_interleaved_memory = (atoi(optarg) != 0);
2651 break;
2652 case 'l':
2653 l_flag = 1;
2654 log_level = atoi(optarg);
2655 break;
2656 case 'm':
2657 tmp_int = atoi(optarg);
2658 if ((tmp_int >= 50) && (tmp_int <= 100)) {
2659 m_flag = 1;
2660 target_memlocality = tmp_int;
2661 }
2662 break;
2663 case 'p':
2664 p_flag = 1;
2665 list_pid = atol(optarg);
2666 exclude_pid_list = remove_pid_from_pid_list(exclude_pid_list, list_pid);
2667 include_pid_list = insert_pid_into_pid_list(include_pid_list, list_pid);
2668 break;
2669 case 'r':
2670 r_flag = 1;
2671 list_pid = atol(optarg);
2672 // Remove this PID from both explicit pid lists.
2673 include_pid_list = remove_pid_from_pid_list(include_pid_list, list_pid);
2674 exclude_pid_list = remove_pid_from_pid_list(exclude_pid_list, list_pid);
2675 break;
2676 case 'R':
2677 reserved_cpu_str = strdup(optarg);
2678 break;
2679 case 'S':
2680 S_flag = 1;
2681 scan_all_processes = (atoi(optarg) != 0);
2682 break;
2683 case 't':
2684 tmp_int = atoi(optarg);
2685 if ((tmp_int >= 0) && (tmp_int <= 100)) {
2686 t_flag = 1;
2687 htt_percent = tmp_int;
2688 }
2689 break;
2690 case 'u':
2691 tmp_int = atoi(optarg);
2692 if ((tmp_int >= 10) && (tmp_int <= 130)) {
2693 u_flag = 1;
2694 target_utilization = tmp_int;
2695 }
2696 break;
2697 case 'v':
2698 v_flag = 1;
2699 log_level = LOG_INFO;
2700 break;
2701 case 'V':
2702 print_version_and_exit(argv[0]);
2703 break;
2704 case 'w':
2705 w_flag = 1;
2706 parse_two_arg_values(optarg, &requested_cpus, &requested_mbs, 0, 2);
2707 break;
2708 case 'x':
2709 x_flag = 1;
2710 list_pid = atol(optarg);
2711 include_pid_list = remove_pid_from_pid_list(include_pid_list, list_pid);
2712 exclude_pid_list = insert_pid_into_pid_list(exclude_pid_list, list_pid);
2713 break;
2714 default:
2715 print_usage_and_exit(argv[0]);
2716 break;
2717 }
2718 }
2719 if (argc > optind) {
2720 fprintf(stderr, "Unexpected arg = %s\n", argv[optind]);
2721 exit(EXIT_FAILURE);
2722 }
2723 if (i_flag) {
2724 if ((max_interval < min_interval) && (max_interval != 0)) {
2725 fprintf(stderr, "Max interval (%d) must be greater than min interval (%d)\n", max_interval, min_interval);
2726 exit(EXIT_FAILURE);
2727 }
2728 }
2729 init_run_file();
2730 open_log_file();
2731 init_msg_queue();
2732 num_cpus = get_num_cpus();
2733 page_size_in_bytes = sysconf(_SC_PAGESIZE);
2734 huge_page_size_in_bytes = get_huge_page_size_in_bytes();
2735 // Figure out if this is the daemon, or a subsequent invocation
2736 int daemon_pid = get_daemon_pid(1);
2737 if (daemon_pid > 0) {
2738 // Daemon is already running. So send dynamic options to persistant
2739 // thread to handle requests, get the response (if any), and finish.
2740 msg_t msg;
2741 if (C_flag) {
2742 send_msg(daemon_pid, 'C', use_inactive_file_cache, 0, "");
2743 }
2744 if (H_flag) {
2745 send_msg(daemon_pid, 'H', thp_scan_sleep_ms, 0, "");
2746 }
2747 if (i_flag) {
2748 send_msg(daemon_pid, 'i', min_interval, max_interval, "");
2749 }
2750 if (K_flag) {
2751 send_msg(daemon_pid, 'K', keep_interleaved_memory, 0, "");
2752 }
2753 if (d_flag || l_flag || v_flag) {
2754 send_msg(daemon_pid, 'l', log_level, 0, "");
2755 }
2756 if (m_flag) {
2757 send_msg(daemon_pid, 'm', target_memlocality, 0, "");
2758 }
2759 if (p_flag) {
2760 send_msg(daemon_pid, 'p', list_pid, 0, "");
2761 }
2762 if (r_flag) {
2763 send_msg(daemon_pid, 'r', list_pid, 0, "");
2764 }
2765 if (S_flag) {
2766 send_msg(daemon_pid, 'S', scan_all_processes, 0, "");
2767 }
2768 if (t_flag) {
2769 send_msg(daemon_pid, 't', htt_percent, 0, "");
2770 }
2771 if (u_flag) {
2772 send_msg(daemon_pid, 'u', target_utilization, 0, "");
2773 }
2774 if (w_flag) {
2775 send_msg(daemon_pid, 'w', requested_cpus, requested_mbs, "");
2776 recv_msg(&msg);
2777 fprintf(stdout, "%s\n", msg.body.text);
2778 }
2779 if (x_flag) {
2780 send_msg(daemon_pid, 'x', list_pid, 0, "");
2781 }
2782 close_log_file();
2783 exit(EXIT_SUCCESS);
2784 }
2785 // No numad daemon running yet.
2786 // First, make note of any reserved CPUs....
2787 if (reserved_cpu_str != NULL) {
2788 CLEAR_CPU_LIST(reserved_cpu_mask_list_p);
2789 int n = add_ids_to_list_from_str(reserved_cpu_mask_list_p, reserved_cpu_str);
2790 char buf[BUF_SIZE];
2791 str_from_id_list(buf, BUF_SIZE, reserved_cpu_mask_list_p);
2792 numad_log(LOG_NOTICE, "Reserving %d CPUs (%s) for non-numad use\n", n, buf);
2793 // turn reserved list into a negated mask for later ANDing use...
2794 negate_cpu_list(reserved_cpu_mask_list_p);
2795 }
2796 // If it is a "-w" pre-placement request, handle that without starting
2797 // the daemon. Otherwise start the numad daemon.
2798 if (w_flag) {
2799 // Get pre-placement NUMA advice without starting daemon
2800 update_nodes();
2801 sleep(2);
2802 update_nodes();
2803 numad_log(LOG_NOTICE, "Getting NUMA pre-placement advice for %d CPUs and %d MBs\n", requested_cpus, requested_mbs);
2804 id_list_p node_list_p = pick_numa_nodes(-1, requested_cpus, requested_mbs, 0);
2805 char buf[BUF_SIZE];
2806 str_from_id_list(buf, BUF_SIZE, node_list_p);
2807 fprintf(stdout, "%s\n", buf);
2808 close_log_file();
2809 exit(EXIT_SUCCESS);
2810 } else if (max_interval > 0) {
2811 // Start the numad daemon...
2812 check_prereqs(argv[0]);
2813 #if (!NO_DAEMON)
2814 // Daemonize self...
2815 daemon_pid = fork();
2816 if (daemon_pid < 0) { numad_log(LOG_CRIT, "fork() failed\n"); exit(EXIT_FAILURE); }
2817 // Parent process now exits
2818 if (daemon_pid > 0) { exit(EXIT_SUCCESS); }
2819 // Child process continues...
2820 umask(S_IWGRP | S_IWOTH); // Reset the file mode
2821 int sid = setsid(); // Start a new session
2822 if (sid < 0) { numad_log(LOG_CRIT, "setsid() failed\n"); exit(EXIT_FAILURE); }
2823 if ((chdir("/")) < 0) { numad_log(LOG_CRIT, "chdir() failed"); exit(EXIT_FAILURE); }
2824 daemon_pid = register_numad_pid();
2825 if (daemon_pid != getpid()) {
2826 numad_log(LOG_CRIT, "Could not register daemon PID\n");
2827 exit(EXIT_FAILURE);
2828 }
2829 fclose(stdin);
2830 fclose(stdout);
2831 if (log_fs != stderr) {
2832 fclose(stderr);
2833 }
2834 #endif
2835 // Set up signal handlers
2836 struct sigaction sa;
2837 memset(&sa, 0, sizeof(sa));
2838 sa.sa_handler = sig_handler;
2839 if (sigaction(SIGHUP, &sa, NULL)
2840 || sigaction(SIGTERM, &sa, NULL)
2841 || sigaction(SIGQUIT, &sa, NULL)) {
2842 numad_log(LOG_CRIT, "sigaction does not work?\n");
2843 exit(EXIT_FAILURE);
2844 }
2845 // Allocate initial process hash table
2846 process_hash_table_expand();
2847 // Spawn a thread to handle messages from subsequent invocation requests
2848 pthread_mutex_init(&pid_list_mutex, NULL);
2849 pthread_mutex_init(&node_info_mutex, NULL);
2850 pthread_attr_t attr;
2851 if (pthread_attr_init(&attr) != 0) {
2852 numad_log(LOG_CRIT, "pthread_attr_init failure\n");
2853 exit(EXIT_FAILURE);
2854 }
2855 #if (!NO_DAEMON)
2856 pthread_t tid;
2857 if (pthread_create(&tid, &attr, &set_dynamic_options, NULL) != 0) {
2858 numad_log(LOG_CRIT, "pthread_create failure: setting thread\n");
2859 exit(EXIT_FAILURE);
2860 }
2861 #endif
2862 // Loop here forwever...
2863 for (;;) {
2864 int interval = max_interval;
2865 pthread_mutex_lock(&node_info_mutex);
2866 int nodes = update_nodes();
2867 pthread_mutex_unlock(&node_info_mutex);
2868 if (log_level >= LOG_INFO) {
2869 show_nodes(nodes);
2870 }
2871 int processes = update_processes();
2872 if (log_level >= LOG_INFO) {
2873 show_processes(processes);
2874 }
2875 if (nodes > 1) {
2876 interval = manage_loads();
2877 }
2878 #if (!NO_DAEMON)
2879 sleep(interval);
2880 #endif
2881 if (got_sigterm | got_sigquit) {
2882 shut_down_numad();
2883 }
2884 if (got_sighup) {
2885 got_sighup = 0;
2886 close_log_file();
2887 open_log_file();
2888 }
2889 }
2890 if (pthread_attr_destroy(&attr) != 0) {
2891 numad_log(LOG_WARNING, "pthread_attr_destroy failure\n");
2892 }
2893 pthread_mutex_destroy(&pid_list_mutex);
2894 pthread_mutex_destroy(&node_info_mutex);
2895 }
2896 exit(EXIT_SUCCESS);
2897 }
2898