mem: share hugepage info primary and secondary
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_hugepage_info.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4
5 #include <string.h>
6 #include <sys/types.h>
7 #include <sys/file.h>
8 #include <dirent.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <fnmatch.h>
13 #include <inttypes.h>
14 #include <stdarg.h>
15 #include <unistd.h>
16 #include <errno.h>
17 #include <sys/mman.h>
18 #include <sys/queue.h>
19 #include <sys/stat.h>
20
21 #include <rte_memory.h>
22 #include <rte_eal.h>
23 #include <rte_launch.h>
24 #include <rte_per_lcore.h>
25 #include <rte_lcore.h>
26 #include <rte_debug.h>
27 #include <rte_log.h>
28 #include <rte_common.h>
29 #include "rte_string_fns.h"
30 #include "eal_internal_cfg.h"
31 #include "eal_hugepages.h"
32 #include "eal_filesystem.h"
33
34 static const char sys_dir_path[] = "/sys/kernel/mm/hugepages";
35 static const char sys_pages_numa_dir_path[] = "/sys/devices/system/node";
36
37 /*
38  * Uses mmap to create a shared memory area for storage of data
39  * Used in this file to store the hugepage file map on disk
40  */
41 static void *
42 map_shared_memory(const char *filename, const size_t mem_size, int flags)
43 {
44         void *retval;
45         int fd = open(filename, flags, 0666);
46         if (fd < 0)
47                 return NULL;
48         if (ftruncate(fd, mem_size) < 0) {
49                 close(fd);
50                 return NULL;
51         }
52         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE,
53                         MAP_SHARED, fd, 0);
54         close(fd);
55         return retval;
56 }
57
58 static void *
59 open_shared_memory(const char *filename, const size_t mem_size)
60 {
61         return map_shared_memory(filename, mem_size, O_RDWR);
62 }
63
64 static void *
65 create_shared_memory(const char *filename, const size_t mem_size)
66 {
67         return map_shared_memory(filename, mem_size, O_RDWR | O_CREAT);
68 }
69
70 /* this function is only called from eal_hugepage_info_init which itself
71  * is only called from a primary process */
72 static uint32_t
73 get_num_hugepages(const char *subdir)
74 {
75         char path[PATH_MAX];
76         long unsigned resv_pages, num_pages = 0;
77         const char *nr_hp_file = "free_hugepages";
78         const char *nr_rsvd_file = "resv_hugepages";
79
80         /* first, check how many reserved pages kernel reports */
81         snprintf(path, sizeof(path), "%s/%s/%s",
82                         sys_dir_path, subdir, nr_rsvd_file);
83         if (eal_parse_sysfs_value(path, &resv_pages) < 0)
84                 return 0;
85
86         snprintf(path, sizeof(path), "%s/%s/%s",
87                         sys_dir_path, subdir, nr_hp_file);
88         if (eal_parse_sysfs_value(path, &num_pages) < 0)
89                 return 0;
90
91         if (num_pages == 0)
92                 RTE_LOG(WARNING, EAL, "No free hugepages reported in %s\n",
93                                 subdir);
94
95         /* adjust num_pages */
96         if (num_pages >= resv_pages)
97                 num_pages -= resv_pages;
98         else if (resv_pages)
99                 num_pages = 0;
100
101         /* we want to return a uint32_t and more than this looks suspicious
102          * anyway ... */
103         if (num_pages > UINT32_MAX)
104                 num_pages = UINT32_MAX;
105
106         return num_pages;
107 }
108
109 static uint32_t
110 get_num_hugepages_on_node(const char *subdir, unsigned int socket)
111 {
112         char path[PATH_MAX], socketpath[PATH_MAX];
113         DIR *socketdir;
114         unsigned long num_pages = 0;
115         const char *nr_hp_file = "free_hugepages";
116
117         snprintf(socketpath, sizeof(socketpath), "%s/node%u/hugepages",
118                 sys_pages_numa_dir_path, socket);
119
120         socketdir = opendir(socketpath);
121         if (socketdir) {
122                 /* Keep calm and carry on */
123                 closedir(socketdir);
124         } else {
125                 /* Can't find socket dir, so ignore it */
126                 return 0;
127         }
128
129         snprintf(path, sizeof(path), "%s/%s/%s",
130                         socketpath, subdir, nr_hp_file);
131         if (eal_parse_sysfs_value(path, &num_pages) < 0)
132                 return 0;
133
134         if (num_pages == 0)
135                 RTE_LOG(WARNING, EAL, "No free hugepages reported in %s\n",
136                                 subdir);
137
138         /*
139          * we want to return a uint32_t and more than this looks suspicious
140          * anyway ...
141          */
142         if (num_pages > UINT32_MAX)
143                 num_pages = UINT32_MAX;
144
145         return num_pages;
146 }
147
148 static uint64_t
149 get_default_hp_size(void)
150 {
151         const char proc_meminfo[] = "/proc/meminfo";
152         const char str_hugepagesz[] = "Hugepagesize:";
153         unsigned hugepagesz_len = sizeof(str_hugepagesz) - 1;
154         char buffer[256];
155         unsigned long long size = 0;
156
157         FILE *fd = fopen(proc_meminfo, "r");
158         if (fd == NULL)
159                 rte_panic("Cannot open %s\n", proc_meminfo);
160         while(fgets(buffer, sizeof(buffer), fd)){
161                 if (strncmp(buffer, str_hugepagesz, hugepagesz_len) == 0){
162                         size = rte_str_to_size(&buffer[hugepagesz_len]);
163                         break;
164                 }
165         }
166         fclose(fd);
167         if (size == 0)
168                 rte_panic("Cannot get default hugepage size from %s\n", proc_meminfo);
169         return size;
170 }
171
172 static const char *
173 get_hugepage_dir(uint64_t hugepage_sz)
174 {
175         enum proc_mount_fieldnames {
176                 DEVICE = 0,
177                 MOUNTPT,
178                 FSTYPE,
179                 OPTIONS,
180                 _FIELDNAME_MAX
181         };
182         static uint64_t default_size = 0;
183         const char proc_mounts[] = "/proc/mounts";
184         const char hugetlbfs_str[] = "hugetlbfs";
185         const size_t htlbfs_str_len = sizeof(hugetlbfs_str) - 1;
186         const char pagesize_opt[] = "pagesize=";
187         const size_t pagesize_opt_len = sizeof(pagesize_opt) - 1;
188         const char split_tok = ' ';
189         char *splitstr[_FIELDNAME_MAX];
190         char buf[BUFSIZ];
191         char *retval = NULL;
192
193         FILE *fd = fopen(proc_mounts, "r");
194         if (fd == NULL)
195                 rte_panic("Cannot open %s\n", proc_mounts);
196
197         if (default_size == 0)
198                 default_size = get_default_hp_size();
199
200         while (fgets(buf, sizeof(buf), fd)){
201                 if (rte_strsplit(buf, sizeof(buf), splitstr, _FIELDNAME_MAX,
202                                 split_tok) != _FIELDNAME_MAX) {
203                         RTE_LOG(ERR, EAL, "Error parsing %s\n", proc_mounts);
204                         break; /* return NULL */
205                 }
206
207                 /* we have a specified --huge-dir option, only examine that dir */
208                 if (internal_config.hugepage_dir != NULL &&
209                                 strcmp(splitstr[MOUNTPT], internal_config.hugepage_dir) != 0)
210                         continue;
211
212                 if (strncmp(splitstr[FSTYPE], hugetlbfs_str, htlbfs_str_len) == 0){
213                         const char *pagesz_str = strstr(splitstr[OPTIONS], pagesize_opt);
214
215                         /* if no explicit page size, the default page size is compared */
216                         if (pagesz_str == NULL){
217                                 if (hugepage_sz == default_size){
218                                         retval = strdup(splitstr[MOUNTPT]);
219                                         break;
220                                 }
221                         }
222                         /* there is an explicit page size, so check it */
223                         else {
224                                 uint64_t pagesz = rte_str_to_size(&pagesz_str[pagesize_opt_len]);
225                                 if (pagesz == hugepage_sz) {
226                                         retval = strdup(splitstr[MOUNTPT]);
227                                         break;
228                                 }
229                         }
230                 } /* end if strncmp hugetlbfs */
231         } /* end while fgets */
232
233         fclose(fd);
234         return retval;
235 }
236
237 /*
238  * uses fstat to report the size of a file on disk
239  */
240 static off_t
241 get_file_size(int fd)
242 {
243         struct stat st;
244         if (fstat(fd, &st) < 0)
245                 return 0;
246         return st.st_size;
247 }
248
249 /*
250  * Clear the hugepage directory of whatever hugepage files
251  * there are. Checks if the file is locked (i.e.
252  * if it's in use by another DPDK process).
253  */
254 static int
255 clear_hugedir(const char * hugedir)
256 {
257         DIR *dir;
258         struct dirent *dirent;
259         int dir_fd, fd, lck_result;
260         const char filter[] = "*map_*"; /* matches hugepage files */
261
262         /* open directory */
263         dir = opendir(hugedir);
264         if (!dir) {
265                 RTE_LOG(ERR, EAL, "Unable to open hugepage directory %s\n",
266                                 hugedir);
267                 goto error;
268         }
269         dir_fd = dirfd(dir);
270
271         dirent = readdir(dir);
272         if (!dirent) {
273                 RTE_LOG(ERR, EAL, "Unable to read hugepage directory %s\n",
274                                 hugedir);
275                 goto error;
276         }
277
278         while(dirent != NULL){
279                 struct flock lck = {0};
280
281                 /* skip files that don't match the hugepage pattern */
282                 if (fnmatch(filter, dirent->d_name, 0) > 0) {
283                         dirent = readdir(dir);
284                         continue;
285                 }
286
287                 /* try and lock the file */
288                 fd = openat(dir_fd, dirent->d_name, O_RDONLY);
289
290                 /* skip to next file */
291                 if (fd == -1) {
292                         dirent = readdir(dir);
293                         continue;
294                 }
295
296                 /* non-blocking lock */
297                 lck.l_type = F_RDLCK;
298                 lck.l_whence = SEEK_SET;
299                 lck.l_start = 0;
300                 lck.l_len = get_file_size(fd);
301
302                 lck_result = fcntl(fd, F_SETLK, &lck);
303
304                 /* if lock succeeds, unlock and remove the file */
305                 if (lck_result != -1) {
306                         lck.l_type = F_UNLCK;
307                         fcntl(fd, F_SETLK, &lck);
308                         unlinkat(dir_fd, dirent->d_name, 0);
309                 }
310                 close (fd);
311                 dirent = readdir(dir);
312         }
313
314         closedir(dir);
315         return 0;
316
317 error:
318         if (dir)
319                 closedir(dir);
320
321         RTE_LOG(ERR, EAL, "Error while clearing hugepage dir: %s\n",
322                 strerror(errno));
323
324         return -1;
325 }
326
327 static int
328 compare_hpi(const void *a, const void *b)
329 {
330         const struct hugepage_info *hpi_a = a;
331         const struct hugepage_info *hpi_b = b;
332
333         return hpi_b->hugepage_sz - hpi_a->hugepage_sz;
334 }
335
336 static int
337 hugepage_info_init(void)
338 {       const char dirent_start_text[] = "hugepages-";
339         const size_t dirent_start_len = sizeof(dirent_start_text) - 1;
340         unsigned int i, total_pages, num_sizes = 0;
341         DIR *dir;
342         struct dirent *dirent;
343
344         dir = opendir(sys_dir_path);
345         if (dir == NULL) {
346                 RTE_LOG(ERR, EAL,
347                         "Cannot open directory %s to read system hugepage info\n",
348                         sys_dir_path);
349                 return -1;
350         }
351
352         for (dirent = readdir(dir); dirent != NULL; dirent = readdir(dir)) {
353                 struct hugepage_info *hpi;
354                 const char *hugedir;
355
356                 if (strncmp(dirent->d_name, dirent_start_text,
357                             dirent_start_len) != 0)
358                         continue;
359
360                 if (num_sizes >= MAX_HUGEPAGE_SIZES)
361                         break;
362
363                 hpi = &internal_config.hugepage_info[num_sizes];
364                 hpi->hugepage_sz =
365                         rte_str_to_size(&dirent->d_name[dirent_start_len]);
366                 hugedir = get_hugepage_dir(hpi->hugepage_sz);
367
368                 /* first, check if we have a mountpoint */
369                 if (hugedir == NULL) {
370                         uint32_t num_pages;
371
372                         num_pages = get_num_hugepages(dirent->d_name);
373                         if (num_pages > 0)
374                                 RTE_LOG(NOTICE, EAL,
375                                         "%" PRIu32 " hugepages of size "
376                                         "%" PRIu64 " reserved, but no mounted "
377                                         "hugetlbfs found for that size\n",
378                                         num_pages, hpi->hugepage_sz);
379                         continue;
380                 }
381                 snprintf(hpi->hugedir, sizeof(hpi->hugedir), "%s", hugedir);
382
383                 /* try to obtain a writelock */
384                 hpi->lock_descriptor = open(hpi->hugedir, O_RDONLY);
385
386                 /* if blocking lock failed */
387                 if (flock(hpi->lock_descriptor, LOCK_EX) == -1) {
388                         RTE_LOG(CRIT, EAL,
389                                 "Failed to lock hugepage directory!\n");
390                         break;
391                 }
392                 /* clear out the hugepages dir from unused pages */
393                 if (clear_hugedir(hpi->hugedir) == -1)
394                         break;
395
396                 /*
397                  * first, try to put all hugepages into relevant sockets, but
398                  * if first attempts fails, fall back to collecting all pages
399                  * in one socket and sorting them later
400                  */
401                 total_pages = 0;
402                 /* we also don't want to do this for legacy init */
403                 if (!internal_config.legacy_mem)
404                         for (i = 0; i < rte_socket_count(); i++) {
405                                 int socket = rte_socket_id_by_idx(i);
406                                 unsigned int num_pages =
407                                                 get_num_hugepages_on_node(
408                                                         dirent->d_name, socket);
409                                 hpi->num_pages[socket] = num_pages;
410                                 total_pages += num_pages;
411                         }
412                 /*
413                  * we failed to sort memory from the get go, so fall
414                  * back to old way
415                  */
416                 if (total_pages == 0)
417                         hpi->num_pages[0] = get_num_hugepages(dirent->d_name);
418
419 #ifndef RTE_ARCH_64
420                 /* for 32-bit systems, limit number of hugepages to
421                  * 1GB per page size */
422                 hpi->num_pages[0] = RTE_MIN(hpi->num_pages[0],
423                                             RTE_PGSIZE_1G / hpi->hugepage_sz);
424 #endif
425
426                 num_sizes++;
427         }
428         closedir(dir);
429
430         /* something went wrong, and we broke from the for loop above */
431         if (dirent != NULL)
432                 return -1;
433
434         internal_config.num_hugepage_sizes = num_sizes;
435
436         /* sort the page directory entries by size, largest to smallest */
437         qsort(&internal_config.hugepage_info[0], num_sizes,
438               sizeof(internal_config.hugepage_info[0]), compare_hpi);
439
440         /* now we have all info, check we have at least one valid size */
441         for (i = 0; i < num_sizes; i++) {
442                 /* pages may no longer all be on socket 0, so check all */
443                 unsigned int j, num_pages = 0;
444                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
445
446                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
447                         num_pages += hpi->num_pages[j];
448                 if (strnlen(hpi->hugedir, sizeof(hpi->hugedir)) != 0 &&
449                                 num_pages > 0)
450                         return 0;
451         }
452
453         /* no valid hugepage mounts available, return error */
454         return -1;
455 }
456
457 /*
458  * when we initialize the hugepage info, everything goes
459  * to socket 0 by default. it will later get sorted by memory
460  * initialization procedure.
461  */
462 int
463 eal_hugepage_info_init(void)
464 {
465         struct hugepage_info *hpi, *tmp_hpi;
466         unsigned int i;
467
468         if (hugepage_info_init() < 0)
469                 return -1;
470
471         hpi = &internal_config.hugepage_info[0];
472
473         tmp_hpi = create_shared_memory(eal_hugepage_info_path(),
474                         sizeof(internal_config.hugepage_info));
475         if (tmp_hpi == NULL) {
476                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
477                 return -1;
478         }
479
480         memcpy(tmp_hpi, hpi, sizeof(internal_config.hugepage_info));
481
482         /* we've copied file descriptors along with everything else, but they
483          * will be invalid in secondary process, so overwrite them
484          */
485         for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
486                 struct hugepage_info *tmp = &tmp_hpi[i];
487                 tmp->lock_descriptor = -1;
488         }
489
490         if (munmap(tmp_hpi, sizeof(internal_config.hugepage_info)) < 0) {
491                 RTE_LOG(ERR, EAL, "Failed to unmap shared memory!\n");
492                 return -1;
493         }
494         return 0;
495 }
496
497 int eal_hugepage_info_read(void)
498 {
499         struct hugepage_info *hpi = &internal_config.hugepage_info[0];
500         struct hugepage_info *tmp_hpi;
501
502         tmp_hpi = open_shared_memory(eal_hugepage_info_path(),
503                                   sizeof(internal_config.hugepage_info));
504         if (tmp_hpi == NULL) {
505                 RTE_LOG(ERR, EAL, "Failed to open shared memory!\n");
506                 return -1;
507         }
508
509         memcpy(hpi, tmp_hpi, sizeof(internal_config.hugepage_info));
510
511         if (munmap(tmp_hpi, sizeof(internal_config.hugepage_info)) < 0) {
512                 RTE_LOG(ERR, EAL, "Failed to unmap shared memory!\n");
513                 return -1;
514         }
515         return 0;
516 }