1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * mem-memcpy.c 4 * 5 * Simple memcpy() and memset() benchmarks 6 * 7 * Written by Hitoshi Mitake <mitake@dcl.info.waseda.ac.jp> 8 */ 9 10 #include "bench.h" 11 #include "../perf-sys.h" 12 #include <subcmd/parse-options.h> 13 #include "util/cloexec.h" 14 #include "util/debug.h" 15 #include "util/header.h" 16 #include "util/stat.h" 17 #include "util/string2.h" 18 #include "mem-memcpy-arch.h" 19 #include "mem-memset-arch.h" 20 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <string.h> 24 #include <unistd.h> 25 #include <sys/time.h> 26 #include <sys/mman.h> 27 #include <errno.h> 28 #include <linux/time64.h> 29 #include <linux/log2.h> 30 #include <pthread.h> 31 32 #define K 1024 33 34 #define PAGE_SHIFT_4KB 12 35 #define PAGE_SHIFT_2MB 21 36 #define PAGE_SHIFT_1GB 30 37 38 static const char *size_str = "1MB"; 39 static const char *function_str = "all"; 40 static const char *page_size_str = "4KB"; 41 static const char *chunk_size_str = "0"; 42 static unsigned int nr_loops = 1; 43 static bool use_cycles; 44 static int cycles_fd; 45 static unsigned int seed; 46 static unsigned int nr_threads = 1; 47 48 static const struct option bench_common_options[] = { 49 OPT_STRING('s', "size", &size_str, "1MB", 50 "Specify the size of the memory buffers. " 51 "Available units: B, KB, MB, GB and TB (case insensitive)"), 52 53 OPT_STRING('p', "page", &page_size_str, "4KB", 54 "Specify page-size for mapping memory buffers. " 55 "Available sizes: 4KB, 2MB, 1GB (case insensitive)"), 56 57 OPT_STRING('f', "function", &function_str, "all", 58 "Specify the function to run, \"all\" runs all available functions, \"help\" lists them"), 59 60 OPT_UINTEGER('l', "nr_loops", &nr_loops, 61 "Specify the number of loops to run. (default: 1)"), 62 63 OPT_BOOLEAN('c', "cycles", &use_cycles, 64 "Use a cycles event instead of gettimeofday() to measure performance"), 65 66 OPT_END() 67 }; 68 69 static const struct option bench_mem_options[] = { 70 OPT_STRING('k', "chunk", &chunk_size_str, "0", 71 "Specify the chunk-size for each invocation. " 72 "Available units: B, KB, MB, GB and TB (case insensitive)"), 73 OPT_PARENT(bench_common_options), 74 OPT_END() 75 }; 76 77 union bench_clock { 78 u64 cycles; 79 struct timeval tv; 80 }; 81 82 struct bench_params { 83 size_t size; 84 size_t size_total; 85 size_t chunk_size; 86 unsigned int nr_loops; 87 unsigned int page_shift; 88 unsigned int seed; 89 }; 90 91 struct bench_mem_info { 92 const struct function *functions; 93 int (*do_op)(const struct function *r, struct bench_params *p, 94 void *src, void *dst, union bench_clock *rt); 95 const char *const *usage; 96 const struct option *options; 97 bool alloc_src; 98 }; 99 100 typedef bool (*mem_init_t)(struct bench_mem_info *, struct bench_params *, 101 void **, void **); 102 typedef void (*mem_fini_t)(struct bench_mem_info *, struct bench_params *, 103 void **, void **); 104 typedef void *(*memcpy_t)(void *, const void *, size_t); 105 typedef void *(*memset_t)(void *, int, size_t); 106 typedef void (*mmap_op_t)(void *, size_t, unsigned int, bool); 107 108 struct function { 109 const char *name; 110 const char *desc; 111 struct { 112 mem_init_t init; 113 mem_fini_t fini; 114 union { 115 memcpy_t memcpy; 116 memset_t memset; 117 mmap_op_t mmap_op; 118 }; 119 } fn; 120 }; 121 122 static struct perf_event_attr cycle_attr = { 123 .type = PERF_TYPE_HARDWARE, 124 .config = PERF_COUNT_HW_CPU_CYCLES 125 }; 126 127 static struct stats stats; 128 129 static int init_cycles(void) 130 { 131 cycles_fd = sys_perf_event_open(&cycle_attr, getpid(), -1, -1, perf_event_open_cloexec_flag()); 132 133 if (cycles_fd < 0 && errno == ENOSYS) { 134 pr_debug("No CONFIG_PERF_EVENTS=y kernel support configured?\n"); 135 return -1; 136 } 137 138 return cycles_fd; 139 } 140 141 static u64 get_cycles(void) 142 { 143 int ret; 144 u64 clk; 145 146 ret = read(cycles_fd, &clk, sizeof(u64)); 147 BUG_ON(ret != sizeof(u64)); 148 149 return clk; 150 } 151 152 static void clock_get(union bench_clock *t) 153 { 154 if (use_cycles) 155 t->cycles = get_cycles(); 156 else 157 BUG_ON(gettimeofday(&t->tv, NULL)); 158 } 159 160 static union bench_clock clock_diff(union bench_clock *s, union bench_clock *e) 161 { 162 union bench_clock t; 163 164 if (use_cycles) 165 t.cycles = e->cycles - s->cycles; 166 else 167 timersub(&e->tv, &s->tv, &t.tv); 168 169 return t; 170 } 171 172 static void clock_accum(union bench_clock *a, union bench_clock *b) 173 { 174 if (use_cycles) 175 a->cycles += b->cycles; 176 else 177 timeradd(&a->tv, &b->tv, &a->tv); 178 } 179 180 static double timeval2double(struct timeval *ts) 181 { 182 return ((double)ts->tv_sec + (double)ts->tv_usec / (double)USEC_PER_SEC) / nr_threads; 183 } 184 185 #define print_bps(x) do { \ 186 if (x < K) \ 187 printf(" %14lf bytes/sec", x); \ 188 else if (x < K * K) \ 189 printf(" %14lfd KB/sec", x / K); \ 190 else if (x < K * K * K) \ 191 printf(" %14lf MB/sec", x / K / K); \ 192 else \ 193 printf(" %14lf GB/sec", x / K / K / K); \ 194 } while (0) 195 196 static void __bench_mem_function(struct bench_mem_info *info, struct bench_params *p, 197 int r_idx) 198 { 199 const struct function *r = &info->functions[r_idx]; 200 double result_bps = 0.0; 201 union bench_clock rt = { 0 }; 202 void *src = NULL, *dst = NULL; 203 204 init_stats(&stats); 205 printf("# function '%s' (%s)\n", r->name, r->desc); 206 207 if (r->fn.init && r->fn.init(info, p, &src, &dst)) 208 goto out_init_failed; 209 210 if (bench_format == BENCH_FORMAT_DEFAULT) 211 printf("# Copying %s bytes ...\n\n", size_str); 212 213 if (info->do_op(r, p, src, dst, &rt)) 214 goto out_test_failed; 215 216 switch (bench_format) { 217 case BENCH_FORMAT_DEFAULT: 218 if (use_cycles) { 219 printf(" %14lf cycles/byte", (double)rt.cycles/(double)p->size_total); 220 } else { 221 result_bps = (double)p->size_total/timeval2double(&rt.tv); 222 print_bps(result_bps); 223 } 224 if (nr_threads > 1) { 225 printf("/thread\t( +- %6.2f%% )", 226 rel_stddev_stats(stddev_stats(&stats), avg_stats(&stats))); 227 } 228 printf("\n"); 229 break; 230 231 case BENCH_FORMAT_SIMPLE: 232 if (use_cycles) { 233 printf("%lf\n", (double)rt.cycles/(double)p->size_total); 234 } else { 235 result_bps = (double)p->size_total/timeval2double(&rt.tv); 236 printf("%lf\n", result_bps); 237 } 238 break; 239 240 default: 241 BUG_ON(1); 242 break; 243 } 244 245 out_test_failed: 246 out_free: 247 if (r->fn.fini) r->fn.fini(info, p, &src, &dst); 248 return; 249 out_init_failed: 250 printf("# Memory allocation failed - maybe size (%s) %s?\n", size_str, 251 p->page_shift != PAGE_SHIFT_4KB ? "has insufficient hugepages" : "is too large"); 252 goto out_free; 253 } 254 255 static int bench_mem_common(int argc, const char **argv, struct bench_mem_info *info) 256 { 257 int i; 258 struct bench_params p = { 0 }; 259 unsigned int page_size; 260 261 argc = parse_options(argc, argv, info->options, info->usage, 0); 262 263 if (use_cycles) { 264 i = init_cycles(); 265 if (i < 0) { 266 fprintf(stderr, "Failed to open cycles counter\n"); 267 return i; 268 } 269 } 270 271 p.nr_loops = nr_loops; 272 p.size = (size_t)perf_atoll((char *)size_str); 273 274 if ((s64)p.size <= 0) { 275 fprintf(stderr, "Invalid size:%s\n", size_str); 276 return 1; 277 } 278 p.size_total = p.size * p.nr_loops; 279 280 p.chunk_size = (size_t)perf_atoll((char *)chunk_size_str); 281 if ((s64)p.chunk_size < 0 || (s64)p.chunk_size > (s64)p.size) { 282 fprintf(stderr, "Invalid chunk_size:%s\n", chunk_size_str); 283 return 1; 284 } 285 if (!p.chunk_size) 286 p.chunk_size = p.size; 287 288 page_size = (unsigned int)perf_atoll((char *)page_size_str); 289 if (page_size != (1 << PAGE_SHIFT_4KB) && 290 page_size != (1 << PAGE_SHIFT_2MB) && 291 page_size != (1 << PAGE_SHIFT_1GB)) { 292 fprintf(stderr, "Invalid page-size:%s\n", page_size_str); 293 return 1; 294 } 295 p.page_shift = ilog2(page_size); 296 297 p.seed = seed; 298 299 if (!strncmp(function_str, "all", 3)) { 300 for (i = 0; info->functions[i].name; i++) 301 __bench_mem_function(info, &p, i); 302 return 0; 303 } 304 305 for (i = 0; info->functions[i].name; i++) { 306 if (!strcmp(info->functions[i].name, function_str)) 307 break; 308 } 309 if (!info->functions[i].name) { 310 if (strcmp(function_str, "help") && strcmp(function_str, "h")) 311 printf("Unknown function: %s\n", function_str); 312 printf("Available functions:\n"); 313 for (i = 0; info->functions[i].name; i++) { 314 printf("\t%s ... %s\n", 315 info->functions[i].name, info->functions[i].desc); 316 } 317 return 1; 318 } 319 320 __bench_mem_function(info, &p, i); 321 322 return 0; 323 } 324 325 static void memcpy_prefault(memcpy_t fn, size_t size, void *src, void *dst) 326 { 327 /* Make sure to always prefault zero pages even if MMAP_THRESH is crossed: */ 328 memset(src, 0, size); 329 330 /* 331 * We prefault the freshly allocated memory range here, 332 * to not measure page fault overhead: 333 */ 334 fn(dst, src, size); 335 } 336 337 static int do_memcpy(const struct function *r, struct bench_params *p, 338 void *src, void *dst, union bench_clock *rt) 339 { 340 union bench_clock start, end; 341 memcpy_t fn = r->fn.memcpy; 342 343 memcpy_prefault(fn, p->size, src, dst); 344 345 clock_get(&start); 346 for (unsigned int i = 0; i < p->nr_loops; ++i) 347 for (size_t off = 0; off < p->size; off += p->chunk_size) 348 fn(dst + off, src + off, min(p->chunk_size, p->size - off)); 349 clock_get(&end); 350 351 *rt = clock_diff(&start, &end); 352 353 return 0; 354 } 355 356 static void *bench_mmap(size_t size, bool populate, unsigned int page_shift) 357 { 358 void *p; 359 int extra = populate ? MAP_POPULATE : 0; 360 361 if (page_shift != PAGE_SHIFT_4KB) 362 extra |= MAP_HUGETLB | (page_shift << MAP_HUGE_SHIFT); 363 364 p = mmap(NULL, size, PROT_READ|PROT_WRITE, 365 extra | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); 366 367 return p == MAP_FAILED ? NULL : p; 368 } 369 370 static void bench_munmap(void *p, size_t size) 371 { 372 if (p) 373 munmap(p, size); 374 } 375 376 static bool mem_alloc(struct bench_mem_info *info, struct bench_params *p, 377 void **src, void **dst) 378 { 379 bool failed; 380 381 *dst = bench_mmap(p->size, true, p->page_shift); 382 failed = *dst == NULL; 383 384 if (info->alloc_src) { 385 *src = bench_mmap(p->size, true, p->page_shift); 386 failed = failed || *src == NULL; 387 } 388 389 return failed; 390 } 391 392 static void mem_free(struct bench_mem_info *info __maybe_unused, 393 struct bench_params *p __maybe_unused, 394 void **src, void **dst) 395 { 396 bench_munmap(*dst, p->size); 397 bench_munmap(*src, p->size); 398 399 *dst = *src = NULL; 400 } 401 402 static struct function memcpy_functions[] = { 403 { .name = "default", 404 .desc = "Default memcpy() provided by glibc", 405 .fn.init = mem_alloc, 406 .fn.fini = mem_free, 407 .fn.memcpy = memcpy }, 408 409 #ifdef HAVE_ARCH_X86_64_SUPPORT 410 # define MEMCPY_FN(_fn, _init, _fini, _name, _desc) \ 411 {.name = _name, .desc = _desc, .fn.memcpy = _fn, .fn.init = _init, .fn.fini = _fini }, 412 # include "mem-memcpy-x86-64-asm-def.h" 413 # undef MEMCPY_FN 414 #endif 415 416 { .name = NULL, } 417 }; 418 419 static const char * const bench_mem_memcpy_usage[] = { 420 "perf bench mem memcpy <options>", 421 NULL 422 }; 423 424 int bench_mem_memcpy(int argc, const char **argv) 425 { 426 struct bench_mem_info info = { 427 .functions = memcpy_functions, 428 .do_op = do_memcpy, 429 .usage = bench_mem_memcpy_usage, 430 .options = bench_mem_options, 431 .alloc_src = true, 432 }; 433 434 return bench_mem_common(argc, argv, &info); 435 } 436 437 static int do_memset(const struct function *r, struct bench_params *p, 438 void *src __maybe_unused, void *dst, union bench_clock *rt) 439 { 440 union bench_clock start, end; 441 memset_t fn = r->fn.memset; 442 443 /* 444 * We prefault the freshly allocated memory range here, 445 * to not measure page fault overhead: 446 */ 447 fn(dst, -1, p->size); 448 449 clock_get(&start); 450 for (unsigned int i = 0; i < p->nr_loops; ++i) 451 for (size_t off = 0; off < p->size; off += p->chunk_size) 452 fn(dst + off, i, min(p->chunk_size, p->size - off)); 453 clock_get(&end); 454 455 *rt = clock_diff(&start, &end); 456 457 return 0; 458 } 459 460 static const char * const bench_mem_memset_usage[] = { 461 "perf bench mem memset <options>", 462 NULL 463 }; 464 465 static const struct function memset_functions[] = { 466 { .name = "default", 467 .desc = "Default memset() provided by glibc", 468 .fn.init = mem_alloc, 469 .fn.fini = mem_free, 470 .fn.memset = memset }, 471 472 #ifdef HAVE_ARCH_X86_64_SUPPORT 473 # define MEMSET_FN(_fn, _init, _fini, _name, _desc) \ 474 {.name = _name, .desc = _desc, .fn.memset = _fn, .fn.init = _init, .fn.fini = _fini }, 475 # include "mem-memset-x86-64-asm-def.h" 476 # undef MEMSET_FN 477 #endif 478 479 { .name = NULL, } 480 }; 481 482 int bench_mem_memset(int argc, const char **argv) 483 { 484 struct bench_mem_info info = { 485 .functions = memset_functions, 486 .do_op = do_memset, 487 .usage = bench_mem_memset_usage, 488 .options = bench_mem_options, 489 }; 490 491 return bench_mem_common(argc, argv, &info); 492 } 493 494 static void mmap_page_touch(void *dst, size_t size, unsigned int page_shift, bool random) 495 { 496 unsigned long npages = size / (1 << page_shift); 497 unsigned long offset = 0, r = 0; 498 499 for (unsigned long i = 0; i < npages; i++) { 500 if (random) 501 r = rand() % (1 << page_shift); 502 503 *((char *)dst + offset + r) = *(char *)(dst + offset + r) + i; 504 offset += 1 << page_shift; 505 } 506 } 507 508 struct mmap_data { 509 pthread_t id; 510 const struct function *func; 511 struct bench_params *params; 512 union bench_clock result; 513 unsigned int seed; 514 int error; 515 }; 516 517 static void *do_mmap_thread(void *arg) 518 { 519 struct mmap_data *data = arg; 520 const struct function *r = data->func; 521 struct bench_params *p = data->params; 522 union bench_clock start, end, diff; 523 mmap_op_t fn = r->fn.mmap_op; 524 bool populate = strcmp(r->name, "populate") == 0; 525 void *dst; 526 527 if (data->seed) 528 srand(data->seed); 529 530 for (unsigned int i = 0; i < p->nr_loops; i++) { 531 clock_get(&start); 532 dst = bench_mmap(p->size, populate, p->page_shift); 533 if (!dst) 534 goto out; 535 536 fn(dst, p->size, p->page_shift, p->seed); 537 clock_get(&end); 538 diff = clock_diff(&start, &end); 539 clock_accum(&data->result, &diff); 540 541 bench_munmap(dst, p->size); 542 } 543 544 return data; 545 out: 546 data->error = -ENOMEM; 547 return NULL; 548 } 549 550 static int do_mmap(const struct function *r, struct bench_params *p, 551 void *src __maybe_unused, void *dst __maybe_unused, 552 union bench_clock *accum) 553 { 554 struct mmap_data *data; 555 int error = 0; 556 557 data = calloc(nr_threads, sizeof(*data)); 558 if (!data) { 559 printf("# Failed to allocate thread resources\n"); 560 return -1; 561 } 562 563 for (unsigned int i = 0; i < nr_threads; i++) { 564 data[i].func = r; 565 data[i].params = p; 566 if (p->seed) 567 data[i].seed = p->seed + i; 568 569 if (pthread_create(&data[i].id, NULL, do_mmap_thread, &data[i]) < 0) 570 data[i].error = -errno; 571 } 572 573 for (unsigned int i = 0; i < nr_threads; i++) { 574 union bench_clock *t = &data[i].result; 575 576 pthread_join(data[i].id, NULL); 577 578 clock_accum(accum, t); 579 if (use_cycles) 580 update_stats(&stats, t->cycles); 581 else 582 update_stats(&stats, t->tv.tv_sec * 1e6 + t->tv.tv_usec); 583 error |= data[i].error; 584 } 585 free(data); 586 587 if (error) { 588 printf("# Memory allocation failed - maybe size (%s) %s?\n", size_str, 589 p->page_shift != PAGE_SHIFT_4KB ? "has insufficient hugepages" : "is too large"); 590 } 591 return error ? -1 : 0; 592 } 593 594 static const char * const bench_mem_mmap_usage[] = { 595 "perf bench mem mmap <options>", 596 NULL 597 }; 598 599 static const struct function mmap_functions[] = { 600 { .name = "demand", 601 .desc = "Demand loaded mmap()", 602 .fn.mmap_op = mmap_page_touch }, 603 604 { .name = "populate", 605 .desc = "Eagerly populated mmap()", 606 .fn.mmap_op = mmap_page_touch }, 607 608 { .name = NULL, } 609 }; 610 611 int bench_mem_mmap(int argc, const char **argv) 612 { 613 static const struct option bench_mmap_options[] = { 614 OPT_UINTEGER('r', "randomize", &seed, 615 "Seed to randomize page access offset."), 616 OPT_UINTEGER('t', "threads", &nr_threads, 617 "Number of threads to run concurrently (default: 1)."), 618 OPT_PARENT(bench_common_options), 619 OPT_END() 620 }; 621 622 struct bench_mem_info info = { 623 .functions = mmap_functions, 624 .do_op = do_mmap, 625 .usage = bench_mem_mmap_usage, 626 .options = bench_mmap_options, 627 }; 628 629 return bench_mem_common(argc, argv, &info); 630 } 631