1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 2018 Intel Corporation
14 #include <sys/types.h>
22 #define PAGE_SIZE (4 * 1024)
23 #define MB (1024 * 1024)
25 static unsigned char *startptr;
29 #if defined(__i386) || defined(__x86_64)
30 asm volatile("sfence\n\t"
35 static void cl_flush(void *p)
37 #if defined(__i386) || defined(__x86_64)
38 asm volatile("clflush (%0)\n\t"
39 : : "r"(p) : "memory");
43 static void mem_flush(void *p, size_t s)
48 s = s / CL_SIZE; /* mem size in cache llines */
50 for (i = 0; i < s; i++)
51 cl_flush(&cp[i * CL_SIZE]);
56 static void *malloc_and_init_memory(size_t s)
63 ret = posix_memalign(&p, PAGE_SIZE, s);
68 s64 = s / sizeof(uint64_t);
71 *p64 = (uint64_t)rand();
72 p64 += (CL_SIZE / sizeof(uint64_t));
73 s64 -= (CL_SIZE / sizeof(uint64_t));
79 static int fill_one_span_read(unsigned char *start_ptr, unsigned char *end_ptr)
81 unsigned char sum, *p;
94 void fill_one_span_write(unsigned char *start_ptr, unsigned char *end_ptr)
105 static int fill_cache_read(unsigned char *start_ptr, unsigned char *end_ptr,
112 ret = fill_one_span_read(start_ptr, end_ptr);
113 if (!strncmp(resctrl_val, CAT_STR, sizeof(CAT_STR)))
117 /* Consume read result so that reading memory is not optimized out. */
118 fp = fopen("/dev/null", "w");
120 perror("Unable to write to /dev/null");
123 fprintf(fp, "Sum: %d ", ret);
129 static int fill_cache_write(unsigned char *start_ptr, unsigned char *end_ptr,
133 fill_one_span_write(start_ptr, end_ptr);
134 if (!strncmp(resctrl_val, CAT_STR, sizeof(CAT_STR)))
142 fill_cache(unsigned long long buf_size, int malloc_and_init, int memflush,
143 int op, char *resctrl_val)
145 unsigned char *start_ptr, *end_ptr;
146 unsigned long long i;
150 start_ptr = malloc_and_init_memory(buf_size);
152 start_ptr = malloc(buf_size);
157 startptr = start_ptr;
158 end_ptr = start_ptr + buf_size;
161 * It's better to touch the memory once to avoid any compiler
164 if (!malloc_and_init) {
165 for (i = 0; i < buf_size; i++)
166 *start_ptr++ = (unsigned char)rand();
169 start_ptr = startptr;
171 /* Flush the memory before using to avoid "cache hot pages" effect */
173 mem_flush(start_ptr, buf_size);
176 ret = fill_cache_read(start_ptr, end_ptr, resctrl_val);
178 ret = fill_cache_write(start_ptr, end_ptr, resctrl_val);
181 printf("\n Error in fill cache read/write...\n");
190 int run_fill_buf(unsigned long span, int malloc_and_init_memory,
191 int memflush, int op, char *resctrl_val)
193 unsigned long long cache_size = span;
196 ret = fill_cache(cache_size, malloc_and_init_memory, memflush, op,
199 printf("\n Error in fill cache\n");