xref: /openbmc/linux/tools/perf/bench/numa.c (revision 7a2eb736)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * numa.c
4  *
5  * numa: Simulate NUMA-sensitive workload and measure their NUMA performance
6  */
7 
8 #include <inttypes.h>
9 /* For the CLR_() macros */
10 #include <pthread.h>
11 
12 #include "../perf.h"
13 #include "../builtin.h"
14 #include <subcmd/parse-options.h>
15 #include "../util/cloexec.h"
16 
17 #include "bench.h"
18 
19 #include <errno.h>
20 #include <sched.h>
21 #include <stdio.h>
22 #include <assert.h>
23 #include <malloc.h>
24 #include <signal.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/mman.h>
29 #include <sys/time.h>
30 #include <sys/resource.h>
31 #include <sys/wait.h>
32 #include <sys/prctl.h>
33 #include <sys/types.h>
34 #include <linux/kernel.h>
35 #include <linux/time64.h>
36 #include <linux/numa.h>
37 #include <linux/zalloc.h>
38 
39 #include <numa.h>
40 #include <numaif.h>
41 
42 #ifndef RUSAGE_THREAD
43 # define RUSAGE_THREAD 1
44 #endif
45 
46 /*
47  * Regular printout to the terminal, supressed if -q is specified:
48  */
49 #define tprintf(x...) do { if (g && g->p.show_details >= 0) printf(x); } while (0)
50 
51 /*
52  * Debug printf:
53  */
54 #undef dprintf
55 #define dprintf(x...) do { if (g && g->p.show_details >= 1) printf(x); } while (0)
56 
57 struct thread_data {
58 	int			curr_cpu;
59 	cpu_set_t		bind_cpumask;
60 	int			bind_node;
61 	u8			*process_data;
62 	int			process_nr;
63 	int			thread_nr;
64 	int			task_nr;
65 	unsigned int		loops_done;
66 	u64			val;
67 	u64			runtime_ns;
68 	u64			system_time_ns;
69 	u64			user_time_ns;
70 	double			speed_gbs;
71 	pthread_mutex_t		*process_lock;
72 };
73 
74 /* Parameters set by options: */
75 
76 struct params {
77 	/* Startup synchronization: */
78 	bool			serialize_startup;
79 
80 	/* Task hierarchy: */
81 	int			nr_proc;
82 	int			nr_threads;
83 
84 	/* Working set sizes: */
85 	const char		*mb_global_str;
86 	const char		*mb_proc_str;
87 	const char		*mb_proc_locked_str;
88 	const char		*mb_thread_str;
89 
90 	double			mb_global;
91 	double			mb_proc;
92 	double			mb_proc_locked;
93 	double			mb_thread;
94 
95 	/* Access patterns to the working set: */
96 	bool			data_reads;
97 	bool			data_writes;
98 	bool			data_backwards;
99 	bool			data_zero_memset;
100 	bool			data_rand_walk;
101 	u32			nr_loops;
102 	u32			nr_secs;
103 	u32			sleep_usecs;
104 
105 	/* Working set initialization: */
106 	bool			init_zero;
107 	bool			init_random;
108 	bool			init_cpu0;
109 
110 	/* Misc options: */
111 	int			show_details;
112 	int			run_all;
113 	int			thp;
114 
115 	long			bytes_global;
116 	long			bytes_process;
117 	long			bytes_process_locked;
118 	long			bytes_thread;
119 
120 	int			nr_tasks;
121 	bool			show_quiet;
122 
123 	bool			show_convergence;
124 	bool			measure_convergence;
125 
126 	int			perturb_secs;
127 	int			nr_cpus;
128 	int			nr_nodes;
129 
130 	/* Affinity options -C and -N: */
131 	char			*cpu_list_str;
132 	char			*node_list_str;
133 };
134 
135 
136 /* Global, read-writable area, accessible to all processes and threads: */
137 
138 struct global_info {
139 	u8			*data;
140 
141 	pthread_mutex_t		startup_mutex;
142 	int			nr_tasks_started;
143 
144 	pthread_mutex_t		startup_done_mutex;
145 
146 	pthread_mutex_t		start_work_mutex;
147 	int			nr_tasks_working;
148 
149 	pthread_mutex_t		stop_work_mutex;
150 	u64			bytes_done;
151 
152 	struct thread_data	*threads;
153 
154 	/* Convergence latency measurement: */
155 	bool			all_converged;
156 	bool			stop_work;
157 
158 	int			print_once;
159 
160 	struct params		p;
161 };
162 
163 static struct global_info	*g = NULL;
164 
165 static int parse_cpus_opt(const struct option *opt, const char *arg, int unset);
166 static int parse_nodes_opt(const struct option *opt, const char *arg, int unset);
167 
168 struct params p0;
169 
170 static const struct option options[] = {
171 	OPT_INTEGER('p', "nr_proc"	, &p0.nr_proc,		"number of processes"),
172 	OPT_INTEGER('t', "nr_threads"	, &p0.nr_threads,	"number of threads per process"),
173 
174 	OPT_STRING('G', "mb_global"	, &p0.mb_global_str,	"MB", "global  memory (MBs)"),
175 	OPT_STRING('P', "mb_proc"	, &p0.mb_proc_str,	"MB", "process memory (MBs)"),
176 	OPT_STRING('L', "mb_proc_locked", &p0.mb_proc_locked_str,"MB", "process serialized/locked memory access (MBs), <= process_memory"),
177 	OPT_STRING('T', "mb_thread"	, &p0.mb_thread_str,	"MB", "thread  memory (MBs)"),
178 
179 	OPT_UINTEGER('l', "nr_loops"	, &p0.nr_loops,		"max number of loops to run (default: unlimited)"),
180 	OPT_UINTEGER('s', "nr_secs"	, &p0.nr_secs,		"max number of seconds to run (default: 5 secs)"),
181 	OPT_UINTEGER('u', "usleep"	, &p0.sleep_usecs,	"usecs to sleep per loop iteration"),
182 
183 	OPT_BOOLEAN('R', "data_reads"	, &p0.data_reads,	"access the data via reads (can be mixed with -W)"),
184 	OPT_BOOLEAN('W', "data_writes"	, &p0.data_writes,	"access the data via writes (can be mixed with -R)"),
185 	OPT_BOOLEAN('B', "data_backwards", &p0.data_backwards,	"access the data backwards as well"),
186 	OPT_BOOLEAN('Z', "data_zero_memset", &p0.data_zero_memset,"access the data via glibc bzero only"),
187 	OPT_BOOLEAN('r', "data_rand_walk", &p0.data_rand_walk,	"access the data with random (32bit LFSR) walk"),
188 
189 
190 	OPT_BOOLEAN('z', "init_zero"	, &p0.init_zero,	"bzero the initial allocations"),
191 	OPT_BOOLEAN('I', "init_random"	, &p0.init_random,	"randomize the contents of the initial allocations"),
192 	OPT_BOOLEAN('0', "init_cpu0"	, &p0.init_cpu0,	"do the initial allocations on CPU#0"),
193 	OPT_INTEGER('x', "perturb_secs", &p0.perturb_secs,	"perturb thread 0/0 every X secs, to test convergence stability"),
194 
195 	OPT_INCR   ('d', "show_details"	, &p0.show_details,	"Show details"),
196 	OPT_INCR   ('a', "all"		, &p0.run_all,		"Run all tests in the suite"),
197 	OPT_INTEGER('H', "thp"		, &p0.thp,		"MADV_NOHUGEPAGE < 0 < MADV_HUGEPAGE"),
198 	OPT_BOOLEAN('c', "show_convergence", &p0.show_convergence, "show convergence details, "
199 		    "convergence is reached when each process (all its threads) is running on a single NUMA node."),
200 	OPT_BOOLEAN('m', "measure_convergence",	&p0.measure_convergence, "measure convergence latency"),
201 	OPT_BOOLEAN('q', "quiet"	, &p0.show_quiet,	"quiet mode"),
202 	OPT_BOOLEAN('S', "serialize-startup", &p0.serialize_startup,"serialize thread startup"),
203 
204 	/* Special option string parsing callbacks: */
205         OPT_CALLBACK('C', "cpus", NULL, "cpu[,cpu2,...cpuN]",
206 			"bind the first N tasks to these specific cpus (the rest is unbound)",
207 			parse_cpus_opt),
208         OPT_CALLBACK('M', "memnodes", NULL, "node[,node2,...nodeN]",
209 			"bind the first N tasks to these specific memory nodes (the rest is unbound)",
210 			parse_nodes_opt),
211 	OPT_END()
212 };
213 
214 static const char * const bench_numa_usage[] = {
215 	"perf bench numa <options>",
216 	NULL
217 };
218 
219 static const char * const numa_usage[] = {
220 	"perf bench numa mem [<options>]",
221 	NULL
222 };
223 
224 /*
225  * To get number of numa nodes present.
226  */
227 static int nr_numa_nodes(void)
228 {
229 	int i, nr_nodes = 0;
230 
231 	for (i = 0; i < g->p.nr_nodes; i++) {
232 		if (numa_bitmask_isbitset(numa_nodes_ptr, i))
233 			nr_nodes++;
234 	}
235 
236 	return nr_nodes;
237 }
238 
239 /*
240  * To check if given numa node is present.
241  */
242 static int is_node_present(int node)
243 {
244 	return numa_bitmask_isbitset(numa_nodes_ptr, node);
245 }
246 
247 /*
248  * To check given numa node has cpus.
249  */
250 static bool node_has_cpus(int node)
251 {
252 	struct bitmask *cpu = numa_allocate_cpumask();
253 	unsigned int i;
254 
255 	if (cpu && !numa_node_to_cpus(node, cpu)) {
256 		for (i = 0; i < cpu->size; i++) {
257 			if (numa_bitmask_isbitset(cpu, i))
258 				return true;
259 		}
260 	}
261 
262 	return false; /* lets fall back to nocpus safely */
263 }
264 
265 static cpu_set_t bind_to_cpu(int target_cpu)
266 {
267 	cpu_set_t orig_mask, mask;
268 	int ret;
269 
270 	ret = sched_getaffinity(0, sizeof(orig_mask), &orig_mask);
271 	BUG_ON(ret);
272 
273 	CPU_ZERO(&mask);
274 
275 	if (target_cpu == -1) {
276 		int cpu;
277 
278 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
279 			CPU_SET(cpu, &mask);
280 	} else {
281 		BUG_ON(target_cpu < 0 || target_cpu >= g->p.nr_cpus);
282 		CPU_SET(target_cpu, &mask);
283 	}
284 
285 	ret = sched_setaffinity(0, sizeof(mask), &mask);
286 	BUG_ON(ret);
287 
288 	return orig_mask;
289 }
290 
291 static cpu_set_t bind_to_node(int target_node)
292 {
293 	int cpus_per_node = g->p.nr_cpus / nr_numa_nodes();
294 	cpu_set_t orig_mask, mask;
295 	int cpu;
296 	int ret;
297 
298 	BUG_ON(cpus_per_node * nr_numa_nodes() != g->p.nr_cpus);
299 	BUG_ON(!cpus_per_node);
300 
301 	ret = sched_getaffinity(0, sizeof(orig_mask), &orig_mask);
302 	BUG_ON(ret);
303 
304 	CPU_ZERO(&mask);
305 
306 	if (target_node == NUMA_NO_NODE) {
307 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
308 			CPU_SET(cpu, &mask);
309 	} else {
310 		int cpu_start = (target_node + 0) * cpus_per_node;
311 		int cpu_stop  = (target_node + 1) * cpus_per_node;
312 
313 		BUG_ON(cpu_stop > g->p.nr_cpus);
314 
315 		for (cpu = cpu_start; cpu < cpu_stop; cpu++)
316 			CPU_SET(cpu, &mask);
317 	}
318 
319 	ret = sched_setaffinity(0, sizeof(mask), &mask);
320 	BUG_ON(ret);
321 
322 	return orig_mask;
323 }
324 
325 static void bind_to_cpumask(cpu_set_t mask)
326 {
327 	int ret;
328 
329 	ret = sched_setaffinity(0, sizeof(mask), &mask);
330 	BUG_ON(ret);
331 }
332 
333 static void mempol_restore(void)
334 {
335 	int ret;
336 
337 	ret = set_mempolicy(MPOL_DEFAULT, NULL, g->p.nr_nodes-1);
338 
339 	BUG_ON(ret);
340 }
341 
342 static void bind_to_memnode(int node)
343 {
344 	unsigned long nodemask;
345 	int ret;
346 
347 	if (node == NUMA_NO_NODE)
348 		return;
349 
350 	BUG_ON(g->p.nr_nodes > (int)sizeof(nodemask)*8);
351 	nodemask = 1L << node;
352 
353 	ret = set_mempolicy(MPOL_BIND, &nodemask, sizeof(nodemask)*8);
354 	dprintf("binding to node %d, mask: %016lx => %d\n", node, nodemask, ret);
355 
356 	BUG_ON(ret);
357 }
358 
359 #define HPSIZE (2*1024*1024)
360 
361 #define set_taskname(fmt...)				\
362 do {							\
363 	char name[20];					\
364 							\
365 	snprintf(name, 20, fmt);			\
366 	prctl(PR_SET_NAME, name);			\
367 } while (0)
368 
369 static u8 *alloc_data(ssize_t bytes0, int map_flags,
370 		      int init_zero, int init_cpu0, int thp, int init_random)
371 {
372 	cpu_set_t orig_mask;
373 	ssize_t bytes;
374 	u8 *buf;
375 	int ret;
376 
377 	if (!bytes0)
378 		return NULL;
379 
380 	/* Allocate and initialize all memory on CPU#0: */
381 	if (init_cpu0) {
382 		int node = numa_node_of_cpu(0);
383 
384 		orig_mask = bind_to_node(node);
385 		bind_to_memnode(node);
386 	}
387 
388 	bytes = bytes0 + HPSIZE;
389 
390 	buf = (void *)mmap(0, bytes, PROT_READ|PROT_WRITE, MAP_ANON|map_flags, -1, 0);
391 	BUG_ON(buf == (void *)-1);
392 
393 	if (map_flags == MAP_PRIVATE) {
394 		if (thp > 0) {
395 			ret = madvise(buf, bytes, MADV_HUGEPAGE);
396 			if (ret && !g->print_once) {
397 				g->print_once = 1;
398 				printf("WARNING: Could not enable THP - do: 'echo madvise > /sys/kernel/mm/transparent_hugepage/enabled'\n");
399 			}
400 		}
401 		if (thp < 0) {
402 			ret = madvise(buf, bytes, MADV_NOHUGEPAGE);
403 			if (ret && !g->print_once) {
404 				g->print_once = 1;
405 				printf("WARNING: Could not disable THP: run a CONFIG_TRANSPARENT_HUGEPAGE kernel?\n");
406 			}
407 		}
408 	}
409 
410 	if (init_zero) {
411 		bzero(buf, bytes);
412 	} else {
413 		/* Initialize random contents, different in each word: */
414 		if (init_random) {
415 			u64 *wbuf = (void *)buf;
416 			long off = rand();
417 			long i;
418 
419 			for (i = 0; i < bytes/8; i++)
420 				wbuf[i] = i + off;
421 		}
422 	}
423 
424 	/* Align to 2MB boundary: */
425 	buf = (void *)(((unsigned long)buf + HPSIZE-1) & ~(HPSIZE-1));
426 
427 	/* Restore affinity: */
428 	if (init_cpu0) {
429 		bind_to_cpumask(orig_mask);
430 		mempol_restore();
431 	}
432 
433 	return buf;
434 }
435 
436 static void free_data(void *data, ssize_t bytes)
437 {
438 	int ret;
439 
440 	if (!data)
441 		return;
442 
443 	ret = munmap(data, bytes);
444 	BUG_ON(ret);
445 }
446 
447 /*
448  * Create a shared memory buffer that can be shared between processes, zeroed:
449  */
450 static void * zalloc_shared_data(ssize_t bytes)
451 {
452 	return alloc_data(bytes, MAP_SHARED, 1, g->p.init_cpu0,  g->p.thp, g->p.init_random);
453 }
454 
455 /*
456  * Create a shared memory buffer that can be shared between processes:
457  */
458 static void * setup_shared_data(ssize_t bytes)
459 {
460 	return alloc_data(bytes, MAP_SHARED, 0, g->p.init_cpu0,  g->p.thp, g->p.init_random);
461 }
462 
463 /*
464  * Allocate process-local memory - this will either be shared between
465  * threads of this process, or only be accessed by this thread:
466  */
467 static void * setup_private_data(ssize_t bytes)
468 {
469 	return alloc_data(bytes, MAP_PRIVATE, 0, g->p.init_cpu0,  g->p.thp, g->p.init_random);
470 }
471 
472 /*
473  * Return a process-shared (global) mutex:
474  */
475 static void init_global_mutex(pthread_mutex_t *mutex)
476 {
477 	pthread_mutexattr_t attr;
478 
479 	pthread_mutexattr_init(&attr);
480 	pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
481 	pthread_mutex_init(mutex, &attr);
482 }
483 
484 static int parse_cpu_list(const char *arg)
485 {
486 	p0.cpu_list_str = strdup(arg);
487 
488 	dprintf("got CPU list: {%s}\n", p0.cpu_list_str);
489 
490 	return 0;
491 }
492 
493 static int parse_setup_cpu_list(void)
494 {
495 	struct thread_data *td;
496 	char *str0, *str;
497 	int t;
498 
499 	if (!g->p.cpu_list_str)
500 		return 0;
501 
502 	dprintf("g->p.nr_tasks: %d\n", g->p.nr_tasks);
503 
504 	str0 = str = strdup(g->p.cpu_list_str);
505 	t = 0;
506 
507 	BUG_ON(!str);
508 
509 	tprintf("# binding tasks to CPUs:\n");
510 	tprintf("#  ");
511 
512 	while (true) {
513 		int bind_cpu, bind_cpu_0, bind_cpu_1;
514 		char *tok, *tok_end, *tok_step, *tok_len, *tok_mul;
515 		int bind_len;
516 		int step;
517 		int mul;
518 
519 		tok = strsep(&str, ",");
520 		if (!tok)
521 			break;
522 
523 		tok_end = strstr(tok, "-");
524 
525 		dprintf("\ntoken: {%s}, end: {%s}\n", tok, tok_end);
526 		if (!tok_end) {
527 			/* Single CPU specified: */
528 			bind_cpu_0 = bind_cpu_1 = atol(tok);
529 		} else {
530 			/* CPU range specified (for example: "5-11"): */
531 			bind_cpu_0 = atol(tok);
532 			bind_cpu_1 = atol(tok_end + 1);
533 		}
534 
535 		step = 1;
536 		tok_step = strstr(tok, "#");
537 		if (tok_step) {
538 			step = atol(tok_step + 1);
539 			BUG_ON(step <= 0 || step >= g->p.nr_cpus);
540 		}
541 
542 		/*
543 		 * Mask length.
544 		 * Eg: "--cpus 8_4-16#4" means: '--cpus 8_4,12_4,16_4',
545 		 * where the _4 means the next 4 CPUs are allowed.
546 		 */
547 		bind_len = 1;
548 		tok_len = strstr(tok, "_");
549 		if (tok_len) {
550 			bind_len = atol(tok_len + 1);
551 			BUG_ON(bind_len <= 0 || bind_len > g->p.nr_cpus);
552 		}
553 
554 		/* Multiplicator shortcut, "0x8" is a shortcut for: "0,0,0,0,0,0,0,0" */
555 		mul = 1;
556 		tok_mul = strstr(tok, "x");
557 		if (tok_mul) {
558 			mul = atol(tok_mul + 1);
559 			BUG_ON(mul <= 0);
560 		}
561 
562 		dprintf("CPUs: %d_%d-%d#%dx%d\n", bind_cpu_0, bind_len, bind_cpu_1, step, mul);
563 
564 		if (bind_cpu_0 >= g->p.nr_cpus || bind_cpu_1 >= g->p.nr_cpus) {
565 			printf("\nTest not applicable, system has only %d CPUs.\n", g->p.nr_cpus);
566 			return -1;
567 		}
568 
569 		BUG_ON(bind_cpu_0 < 0 || bind_cpu_1 < 0);
570 		BUG_ON(bind_cpu_0 > bind_cpu_1);
571 
572 		for (bind_cpu = bind_cpu_0; bind_cpu <= bind_cpu_1; bind_cpu += step) {
573 			int i;
574 
575 			for (i = 0; i < mul; i++) {
576 				int cpu;
577 
578 				if (t >= g->p.nr_tasks) {
579 					printf("\n# NOTE: ignoring bind CPUs starting at CPU#%d\n #", bind_cpu);
580 					goto out;
581 				}
582 				td = g->threads + t;
583 
584 				if (t)
585 					tprintf(",");
586 				if (bind_len > 1) {
587 					tprintf("%2d/%d", bind_cpu, bind_len);
588 				} else {
589 					tprintf("%2d", bind_cpu);
590 				}
591 
592 				CPU_ZERO(&td->bind_cpumask);
593 				for (cpu = bind_cpu; cpu < bind_cpu+bind_len; cpu++) {
594 					BUG_ON(cpu < 0 || cpu >= g->p.nr_cpus);
595 					CPU_SET(cpu, &td->bind_cpumask);
596 				}
597 				t++;
598 			}
599 		}
600 	}
601 out:
602 
603 	tprintf("\n");
604 
605 	if (t < g->p.nr_tasks)
606 		printf("# NOTE: %d tasks bound, %d tasks unbound\n", t, g->p.nr_tasks - t);
607 
608 	free(str0);
609 	return 0;
610 }
611 
612 static int parse_cpus_opt(const struct option *opt __maybe_unused,
613 			  const char *arg, int unset __maybe_unused)
614 {
615 	if (!arg)
616 		return -1;
617 
618 	return parse_cpu_list(arg);
619 }
620 
621 static int parse_node_list(const char *arg)
622 {
623 	p0.node_list_str = strdup(arg);
624 
625 	dprintf("got NODE list: {%s}\n", p0.node_list_str);
626 
627 	return 0;
628 }
629 
630 static int parse_setup_node_list(void)
631 {
632 	struct thread_data *td;
633 	char *str0, *str;
634 	int t;
635 
636 	if (!g->p.node_list_str)
637 		return 0;
638 
639 	dprintf("g->p.nr_tasks: %d\n", g->p.nr_tasks);
640 
641 	str0 = str = strdup(g->p.node_list_str);
642 	t = 0;
643 
644 	BUG_ON(!str);
645 
646 	tprintf("# binding tasks to NODEs:\n");
647 	tprintf("# ");
648 
649 	while (true) {
650 		int bind_node, bind_node_0, bind_node_1;
651 		char *tok, *tok_end, *tok_step, *tok_mul;
652 		int step;
653 		int mul;
654 
655 		tok = strsep(&str, ",");
656 		if (!tok)
657 			break;
658 
659 		tok_end = strstr(tok, "-");
660 
661 		dprintf("\ntoken: {%s}, end: {%s}\n", tok, tok_end);
662 		if (!tok_end) {
663 			/* Single NODE specified: */
664 			bind_node_0 = bind_node_1 = atol(tok);
665 		} else {
666 			/* NODE range specified (for example: "5-11"): */
667 			bind_node_0 = atol(tok);
668 			bind_node_1 = atol(tok_end + 1);
669 		}
670 
671 		step = 1;
672 		tok_step = strstr(tok, "#");
673 		if (tok_step) {
674 			step = atol(tok_step + 1);
675 			BUG_ON(step <= 0 || step >= g->p.nr_nodes);
676 		}
677 
678 		/* Multiplicator shortcut, "0x8" is a shortcut for: "0,0,0,0,0,0,0,0" */
679 		mul = 1;
680 		tok_mul = strstr(tok, "x");
681 		if (tok_mul) {
682 			mul = atol(tok_mul + 1);
683 			BUG_ON(mul <= 0);
684 		}
685 
686 		dprintf("NODEs: %d-%d #%d\n", bind_node_0, bind_node_1, step);
687 
688 		if (bind_node_0 >= g->p.nr_nodes || bind_node_1 >= g->p.nr_nodes) {
689 			printf("\nTest not applicable, system has only %d nodes.\n", g->p.nr_nodes);
690 			return -1;
691 		}
692 
693 		BUG_ON(bind_node_0 < 0 || bind_node_1 < 0);
694 		BUG_ON(bind_node_0 > bind_node_1);
695 
696 		for (bind_node = bind_node_0; bind_node <= bind_node_1; bind_node += step) {
697 			int i;
698 
699 			for (i = 0; i < mul; i++) {
700 				if (t >= g->p.nr_tasks || !node_has_cpus(bind_node)) {
701 					printf("\n# NOTE: ignoring bind NODEs starting at NODE#%d\n", bind_node);
702 					goto out;
703 				}
704 				td = g->threads + t;
705 
706 				if (!t)
707 					tprintf(" %2d", bind_node);
708 				else
709 					tprintf(",%2d", bind_node);
710 
711 				td->bind_node = bind_node;
712 				t++;
713 			}
714 		}
715 	}
716 out:
717 
718 	tprintf("\n");
719 
720 	if (t < g->p.nr_tasks)
721 		printf("# NOTE: %d tasks mem-bound, %d tasks unbound\n", t, g->p.nr_tasks - t);
722 
723 	free(str0);
724 	return 0;
725 }
726 
727 static int parse_nodes_opt(const struct option *opt __maybe_unused,
728 			  const char *arg, int unset __maybe_unused)
729 {
730 	if (!arg)
731 		return -1;
732 
733 	return parse_node_list(arg);
734 
735 	return 0;
736 }
737 
738 #define BIT(x) (1ul << x)
739 
740 static inline uint32_t lfsr_32(uint32_t lfsr)
741 {
742 	const uint32_t taps = BIT(1) | BIT(5) | BIT(6) | BIT(31);
743 	return (lfsr>>1) ^ ((0x0u - (lfsr & 0x1u)) & taps);
744 }
745 
746 /*
747  * Make sure there's real data dependency to RAM (when read
748  * accesses are enabled), so the compiler, the CPU and the
749  * kernel (KSM, zero page, etc.) cannot optimize away RAM
750  * accesses:
751  */
752 static inline u64 access_data(u64 *data, u64 val)
753 {
754 	if (g->p.data_reads)
755 		val += *data;
756 	if (g->p.data_writes)
757 		*data = val + 1;
758 	return val;
759 }
760 
761 /*
762  * The worker process does two types of work, a forwards going
763  * loop and a backwards going loop.
764  *
765  * We do this so that on multiprocessor systems we do not create
766  * a 'train' of processing, with highly synchronized processes,
767  * skewing the whole benchmark.
768  */
769 static u64 do_work(u8 *__data, long bytes, int nr, int nr_max, int loop, u64 val)
770 {
771 	long words = bytes/sizeof(u64);
772 	u64 *data = (void *)__data;
773 	long chunk_0, chunk_1;
774 	u64 *d0, *d, *d1;
775 	long off;
776 	long i;
777 
778 	BUG_ON(!data && words);
779 	BUG_ON(data && !words);
780 
781 	if (!data)
782 		return val;
783 
784 	/* Very simple memset() work variant: */
785 	if (g->p.data_zero_memset && !g->p.data_rand_walk) {
786 		bzero(data, bytes);
787 		return val;
788 	}
789 
790 	/* Spread out by PID/TID nr and by loop nr: */
791 	chunk_0 = words/nr_max;
792 	chunk_1 = words/g->p.nr_loops;
793 	off = nr*chunk_0 + loop*chunk_1;
794 
795 	while (off >= words)
796 		off -= words;
797 
798 	if (g->p.data_rand_walk) {
799 		u32 lfsr = nr + loop + val;
800 		int j;
801 
802 		for (i = 0; i < words/1024; i++) {
803 			long start, end;
804 
805 			lfsr = lfsr_32(lfsr);
806 
807 			start = lfsr % words;
808 			end = min(start + 1024, words-1);
809 
810 			if (g->p.data_zero_memset) {
811 				bzero(data + start, (end-start) * sizeof(u64));
812 			} else {
813 				for (j = start; j < end; j++)
814 					val = access_data(data + j, val);
815 			}
816 		}
817 	} else if (!g->p.data_backwards || (nr + loop) & 1) {
818 
819 		d0 = data + off;
820 		d  = data + off + 1;
821 		d1 = data + words;
822 
823 		/* Process data forwards: */
824 		for (;;) {
825 			if (unlikely(d >= d1))
826 				d = data;
827 			if (unlikely(d == d0))
828 				break;
829 
830 			val = access_data(d, val);
831 
832 			d++;
833 		}
834 	} else {
835 		/* Process data backwards: */
836 
837 		d0 = data + off;
838 		d  = data + off - 1;
839 		d1 = data + words;
840 
841 		/* Process data forwards: */
842 		for (;;) {
843 			if (unlikely(d < data))
844 				d = data + words-1;
845 			if (unlikely(d == d0))
846 				break;
847 
848 			val = access_data(d, val);
849 
850 			d--;
851 		}
852 	}
853 
854 	return val;
855 }
856 
857 static void update_curr_cpu(int task_nr, unsigned long bytes_worked)
858 {
859 	unsigned int cpu;
860 
861 	cpu = sched_getcpu();
862 
863 	g->threads[task_nr].curr_cpu = cpu;
864 	prctl(0, bytes_worked);
865 }
866 
867 #define MAX_NR_NODES	64
868 
869 /*
870  * Count the number of nodes a process's threads
871  * are spread out on.
872  *
873  * A count of 1 means that the process is compressed
874  * to a single node. A count of g->p.nr_nodes means it's
875  * spread out on the whole system.
876  */
877 static int count_process_nodes(int process_nr)
878 {
879 	char node_present[MAX_NR_NODES] = { 0, };
880 	int nodes;
881 	int n, t;
882 
883 	for (t = 0; t < g->p.nr_threads; t++) {
884 		struct thread_data *td;
885 		int task_nr;
886 		int node;
887 
888 		task_nr = process_nr*g->p.nr_threads + t;
889 		td = g->threads + task_nr;
890 
891 		node = numa_node_of_cpu(td->curr_cpu);
892 		if (node < 0) /* curr_cpu was likely still -1 */
893 			return 0;
894 
895 		node_present[node] = 1;
896 	}
897 
898 	nodes = 0;
899 
900 	for (n = 0; n < MAX_NR_NODES; n++)
901 		nodes += node_present[n];
902 
903 	return nodes;
904 }
905 
906 /*
907  * Count the number of distinct process-threads a node contains.
908  *
909  * A count of 1 means that the node contains only a single
910  * process. If all nodes on the system contain at most one
911  * process then we are well-converged.
912  */
913 static int count_node_processes(int node)
914 {
915 	int processes = 0;
916 	int t, p;
917 
918 	for (p = 0; p < g->p.nr_proc; p++) {
919 		for (t = 0; t < g->p.nr_threads; t++) {
920 			struct thread_data *td;
921 			int task_nr;
922 			int n;
923 
924 			task_nr = p*g->p.nr_threads + t;
925 			td = g->threads + task_nr;
926 
927 			n = numa_node_of_cpu(td->curr_cpu);
928 			if (n == node) {
929 				processes++;
930 				break;
931 			}
932 		}
933 	}
934 
935 	return processes;
936 }
937 
938 static void calc_convergence_compression(int *strong)
939 {
940 	unsigned int nodes_min, nodes_max;
941 	int p;
942 
943 	nodes_min = -1;
944 	nodes_max =  0;
945 
946 	for (p = 0; p < g->p.nr_proc; p++) {
947 		unsigned int nodes = count_process_nodes(p);
948 
949 		if (!nodes) {
950 			*strong = 0;
951 			return;
952 		}
953 
954 		nodes_min = min(nodes, nodes_min);
955 		nodes_max = max(nodes, nodes_max);
956 	}
957 
958 	/* Strong convergence: all threads compress on a single node: */
959 	if (nodes_min == 1 && nodes_max == 1) {
960 		*strong = 1;
961 	} else {
962 		*strong = 0;
963 		tprintf(" {%d-%d}", nodes_min, nodes_max);
964 	}
965 }
966 
967 static void calc_convergence(double runtime_ns_max, double *convergence)
968 {
969 	unsigned int loops_done_min, loops_done_max;
970 	int process_groups;
971 	int nodes[MAX_NR_NODES];
972 	int distance;
973 	int nr_min;
974 	int nr_max;
975 	int strong;
976 	int sum;
977 	int nr;
978 	int node;
979 	int cpu;
980 	int t;
981 
982 	if (!g->p.show_convergence && !g->p.measure_convergence)
983 		return;
984 
985 	for (node = 0; node < g->p.nr_nodes; node++)
986 		nodes[node] = 0;
987 
988 	loops_done_min = -1;
989 	loops_done_max = 0;
990 
991 	for (t = 0; t < g->p.nr_tasks; t++) {
992 		struct thread_data *td = g->threads + t;
993 		unsigned int loops_done;
994 
995 		cpu = td->curr_cpu;
996 
997 		/* Not all threads have written it yet: */
998 		if (cpu < 0)
999 			continue;
1000 
1001 		node = numa_node_of_cpu(cpu);
1002 
1003 		nodes[node]++;
1004 
1005 		loops_done = td->loops_done;
1006 		loops_done_min = min(loops_done, loops_done_min);
1007 		loops_done_max = max(loops_done, loops_done_max);
1008 	}
1009 
1010 	nr_max = 0;
1011 	nr_min = g->p.nr_tasks;
1012 	sum = 0;
1013 
1014 	for (node = 0; node < g->p.nr_nodes; node++) {
1015 		if (!is_node_present(node))
1016 			continue;
1017 		nr = nodes[node];
1018 		nr_min = min(nr, nr_min);
1019 		nr_max = max(nr, nr_max);
1020 		sum += nr;
1021 	}
1022 	BUG_ON(nr_min > nr_max);
1023 
1024 	BUG_ON(sum > g->p.nr_tasks);
1025 
1026 	if (0 && (sum < g->p.nr_tasks))
1027 		return;
1028 
1029 	/*
1030 	 * Count the number of distinct process groups present
1031 	 * on nodes - when we are converged this will decrease
1032 	 * to g->p.nr_proc:
1033 	 */
1034 	process_groups = 0;
1035 
1036 	for (node = 0; node < g->p.nr_nodes; node++) {
1037 		int processes;
1038 
1039 		if (!is_node_present(node))
1040 			continue;
1041 		processes = count_node_processes(node);
1042 		nr = nodes[node];
1043 		tprintf(" %2d/%-2d", nr, processes);
1044 
1045 		process_groups += processes;
1046 	}
1047 
1048 	distance = nr_max - nr_min;
1049 
1050 	tprintf(" [%2d/%-2d]", distance, process_groups);
1051 
1052 	tprintf(" l:%3d-%-3d (%3d)",
1053 		loops_done_min, loops_done_max, loops_done_max-loops_done_min);
1054 
1055 	if (loops_done_min && loops_done_max) {
1056 		double skew = 1.0 - (double)loops_done_min/loops_done_max;
1057 
1058 		tprintf(" [%4.1f%%]", skew * 100.0);
1059 	}
1060 
1061 	calc_convergence_compression(&strong);
1062 
1063 	if (strong && process_groups == g->p.nr_proc) {
1064 		if (!*convergence) {
1065 			*convergence = runtime_ns_max;
1066 			tprintf(" (%6.1fs converged)\n", *convergence / NSEC_PER_SEC);
1067 			if (g->p.measure_convergence) {
1068 				g->all_converged = true;
1069 				g->stop_work = true;
1070 			}
1071 		}
1072 	} else {
1073 		if (*convergence) {
1074 			tprintf(" (%6.1fs de-converged)", runtime_ns_max / NSEC_PER_SEC);
1075 			*convergence = 0;
1076 		}
1077 		tprintf("\n");
1078 	}
1079 }
1080 
1081 static void show_summary(double runtime_ns_max, int l, double *convergence)
1082 {
1083 	tprintf("\r #  %5.1f%%  [%.1f mins]",
1084 		(double)(l+1)/g->p.nr_loops*100.0, runtime_ns_max / NSEC_PER_SEC / 60.0);
1085 
1086 	calc_convergence(runtime_ns_max, convergence);
1087 
1088 	if (g->p.show_details >= 0)
1089 		fflush(stdout);
1090 }
1091 
1092 static void *worker_thread(void *__tdata)
1093 {
1094 	struct thread_data *td = __tdata;
1095 	struct timeval start0, start, stop, diff;
1096 	int process_nr = td->process_nr;
1097 	int thread_nr = td->thread_nr;
1098 	unsigned long last_perturbance;
1099 	int task_nr = td->task_nr;
1100 	int details = g->p.show_details;
1101 	int first_task, last_task;
1102 	double convergence = 0;
1103 	u64 val = td->val;
1104 	double runtime_ns_max;
1105 	u8 *global_data;
1106 	u8 *process_data;
1107 	u8 *thread_data;
1108 	u64 bytes_done, secs;
1109 	long work_done;
1110 	u32 l;
1111 	struct rusage rusage;
1112 
1113 	bind_to_cpumask(td->bind_cpumask);
1114 	bind_to_memnode(td->bind_node);
1115 
1116 	set_taskname("thread %d/%d", process_nr, thread_nr);
1117 
1118 	global_data = g->data;
1119 	process_data = td->process_data;
1120 	thread_data = setup_private_data(g->p.bytes_thread);
1121 
1122 	bytes_done = 0;
1123 
1124 	last_task = 0;
1125 	if (process_nr == g->p.nr_proc-1 && thread_nr == g->p.nr_threads-1)
1126 		last_task = 1;
1127 
1128 	first_task = 0;
1129 	if (process_nr == 0 && thread_nr == 0)
1130 		first_task = 1;
1131 
1132 	if (details >= 2) {
1133 		printf("#  thread %2d / %2d global mem: %p, process mem: %p, thread mem: %p\n",
1134 			process_nr, thread_nr, global_data, process_data, thread_data);
1135 	}
1136 
1137 	if (g->p.serialize_startup) {
1138 		pthread_mutex_lock(&g->startup_mutex);
1139 		g->nr_tasks_started++;
1140 		pthread_mutex_unlock(&g->startup_mutex);
1141 
1142 		/* Here we will wait for the main process to start us all at once: */
1143 		pthread_mutex_lock(&g->start_work_mutex);
1144 		g->nr_tasks_working++;
1145 
1146 		/* Last one wake the main process: */
1147 		if (g->nr_tasks_working == g->p.nr_tasks)
1148 			pthread_mutex_unlock(&g->startup_done_mutex);
1149 
1150 		pthread_mutex_unlock(&g->start_work_mutex);
1151 	}
1152 
1153 	gettimeofday(&start0, NULL);
1154 
1155 	start = stop = start0;
1156 	last_perturbance = start.tv_sec;
1157 
1158 	for (l = 0; l < g->p.nr_loops; l++) {
1159 		start = stop;
1160 
1161 		if (g->stop_work)
1162 			break;
1163 
1164 		val += do_work(global_data,  g->p.bytes_global,  process_nr, g->p.nr_proc,	l, val);
1165 		val += do_work(process_data, g->p.bytes_process, thread_nr,  g->p.nr_threads,	l, val);
1166 		val += do_work(thread_data,  g->p.bytes_thread,  0,          1,		l, val);
1167 
1168 		if (g->p.sleep_usecs) {
1169 			pthread_mutex_lock(td->process_lock);
1170 			usleep(g->p.sleep_usecs);
1171 			pthread_mutex_unlock(td->process_lock);
1172 		}
1173 		/*
1174 		 * Amount of work to be done under a process-global lock:
1175 		 */
1176 		if (g->p.bytes_process_locked) {
1177 			pthread_mutex_lock(td->process_lock);
1178 			val += do_work(process_data, g->p.bytes_process_locked, thread_nr,  g->p.nr_threads,	l, val);
1179 			pthread_mutex_unlock(td->process_lock);
1180 		}
1181 
1182 		work_done = g->p.bytes_global + g->p.bytes_process +
1183 			    g->p.bytes_process_locked + g->p.bytes_thread;
1184 
1185 		update_curr_cpu(task_nr, work_done);
1186 		bytes_done += work_done;
1187 
1188 		if (details < 0 && !g->p.perturb_secs && !g->p.measure_convergence && !g->p.nr_secs)
1189 			continue;
1190 
1191 		td->loops_done = l;
1192 
1193 		gettimeofday(&stop, NULL);
1194 
1195 		/* Check whether our max runtime timed out: */
1196 		if (g->p.nr_secs) {
1197 			timersub(&stop, &start0, &diff);
1198 			if ((u32)diff.tv_sec >= g->p.nr_secs) {
1199 				g->stop_work = true;
1200 				break;
1201 			}
1202 		}
1203 
1204 		/* Update the summary at most once per second: */
1205 		if (start.tv_sec == stop.tv_sec)
1206 			continue;
1207 
1208 		/*
1209 		 * Perturb the first task's equilibrium every g->p.perturb_secs seconds,
1210 		 * by migrating to CPU#0:
1211 		 */
1212 		if (first_task && g->p.perturb_secs && (int)(stop.tv_sec - last_perturbance) >= g->p.perturb_secs) {
1213 			cpu_set_t orig_mask;
1214 			int target_cpu;
1215 			int this_cpu;
1216 
1217 			last_perturbance = stop.tv_sec;
1218 
1219 			/*
1220 			 * Depending on where we are running, move into
1221 			 * the other half of the system, to create some
1222 			 * real disturbance:
1223 			 */
1224 			this_cpu = g->threads[task_nr].curr_cpu;
1225 			if (this_cpu < g->p.nr_cpus/2)
1226 				target_cpu = g->p.nr_cpus-1;
1227 			else
1228 				target_cpu = 0;
1229 
1230 			orig_mask = bind_to_cpu(target_cpu);
1231 
1232 			/* Here we are running on the target CPU already */
1233 			if (details >= 1)
1234 				printf(" (injecting perturbalance, moved to CPU#%d)\n", target_cpu);
1235 
1236 			bind_to_cpumask(orig_mask);
1237 		}
1238 
1239 		if (details >= 3) {
1240 			timersub(&stop, &start, &diff);
1241 			runtime_ns_max = diff.tv_sec * NSEC_PER_SEC;
1242 			runtime_ns_max += diff.tv_usec * NSEC_PER_USEC;
1243 
1244 			if (details >= 0) {
1245 				printf(" #%2d / %2d: %14.2lf nsecs/op [val: %016"PRIx64"]\n",
1246 					process_nr, thread_nr, runtime_ns_max / bytes_done, val);
1247 			}
1248 			fflush(stdout);
1249 		}
1250 		if (!last_task)
1251 			continue;
1252 
1253 		timersub(&stop, &start0, &diff);
1254 		runtime_ns_max = diff.tv_sec * NSEC_PER_SEC;
1255 		runtime_ns_max += diff.tv_usec * NSEC_PER_USEC;
1256 
1257 		show_summary(runtime_ns_max, l, &convergence);
1258 	}
1259 
1260 	gettimeofday(&stop, NULL);
1261 	timersub(&stop, &start0, &diff);
1262 	td->runtime_ns = diff.tv_sec * NSEC_PER_SEC;
1263 	td->runtime_ns += diff.tv_usec * NSEC_PER_USEC;
1264 	secs = td->runtime_ns / NSEC_PER_SEC;
1265 	td->speed_gbs = secs ? bytes_done / secs / 1e9 : 0;
1266 
1267 	getrusage(RUSAGE_THREAD, &rusage);
1268 	td->system_time_ns = rusage.ru_stime.tv_sec * NSEC_PER_SEC;
1269 	td->system_time_ns += rusage.ru_stime.tv_usec * NSEC_PER_USEC;
1270 	td->user_time_ns = rusage.ru_utime.tv_sec * NSEC_PER_SEC;
1271 	td->user_time_ns += rusage.ru_utime.tv_usec * NSEC_PER_USEC;
1272 
1273 	free_data(thread_data, g->p.bytes_thread);
1274 
1275 	pthread_mutex_lock(&g->stop_work_mutex);
1276 	g->bytes_done += bytes_done;
1277 	pthread_mutex_unlock(&g->stop_work_mutex);
1278 
1279 	return NULL;
1280 }
1281 
1282 /*
1283  * A worker process starts a couple of threads:
1284  */
1285 static void worker_process(int process_nr)
1286 {
1287 	pthread_mutex_t process_lock;
1288 	struct thread_data *td;
1289 	pthread_t *pthreads;
1290 	u8 *process_data;
1291 	int task_nr;
1292 	int ret;
1293 	int t;
1294 
1295 	pthread_mutex_init(&process_lock, NULL);
1296 	set_taskname("process %d", process_nr);
1297 
1298 	/*
1299 	 * Pick up the memory policy and the CPU binding of our first thread,
1300 	 * so that we initialize memory accordingly:
1301 	 */
1302 	task_nr = process_nr*g->p.nr_threads;
1303 	td = g->threads + task_nr;
1304 
1305 	bind_to_memnode(td->bind_node);
1306 	bind_to_cpumask(td->bind_cpumask);
1307 
1308 	pthreads = zalloc(g->p.nr_threads * sizeof(pthread_t));
1309 	process_data = setup_private_data(g->p.bytes_process);
1310 
1311 	if (g->p.show_details >= 3) {
1312 		printf(" # process %2d global mem: %p, process mem: %p\n",
1313 			process_nr, g->data, process_data);
1314 	}
1315 
1316 	for (t = 0; t < g->p.nr_threads; t++) {
1317 		task_nr = process_nr*g->p.nr_threads + t;
1318 		td = g->threads + task_nr;
1319 
1320 		td->process_data = process_data;
1321 		td->process_nr   = process_nr;
1322 		td->thread_nr    = t;
1323 		td->task_nr	 = task_nr;
1324 		td->val          = rand();
1325 		td->curr_cpu	 = -1;
1326 		td->process_lock = &process_lock;
1327 
1328 		ret = pthread_create(pthreads + t, NULL, worker_thread, td);
1329 		BUG_ON(ret);
1330 	}
1331 
1332 	for (t = 0; t < g->p.nr_threads; t++) {
1333                 ret = pthread_join(pthreads[t], NULL);
1334 		BUG_ON(ret);
1335 	}
1336 
1337 	free_data(process_data, g->p.bytes_process);
1338 	free(pthreads);
1339 }
1340 
1341 static void print_summary(void)
1342 {
1343 	if (g->p.show_details < 0)
1344 		return;
1345 
1346 	printf("\n ###\n");
1347 	printf(" # %d %s will execute (on %d nodes, %d CPUs):\n",
1348 		g->p.nr_tasks, g->p.nr_tasks == 1 ? "task" : "tasks", nr_numa_nodes(), g->p.nr_cpus);
1349 	printf(" #      %5dx %5ldMB global  shared mem operations\n",
1350 			g->p.nr_loops, g->p.bytes_global/1024/1024);
1351 	printf(" #      %5dx %5ldMB process shared mem operations\n",
1352 			g->p.nr_loops, g->p.bytes_process/1024/1024);
1353 	printf(" #      %5dx %5ldMB thread  local  mem operations\n",
1354 			g->p.nr_loops, g->p.bytes_thread/1024/1024);
1355 
1356 	printf(" ###\n");
1357 
1358 	printf("\n ###\n"); fflush(stdout);
1359 }
1360 
1361 static void init_thread_data(void)
1362 {
1363 	ssize_t size = sizeof(*g->threads)*g->p.nr_tasks;
1364 	int t;
1365 
1366 	g->threads = zalloc_shared_data(size);
1367 
1368 	for (t = 0; t < g->p.nr_tasks; t++) {
1369 		struct thread_data *td = g->threads + t;
1370 		int cpu;
1371 
1372 		/* Allow all nodes by default: */
1373 		td->bind_node = NUMA_NO_NODE;
1374 
1375 		/* Allow all CPUs by default: */
1376 		CPU_ZERO(&td->bind_cpumask);
1377 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
1378 			CPU_SET(cpu, &td->bind_cpumask);
1379 	}
1380 }
1381 
1382 static void deinit_thread_data(void)
1383 {
1384 	ssize_t size = sizeof(*g->threads)*g->p.nr_tasks;
1385 
1386 	free_data(g->threads, size);
1387 }
1388 
1389 static int init(void)
1390 {
1391 	g = (void *)alloc_data(sizeof(*g), MAP_SHARED, 1, 0, 0 /* THP */, 0);
1392 
1393 	/* Copy over options: */
1394 	g->p = p0;
1395 
1396 	g->p.nr_cpus = numa_num_configured_cpus();
1397 
1398 	g->p.nr_nodes = numa_max_node() + 1;
1399 
1400 	/* char array in count_process_nodes(): */
1401 	BUG_ON(g->p.nr_nodes > MAX_NR_NODES || g->p.nr_nodes < 0);
1402 
1403 	if (g->p.show_quiet && !g->p.show_details)
1404 		g->p.show_details = -1;
1405 
1406 	/* Some memory should be specified: */
1407 	if (!g->p.mb_global_str && !g->p.mb_proc_str && !g->p.mb_thread_str)
1408 		return -1;
1409 
1410 	if (g->p.mb_global_str) {
1411 		g->p.mb_global = atof(g->p.mb_global_str);
1412 		BUG_ON(g->p.mb_global < 0);
1413 	}
1414 
1415 	if (g->p.mb_proc_str) {
1416 		g->p.mb_proc = atof(g->p.mb_proc_str);
1417 		BUG_ON(g->p.mb_proc < 0);
1418 	}
1419 
1420 	if (g->p.mb_proc_locked_str) {
1421 		g->p.mb_proc_locked = atof(g->p.mb_proc_locked_str);
1422 		BUG_ON(g->p.mb_proc_locked < 0);
1423 		BUG_ON(g->p.mb_proc_locked > g->p.mb_proc);
1424 	}
1425 
1426 	if (g->p.mb_thread_str) {
1427 		g->p.mb_thread = atof(g->p.mb_thread_str);
1428 		BUG_ON(g->p.mb_thread < 0);
1429 	}
1430 
1431 	BUG_ON(g->p.nr_threads <= 0);
1432 	BUG_ON(g->p.nr_proc <= 0);
1433 
1434 	g->p.nr_tasks = g->p.nr_proc*g->p.nr_threads;
1435 
1436 	g->p.bytes_global		= g->p.mb_global	*1024L*1024L;
1437 	g->p.bytes_process		= g->p.mb_proc		*1024L*1024L;
1438 	g->p.bytes_process_locked	= g->p.mb_proc_locked	*1024L*1024L;
1439 	g->p.bytes_thread		= g->p.mb_thread	*1024L*1024L;
1440 
1441 	g->data = setup_shared_data(g->p.bytes_global);
1442 
1443 	/* Startup serialization: */
1444 	init_global_mutex(&g->start_work_mutex);
1445 	init_global_mutex(&g->startup_mutex);
1446 	init_global_mutex(&g->startup_done_mutex);
1447 	init_global_mutex(&g->stop_work_mutex);
1448 
1449 	init_thread_data();
1450 
1451 	tprintf("#\n");
1452 	if (parse_setup_cpu_list() || parse_setup_node_list())
1453 		return -1;
1454 	tprintf("#\n");
1455 
1456 	print_summary();
1457 
1458 	return 0;
1459 }
1460 
1461 static void deinit(void)
1462 {
1463 	free_data(g->data, g->p.bytes_global);
1464 	g->data = NULL;
1465 
1466 	deinit_thread_data();
1467 
1468 	free_data(g, sizeof(*g));
1469 	g = NULL;
1470 }
1471 
1472 /*
1473  * Print a short or long result, depending on the verbosity setting:
1474  */
1475 static void print_res(const char *name, double val,
1476 		      const char *txt_unit, const char *txt_short, const char *txt_long)
1477 {
1478 	if (!name)
1479 		name = "main,";
1480 
1481 	if (!g->p.show_quiet)
1482 		printf(" %-30s %15.3f, %-15s %s\n", name, val, txt_unit, txt_short);
1483 	else
1484 		printf(" %14.3f %s\n", val, txt_long);
1485 }
1486 
1487 static int __bench_numa(const char *name)
1488 {
1489 	struct timeval start, stop, diff;
1490 	u64 runtime_ns_min, runtime_ns_sum;
1491 	pid_t *pids, pid, wpid;
1492 	double delta_runtime;
1493 	double runtime_avg;
1494 	double runtime_sec_max;
1495 	double runtime_sec_min;
1496 	int wait_stat;
1497 	double bytes;
1498 	int i, t, p;
1499 
1500 	if (init())
1501 		return -1;
1502 
1503 	pids = zalloc(g->p.nr_proc * sizeof(*pids));
1504 	pid = -1;
1505 
1506 	/* All threads try to acquire it, this way we can wait for them to start up: */
1507 	pthread_mutex_lock(&g->start_work_mutex);
1508 
1509 	if (g->p.serialize_startup) {
1510 		tprintf(" #\n");
1511 		tprintf(" # Startup synchronization: ..."); fflush(stdout);
1512 	}
1513 
1514 	gettimeofday(&start, NULL);
1515 
1516 	for (i = 0; i < g->p.nr_proc; i++) {
1517 		pid = fork();
1518 		dprintf(" # process %2d: PID %d\n", i, pid);
1519 
1520 		BUG_ON(pid < 0);
1521 		if (!pid) {
1522 			/* Child process: */
1523 			worker_process(i);
1524 
1525 			exit(0);
1526 		}
1527 		pids[i] = pid;
1528 
1529 	}
1530 	/* Wait for all the threads to start up: */
1531 	while (g->nr_tasks_started != g->p.nr_tasks)
1532 		usleep(USEC_PER_MSEC);
1533 
1534 	BUG_ON(g->nr_tasks_started != g->p.nr_tasks);
1535 
1536 	if (g->p.serialize_startup) {
1537 		double startup_sec;
1538 
1539 		pthread_mutex_lock(&g->startup_done_mutex);
1540 
1541 		/* This will start all threads: */
1542 		pthread_mutex_unlock(&g->start_work_mutex);
1543 
1544 		/* This mutex is locked - the last started thread will wake us: */
1545 		pthread_mutex_lock(&g->startup_done_mutex);
1546 
1547 		gettimeofday(&stop, NULL);
1548 
1549 		timersub(&stop, &start, &diff);
1550 
1551 		startup_sec = diff.tv_sec * NSEC_PER_SEC;
1552 		startup_sec += diff.tv_usec * NSEC_PER_USEC;
1553 		startup_sec /= NSEC_PER_SEC;
1554 
1555 		tprintf(" threads initialized in %.6f seconds.\n", startup_sec);
1556 		tprintf(" #\n");
1557 
1558 		start = stop;
1559 		pthread_mutex_unlock(&g->startup_done_mutex);
1560 	} else {
1561 		gettimeofday(&start, NULL);
1562 	}
1563 
1564 	/* Parent process: */
1565 
1566 
1567 	for (i = 0; i < g->p.nr_proc; i++) {
1568 		wpid = waitpid(pids[i], &wait_stat, 0);
1569 		BUG_ON(wpid < 0);
1570 		BUG_ON(!WIFEXITED(wait_stat));
1571 
1572 	}
1573 
1574 	runtime_ns_sum = 0;
1575 	runtime_ns_min = -1LL;
1576 
1577 	for (t = 0; t < g->p.nr_tasks; t++) {
1578 		u64 thread_runtime_ns = g->threads[t].runtime_ns;
1579 
1580 		runtime_ns_sum += thread_runtime_ns;
1581 		runtime_ns_min = min(thread_runtime_ns, runtime_ns_min);
1582 	}
1583 
1584 	gettimeofday(&stop, NULL);
1585 	timersub(&stop, &start, &diff);
1586 
1587 	BUG_ON(bench_format != BENCH_FORMAT_DEFAULT);
1588 
1589 	tprintf("\n ###\n");
1590 	tprintf("\n");
1591 
1592 	runtime_sec_max = diff.tv_sec * NSEC_PER_SEC;
1593 	runtime_sec_max += diff.tv_usec * NSEC_PER_USEC;
1594 	runtime_sec_max /= NSEC_PER_SEC;
1595 
1596 	runtime_sec_min = runtime_ns_min / NSEC_PER_SEC;
1597 
1598 	bytes = g->bytes_done;
1599 	runtime_avg = (double)runtime_ns_sum / g->p.nr_tasks / NSEC_PER_SEC;
1600 
1601 	if (g->p.measure_convergence) {
1602 		print_res(name, runtime_sec_max,
1603 			"secs,", "NUMA-convergence-latency", "secs latency to NUMA-converge");
1604 	}
1605 
1606 	print_res(name, runtime_sec_max,
1607 		"secs,", "runtime-max/thread",	"secs slowest (max) thread-runtime");
1608 
1609 	print_res(name, runtime_sec_min,
1610 		"secs,", "runtime-min/thread",	"secs fastest (min) thread-runtime");
1611 
1612 	print_res(name, runtime_avg,
1613 		"secs,", "runtime-avg/thread",	"secs average thread-runtime");
1614 
1615 	delta_runtime = (runtime_sec_max - runtime_sec_min)/2.0;
1616 	print_res(name, delta_runtime / runtime_sec_max * 100.0,
1617 		"%,", "spread-runtime/thread",	"% difference between max/avg runtime");
1618 
1619 	print_res(name, bytes / g->p.nr_tasks / 1e9,
1620 		"GB,", "data/thread",		"GB data processed, per thread");
1621 
1622 	print_res(name, bytes / 1e9,
1623 		"GB,", "data-total",		"GB data processed, total");
1624 
1625 	print_res(name, runtime_sec_max * NSEC_PER_SEC / (bytes / g->p.nr_tasks),
1626 		"nsecs,", "runtime/byte/thread","nsecs/byte/thread runtime");
1627 
1628 	print_res(name, bytes / g->p.nr_tasks / 1e9 / runtime_sec_max,
1629 		"GB/sec,", "thread-speed",	"GB/sec/thread speed");
1630 
1631 	print_res(name, bytes / runtime_sec_max / 1e9,
1632 		"GB/sec,", "total-speed",	"GB/sec total speed");
1633 
1634 	if (g->p.show_details >= 2) {
1635 		char tname[14 + 2 * 10 + 1];
1636 		struct thread_data *td;
1637 		for (p = 0; p < g->p.nr_proc; p++) {
1638 			for (t = 0; t < g->p.nr_threads; t++) {
1639 				memset(tname, 0, sizeof(tname));
1640 				td = g->threads + p*g->p.nr_threads + t;
1641 				snprintf(tname, sizeof(tname), "process%d:thread%d", p, t);
1642 				print_res(tname, td->speed_gbs,
1643 					"GB/sec",	"thread-speed", "GB/sec/thread speed");
1644 				print_res(tname, td->system_time_ns / NSEC_PER_SEC,
1645 					"secs",	"thread-system-time", "system CPU time/thread");
1646 				print_res(tname, td->user_time_ns / NSEC_PER_SEC,
1647 					"secs",	"thread-user-time", "user CPU time/thread");
1648 			}
1649 		}
1650 	}
1651 
1652 	free(pids);
1653 
1654 	deinit();
1655 
1656 	return 0;
1657 }
1658 
1659 #define MAX_ARGS 50
1660 
1661 static int command_size(const char **argv)
1662 {
1663 	int size = 0;
1664 
1665 	while (*argv) {
1666 		size++;
1667 		argv++;
1668 	}
1669 
1670 	BUG_ON(size >= MAX_ARGS);
1671 
1672 	return size;
1673 }
1674 
1675 static void init_params(struct params *p, const char *name, int argc, const char **argv)
1676 {
1677 	int i;
1678 
1679 	printf("\n # Running %s \"perf bench numa", name);
1680 
1681 	for (i = 0; i < argc; i++)
1682 		printf(" %s", argv[i]);
1683 
1684 	printf("\"\n");
1685 
1686 	memset(p, 0, sizeof(*p));
1687 
1688 	/* Initialize nonzero defaults: */
1689 
1690 	p->serialize_startup		= 1;
1691 	p->data_reads			= true;
1692 	p->data_writes			= true;
1693 	p->data_backwards		= true;
1694 	p->data_rand_walk		= true;
1695 	p->nr_loops			= -1;
1696 	p->init_random			= true;
1697 	p->mb_global_str		= "1";
1698 	p->nr_proc			= 1;
1699 	p->nr_threads			= 1;
1700 	p->nr_secs			= 5;
1701 	p->run_all			= argc == 1;
1702 }
1703 
1704 static int run_bench_numa(const char *name, const char **argv)
1705 {
1706 	int argc = command_size(argv);
1707 
1708 	init_params(&p0, name, argc, argv);
1709 	argc = parse_options(argc, argv, options, bench_numa_usage, 0);
1710 	if (argc)
1711 		goto err;
1712 
1713 	if (__bench_numa(name))
1714 		goto err;
1715 
1716 	return 0;
1717 
1718 err:
1719 	return -1;
1720 }
1721 
1722 #define OPT_BW_RAM		"-s",  "20", "-zZq",    "--thp", " 1", "--no-data_rand_walk"
1723 #define OPT_BW_RAM_NOTHP	OPT_BW_RAM,		"--thp", "-1"
1724 
1725 #define OPT_CONV		"-s", "100", "-zZ0qcm", "--thp", " 1"
1726 #define OPT_CONV_NOTHP		OPT_CONV,		"--thp", "-1"
1727 
1728 #define OPT_BW			"-s",  "20", "-zZ0q",   "--thp", " 1"
1729 #define OPT_BW_NOTHP		OPT_BW,			"--thp", "-1"
1730 
1731 /*
1732  * The built-in test-suite executed by "perf bench numa -a".
1733  *
1734  * (A minimum of 4 nodes and 16 GB of RAM is recommended.)
1735  */
1736 static const char *tests[][MAX_ARGS] = {
1737    /* Basic single-stream NUMA bandwidth measurements: */
1738    { "RAM-bw-local,",	  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1739 			  "-C" ,   "0", "-M",   "0", OPT_BW_RAM },
1740    { "RAM-bw-local-NOTHP,",
1741 			  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1742 			  "-C" ,   "0", "-M",   "0", OPT_BW_RAM_NOTHP },
1743    { "RAM-bw-remote,",	  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1744 			  "-C" ,   "0", "-M",   "1", OPT_BW_RAM },
1745 
1746    /* 2-stream NUMA bandwidth measurements: */
1747    { "RAM-bw-local-2x,",  "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1748 			   "-C", "0,2", "-M", "0x2", OPT_BW_RAM },
1749    { "RAM-bw-remote-2x,", "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1750 		 	   "-C", "0,2", "-M", "1x2", OPT_BW_RAM },
1751 
1752    /* Cross-stream NUMA bandwidth measurement: */
1753    { "RAM-bw-cross,",     "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1754 		 	   "-C", "0,8", "-M", "1,0", OPT_BW_RAM },
1755 
1756    /* Convergence latency measurements: */
1757    { " 1x3-convergence,", "mem",  "-p",  "1", "-t",  "3", "-P",  "512", OPT_CONV },
1758    { " 1x4-convergence,", "mem",  "-p",  "1", "-t",  "4", "-P",  "512", OPT_CONV },
1759    { " 1x6-convergence,", "mem",  "-p",  "1", "-t",  "6", "-P", "1020", OPT_CONV },
1760    { " 2x3-convergence,", "mem",  "-p",  "3", "-t",  "3", "-P", "1020", OPT_CONV },
1761    { " 3x3-convergence,", "mem",  "-p",  "3", "-t",  "3", "-P", "1020", OPT_CONV },
1762    { " 4x4-convergence,", "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_CONV },
1763    { " 4x4-convergence-NOTHP,",
1764 			  "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_CONV_NOTHP },
1765    { " 4x6-convergence,", "mem",  "-p",  "4", "-t",  "6", "-P", "1020", OPT_CONV },
1766    { " 4x8-convergence,", "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_CONV },
1767    { " 8x4-convergence,", "mem",  "-p",  "8", "-t",  "4", "-P",  "512", OPT_CONV },
1768    { " 8x4-convergence-NOTHP,",
1769 			  "mem",  "-p",  "8", "-t",  "4", "-P",  "512", OPT_CONV_NOTHP },
1770    { " 3x1-convergence,", "mem",  "-p",  "3", "-t",  "1", "-P",  "512", OPT_CONV },
1771    { " 4x1-convergence,", "mem",  "-p",  "4", "-t",  "1", "-P",  "512", OPT_CONV },
1772    { " 8x1-convergence,", "mem",  "-p",  "8", "-t",  "1", "-P",  "512", OPT_CONV },
1773    { "16x1-convergence,", "mem",  "-p", "16", "-t",  "1", "-P",  "256", OPT_CONV },
1774    { "32x1-convergence,", "mem",  "-p", "32", "-t",  "1", "-P",  "128", OPT_CONV },
1775 
1776    /* Various NUMA process/thread layout bandwidth measurements: */
1777    { " 2x1-bw-process,",  "mem",  "-p",  "2", "-t",  "1", "-P", "1024", OPT_BW },
1778    { " 3x1-bw-process,",  "mem",  "-p",  "3", "-t",  "1", "-P", "1024", OPT_BW },
1779    { " 4x1-bw-process,",  "mem",  "-p",  "4", "-t",  "1", "-P", "1024", OPT_BW },
1780    { " 8x1-bw-process,",  "mem",  "-p",  "8", "-t",  "1", "-P", " 512", OPT_BW },
1781    { " 8x1-bw-process-NOTHP,",
1782 			  "mem",  "-p",  "8", "-t",  "1", "-P", " 512", OPT_BW_NOTHP },
1783    { "16x1-bw-process,",  "mem",  "-p", "16", "-t",  "1", "-P",  "256", OPT_BW },
1784 
1785    { " 4x1-bw-thread,",	  "mem",  "-p",  "1", "-t",  "4", "-T",  "256", OPT_BW },
1786    { " 8x1-bw-thread,",	  "mem",  "-p",  "1", "-t",  "8", "-T",  "256", OPT_BW },
1787    { "16x1-bw-thread,",   "mem",  "-p",  "1", "-t", "16", "-T",  "128", OPT_BW },
1788    { "32x1-bw-thread,",   "mem",  "-p",  "1", "-t", "32", "-T",   "64", OPT_BW },
1789 
1790    { " 2x3-bw-thread,",	  "mem",  "-p",  "2", "-t",  "3", "-P",  "512", OPT_BW },
1791    { " 4x4-bw-thread,",	  "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_BW },
1792    { " 4x6-bw-thread,",	  "mem",  "-p",  "4", "-t",  "6", "-P",  "512", OPT_BW },
1793    { " 4x8-bw-thread,",	  "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_BW },
1794    { " 4x8-bw-thread-NOTHP,",
1795 			  "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_BW_NOTHP },
1796    { " 3x3-bw-thread,",	  "mem",  "-p",  "3", "-t",  "3", "-P",  "512", OPT_BW },
1797    { " 5x5-bw-thread,",	  "mem",  "-p",  "5", "-t",  "5", "-P",  "512", OPT_BW },
1798 
1799    { "2x16-bw-thread,",   "mem",  "-p",  "2", "-t", "16", "-P",  "512", OPT_BW },
1800    { "1x32-bw-thread,",   "mem",  "-p",  "1", "-t", "32", "-P", "2048", OPT_BW },
1801 
1802    { "numa02-bw,",	  "mem",  "-p",  "1", "-t", "32", "-T",   "32", OPT_BW },
1803    { "numa02-bw-NOTHP,",  "mem",  "-p",  "1", "-t", "32", "-T",   "32", OPT_BW_NOTHP },
1804    { "numa01-bw-thread,", "mem",  "-p",  "2", "-t", "16", "-T",  "192", OPT_BW },
1805    { "numa01-bw-thread-NOTHP,",
1806 			  "mem",  "-p",  "2", "-t", "16", "-T",  "192", OPT_BW_NOTHP },
1807 };
1808 
1809 static int bench_all(void)
1810 {
1811 	int nr = ARRAY_SIZE(tests);
1812 	int ret;
1813 	int i;
1814 
1815 	ret = system("echo ' #'; echo ' # Running test on: '$(uname -a); echo ' #'");
1816 	BUG_ON(ret < 0);
1817 
1818 	for (i = 0; i < nr; i++) {
1819 		run_bench_numa(tests[i][0], tests[i] + 1);
1820 	}
1821 
1822 	printf("\n");
1823 
1824 	return 0;
1825 }
1826 
1827 int bench_numa(int argc, const char **argv)
1828 {
1829 	init_params(&p0, "main,", argc, argv);
1830 	argc = parse_options(argc, argv, options, bench_numa_usage, 0);
1831 	if (argc)
1832 		goto err;
1833 
1834 	if (p0.run_all)
1835 		return bench_all();
1836 
1837 	if (__bench_numa(NULL))
1838 		goto err;
1839 
1840 	return 0;
1841 
1842 err:
1843 	usage_with_options(numa_usage, options);
1844 	return -1;
1845 }
1846