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