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