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