mem: exclude unused memory from core dump
[dpdk.git] / lib / librte_eal / linux / eal_memalloc.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2017-2018 Intel Corporation
3  */
4
5 #include <errno.h>
6 #include <stdarg.h>
7 #include <stdbool.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <inttypes.h>
12 #include <string.h>
13 #include <sys/mman.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <sys/queue.h>
17 #include <sys/file.h>
18 #include <unistd.h>
19 #include <limits.h>
20 #include <fcntl.h>
21 #include <sys/ioctl.h>
22 #include <sys/time.h>
23 #include <signal.h>
24 #include <setjmp.h>
25 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
26 #include <linux/memfd.h>
27 #define MEMFD_SUPPORTED
28 #endif
29 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
30 #include <numa.h>
31 #include <numaif.h>
32 #endif
33 #include <linux/falloc.h>
34 #include <linux/mman.h> /* for hugetlb-related mmap flags */
35
36 #include <rte_common.h>
37 #include <rte_log.h>
38 #include <rte_eal.h>
39 #include <rte_errno.h>
40 #include <rte_memory.h>
41 #include <rte_spinlock.h>
42
43 #include "eal_filesystem.h"
44 #include "eal_internal_cfg.h"
45 #include "eal_memalloc.h"
46 #include "eal_memcfg.h"
47 #include "eal_private.h"
48
49 const int anonymous_hugepages_supported =
50 #ifdef MAP_HUGE_SHIFT
51                 1;
52 #define RTE_MAP_HUGE_SHIFT MAP_HUGE_SHIFT
53 #else
54                 0;
55 #define RTE_MAP_HUGE_SHIFT 26
56 #endif
57
58 /*
59  * we've already checked memfd support at compile-time, but we also need to
60  * check if we can create hugepage files with memfd.
61  *
62  * also, this is not a constant, because while we may be *compiled* with memfd
63  * hugetlbfs support, we might not be *running* on a system that supports memfd
64  * and/or memfd with hugetlbfs, so we need to be able to adjust this flag at
65  * runtime, and fall back to anonymous memory.
66  */
67 static int memfd_create_supported =
68 #ifdef MFD_HUGETLB
69                 1;
70 #define RTE_MFD_HUGETLB MFD_HUGETLB
71 #else
72                 0;
73 #define RTE_MFD_HUGETLB 4U
74 #endif
75
76 /*
77  * not all kernel version support fallocate on hugetlbfs, so fall back to
78  * ftruncate and disallow deallocation if fallocate is not supported.
79  */
80 static int fallocate_supported = -1; /* unknown */
81
82 /*
83  * we have two modes - single file segments, and file-per-page mode.
84  *
85  * for single-file segments, we use memseg_list_fd to store the segment fd,
86  * while the fds[] will not be allocated, and len will be set to 0.
87  *
88  * for file-per-page mode, each page will have its own fd, so 'memseg_list_fd'
89  * will be invalid (set to -1), and we'll use 'fds' to keep track of page fd's.
90  *
91  * we cannot know how many pages a system will have in advance, but we do know
92  * that they come in lists, and we know lengths of these lists. so, simply store
93  * a malloc'd array of fd's indexed by list and segment index.
94  *
95  * they will be initialized at startup, and filled as we allocate/deallocate
96  * segments.
97  */
98 static struct {
99         int *fds; /**< dynamically allocated array of segment lock fd's */
100         int memseg_list_fd; /**< memseg list fd */
101         int len; /**< total length of the array */
102         int count; /**< entries used in an array */
103 } fd_list[RTE_MAX_MEMSEG_LISTS];
104
105 /** local copy of a memory map, used to synchronize memory hotplug in MP */
106 static struct rte_memseg_list local_memsegs[RTE_MAX_MEMSEG_LISTS];
107
108 static sigjmp_buf huge_jmpenv;
109
110 static void __rte_unused huge_sigbus_handler(int signo __rte_unused)
111 {
112         siglongjmp(huge_jmpenv, 1);
113 }
114
115 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
116  * non-static local variable in the stack frame calling sigsetjmp might be
117  * clobbered by a call to longjmp.
118  */
119 static int __rte_unused huge_wrap_sigsetjmp(void)
120 {
121         return sigsetjmp(huge_jmpenv, 1);
122 }
123
124 static struct sigaction huge_action_old;
125 static int huge_need_recover;
126
127 static void __rte_unused
128 huge_register_sigbus(void)
129 {
130         sigset_t mask;
131         struct sigaction action;
132
133         sigemptyset(&mask);
134         sigaddset(&mask, SIGBUS);
135         action.sa_flags = 0;
136         action.sa_mask = mask;
137         action.sa_handler = huge_sigbus_handler;
138
139         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
140 }
141
142 static void __rte_unused
143 huge_recover_sigbus(void)
144 {
145         if (huge_need_recover) {
146                 sigaction(SIGBUS, &huge_action_old, NULL);
147                 huge_need_recover = 0;
148         }
149 }
150
151 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
152 static bool
153 check_numa(void)
154 {
155         bool ret = true;
156         /* Check if kernel supports NUMA. */
157         if (numa_available() != 0) {
158                 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
159                 ret = false;
160         }
161         return ret;
162 }
163
164 static void
165 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
166 {
167         RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
168         if (get_mempolicy(oldpolicy, oldmask->maskp,
169                           oldmask->size + 1, 0, 0) < 0) {
170                 RTE_LOG(ERR, EAL,
171                         "Failed to get current mempolicy: %s. "
172                         "Assuming MPOL_DEFAULT.\n", strerror(errno));
173                 *oldpolicy = MPOL_DEFAULT;
174         }
175         RTE_LOG(DEBUG, EAL,
176                 "Setting policy MPOL_PREFERRED for socket %d\n",
177                 socket_id);
178         numa_set_preferred(socket_id);
179 }
180
181 static void
182 restore_numa(int *oldpolicy, struct bitmask *oldmask)
183 {
184         RTE_LOG(DEBUG, EAL,
185                 "Restoring previous memory policy: %d\n", *oldpolicy);
186         if (*oldpolicy == MPOL_DEFAULT) {
187                 numa_set_localalloc();
188         } else if (set_mempolicy(*oldpolicy, oldmask->maskp,
189                                  oldmask->size + 1) < 0) {
190                 RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
191                         strerror(errno));
192                 numa_set_localalloc();
193         }
194         numa_free_cpumask(oldmask);
195 }
196 #endif
197
198 /*
199  * uses fstat to report the size of a file on disk
200  */
201 static off_t
202 get_file_size(int fd)
203 {
204         struct stat st;
205         if (fstat(fd, &st) < 0)
206                 return 0;
207         return st.st_size;
208 }
209
210 static int
211 pagesz_flags(uint64_t page_sz)
212 {
213         /* as per mmap() manpage, all page sizes are log2 of page size
214          * shifted by MAP_HUGE_SHIFT
215          */
216         int log2 = rte_log2_u64(page_sz);
217         return log2 << RTE_MAP_HUGE_SHIFT;
218 }
219
220 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
221 static int lock(int fd, int type)
222 {
223         int ret;
224
225         /* flock may be interrupted */
226         do {
227                 ret = flock(fd, type | LOCK_NB);
228         } while (ret && errno == EINTR);
229
230         if (ret && errno == EWOULDBLOCK) {
231                 /* couldn't lock */
232                 return 0;
233         } else if (ret) {
234                 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
235                         __func__, strerror(errno));
236                 return -1;
237         }
238         /* lock was successful */
239         return 1;
240 }
241
242 static int
243 get_seg_memfd(struct hugepage_info *hi __rte_unused,
244                 unsigned int list_idx __rte_unused,
245                 unsigned int seg_idx __rte_unused)
246 {
247 #ifdef MEMFD_SUPPORTED
248         int fd;
249         char segname[250]; /* as per manpage, limit is 249 bytes plus null */
250
251         int flags = RTE_MFD_HUGETLB | pagesz_flags(hi->hugepage_sz);
252
253         if (internal_config.single_file_segments) {
254                 fd = fd_list[list_idx].memseg_list_fd;
255
256                 if (fd < 0) {
257                         snprintf(segname, sizeof(segname), "seg_%i", list_idx);
258                         fd = memfd_create(segname, flags);
259                         if (fd < 0) {
260                                 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
261                                         __func__, strerror(errno));
262                                 return -1;
263                         }
264                         fd_list[list_idx].memseg_list_fd = fd;
265                 }
266         } else {
267                 fd = fd_list[list_idx].fds[seg_idx];
268
269                 if (fd < 0) {
270                         snprintf(segname, sizeof(segname), "seg_%i-%i",
271                                         list_idx, seg_idx);
272                         fd = memfd_create(segname, flags);
273                         if (fd < 0) {
274                                 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
275                                         __func__, strerror(errno));
276                                 return -1;
277                         }
278                         fd_list[list_idx].fds[seg_idx] = fd;
279                 }
280         }
281         return fd;
282 #endif
283         return -1;
284 }
285
286 static int
287 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
288                 unsigned int list_idx, unsigned int seg_idx)
289 {
290         int fd;
291
292         /* for in-memory mode, we only make it here when we're sure we support
293          * memfd, and this is a special case.
294          */
295         if (internal_config.in_memory)
296                 return get_seg_memfd(hi, list_idx, seg_idx);
297
298         if (internal_config.single_file_segments) {
299                 /* create a hugepage file path */
300                 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
301
302                 fd = fd_list[list_idx].memseg_list_fd;
303
304                 if (fd < 0) {
305                         fd = open(path, O_CREAT | O_RDWR, 0600);
306                         if (fd < 0) {
307                                 RTE_LOG(ERR, EAL, "%s(): open failed: %s\n",
308                                         __func__, strerror(errno));
309                                 return -1;
310                         }
311                         /* take out a read lock and keep it indefinitely */
312                         if (lock(fd, LOCK_SH) < 0) {
313                                 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
314                                         __func__, strerror(errno));
315                                 close(fd);
316                                 return -1;
317                         }
318                         fd_list[list_idx].memseg_list_fd = fd;
319                 }
320         } else {
321                 /* create a hugepage file path */
322                 eal_get_hugefile_path(path, buflen, hi->hugedir,
323                                 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
324
325                 fd = fd_list[list_idx].fds[seg_idx];
326
327                 if (fd < 0) {
328                         fd = open(path, O_CREAT | O_RDWR, 0600);
329                         if (fd < 0) {
330                                 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
331                                         __func__, strerror(errno));
332                                 return -1;
333                         }
334                         /* take out a read lock */
335                         if (lock(fd, LOCK_SH) < 0) {
336                                 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
337                                         __func__, strerror(errno));
338                                 close(fd);
339                                 return -1;
340                         }
341                         fd_list[list_idx].fds[seg_idx] = fd;
342                 }
343         }
344         return fd;
345 }
346
347 static int
348 resize_hugefile_in_memory(int fd, uint64_t fa_offset,
349                 uint64_t page_sz, bool grow)
350 {
351         int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
352                         FALLOC_FL_KEEP_SIZE;
353         int ret;
354
355         /* grow or shrink the file */
356         ret = fallocate(fd, flags, fa_offset, page_sz);
357
358         if (ret < 0) {
359                 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
360                                 __func__,
361                                 strerror(errno));
362                 return -1;
363         }
364         return 0;
365 }
366
367 static int
368 resize_hugefile_in_filesystem(int fd, uint64_t fa_offset, uint64_t page_sz,
369                 bool grow)
370 {
371         bool again = false;
372
373         do {
374                 if (fallocate_supported == 0) {
375                         /* we cannot deallocate memory if fallocate() is not
376                          * supported, and hugepage file is already locked at
377                          * creation, so no further synchronization needed.
378                          */
379
380                         if (!grow) {
381                                 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
382                                         __func__);
383                                 return -1;
384                         }
385                         uint64_t new_size = fa_offset + page_sz;
386                         uint64_t cur_size = get_file_size(fd);
387
388                         /* fallocate isn't supported, fall back to ftruncate */
389                         if (new_size > cur_size &&
390                                         ftruncate(fd, new_size) < 0) {
391                                 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
392                                         __func__, strerror(errno));
393                                 return -1;
394                         }
395                 } else {
396                         int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
397                                         FALLOC_FL_KEEP_SIZE;
398                         int ret;
399
400                         /*
401                          * technically, it is perfectly safe for both primary
402                          * and secondary to grow and shrink the page files:
403                          * growing the file repeatedly has no effect because
404                          * a page can only be allocated once, while mmap ensures
405                          * that secondaries hold on to the page even after the
406                          * page itself is removed from the filesystem.
407                          *
408                          * however, leaving growing/shrinking to the primary
409                          * tends to expose bugs in fdlist page count handling,
410                          * so leave this here just in case.
411                          */
412                         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
413                                 return 0;
414
415                         /* grow or shrink the file */
416                         ret = fallocate(fd, flags, fa_offset, page_sz);
417
418                         if (ret < 0) {
419                                 if (fallocate_supported == -1 &&
420                                                 errno == ENOTSUP) {
421                                         RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
422                                                 __func__);
423                                         again = true;
424                                         fallocate_supported = 0;
425                                 } else {
426                                         RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
427                                                 __func__,
428                                                 strerror(errno));
429                                         return -1;
430                                 }
431                         } else
432                                 fallocate_supported = 1;
433                 }
434         } while (again);
435
436         return 0;
437 }
438
439 static void
440 close_hugefile(int fd, char *path, int list_idx)
441 {
442         /*
443          * primary process must unlink the file, but only when not in in-memory
444          * mode (as in that case there is no file to unlink).
445          */
446         if (!internal_config.in_memory &&
447                         rte_eal_process_type() == RTE_PROC_PRIMARY &&
448                         unlink(path))
449                 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
450                         __func__, path, strerror(errno));
451
452         close(fd);
453         fd_list[list_idx].memseg_list_fd = -1;
454 }
455
456 static int
457 resize_hugefile(int fd, uint64_t fa_offset, uint64_t page_sz, bool grow)
458 {
459         /* in-memory mode is a special case, because we can be sure that
460          * fallocate() is supported.
461          */
462         if (internal_config.in_memory)
463                 return resize_hugefile_in_memory(fd, fa_offset,
464                                 page_sz, grow);
465
466         return resize_hugefile_in_filesystem(fd, fa_offset, page_sz,
467                                 grow);
468 }
469
470 static int
471 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
472                 struct hugepage_info *hi, unsigned int list_idx,
473                 unsigned int seg_idx)
474 {
475 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
476         int cur_socket_id = 0;
477 #endif
478         uint64_t map_offset;
479         rte_iova_t iova;
480         void *va;
481         char path[PATH_MAX];
482         int ret = 0;
483         int fd;
484         size_t alloc_sz;
485         int flags;
486         void *new_addr;
487
488         alloc_sz = hi->hugepage_sz;
489
490         /* these are checked at init, but code analyzers don't know that */
491         if (internal_config.in_memory && !anonymous_hugepages_supported) {
492                 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
493                 return -1;
494         }
495         if (internal_config.in_memory && !memfd_create_supported &&
496                         internal_config.single_file_segments) {
497                 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
498                 return -1;
499         }
500
501         /* in-memory without memfd is a special case */
502         int mmap_flags;
503
504         if (internal_config.in_memory && !memfd_create_supported) {
505                 const int in_memory_flags = MAP_HUGETLB | MAP_FIXED |
506                                 MAP_PRIVATE | MAP_ANONYMOUS;
507                 int pagesz_flag;
508
509                 pagesz_flag = pagesz_flags(alloc_sz);
510                 fd = -1;
511                 mmap_flags = in_memory_flags | pagesz_flag;
512
513                 /* single-file segments codepath will never be active
514                  * here because in-memory mode is incompatible with the
515                  * fallback path, and it's stopped at EAL initialization
516                  * stage.
517                  */
518                 map_offset = 0;
519         } else {
520                 /* takes out a read lock on segment or segment list */
521                 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
522                 if (fd < 0) {
523                         RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
524                         return -1;
525                 }
526
527                 if (internal_config.single_file_segments) {
528                         map_offset = seg_idx * alloc_sz;
529                         ret = resize_hugefile(fd, map_offset, alloc_sz, true);
530                         if (ret < 0)
531                                 goto resized;
532
533                         fd_list[list_idx].count++;
534                 } else {
535                         map_offset = 0;
536                         if (ftruncate(fd, alloc_sz) < 0) {
537                                 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
538                                         __func__, strerror(errno));
539                                 goto resized;
540                         }
541                         if (internal_config.hugepage_unlink &&
542                                         !internal_config.in_memory) {
543                                 if (unlink(path)) {
544                                         RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
545                                                 __func__, strerror(errno));
546                                         goto resized;
547                                 }
548                         }
549                 }
550                 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
551         }
552
553         /*
554          * map the segment, and populate page tables, the kernel fills
555          * this segment with zeros if it's a new page.
556          */
557         va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
558                         map_offset);
559
560         if (va == MAP_FAILED) {
561                 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
562                         strerror(errno));
563                 /* mmap failed, but the previous region might have been
564                  * unmapped anyway. try to remap it
565                  */
566                 goto unmapped;
567         }
568         if (va != addr) {
569                 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
570                 munmap(va, alloc_sz);
571                 goto resized;
572         }
573
574         /* In linux, hugetlb limitations, like cgroup, are
575          * enforced at fault time instead of mmap(), even
576          * with the option of MAP_POPULATE. Kernel will send
577          * a SIGBUS signal. To avoid to be killed, save stack
578          * environment here, if SIGBUS happens, we can jump
579          * back here.
580          */
581         if (huge_wrap_sigsetjmp()) {
582                 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
583                         (unsigned int)(alloc_sz >> 20));
584                 goto mapped;
585         }
586
587         /* we need to trigger a write to the page to enforce page fault and
588          * ensure that page is accessible to us, but we can't overwrite value
589          * that is already there, so read the old value, and write itback.
590          * kernel populates the page with zeroes initially.
591          */
592         *(volatile int *)addr = *(volatile int *)addr;
593
594         iova = rte_mem_virt2iova(addr);
595         if (iova == RTE_BAD_PHYS_ADDR) {
596                 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
597                         __func__);
598                 goto mapped;
599         }
600
601 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
602         ret = get_mempolicy(&cur_socket_id, NULL, 0, addr,
603                             MPOL_F_NODE | MPOL_F_ADDR);
604         if (ret < 0) {
605                 RTE_LOG(DEBUG, EAL, "%s(): get_mempolicy: %s\n",
606                         __func__, strerror(errno));
607                 goto mapped;
608         } else if (cur_socket_id != socket_id) {
609                 RTE_LOG(DEBUG, EAL,
610                                 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
611                         __func__, socket_id, cur_socket_id);
612                 goto mapped;
613         }
614 #else
615         if (rte_socket_count() > 1)
616                 RTE_LOG(DEBUG, EAL, "%s(): not checking hugepage NUMA node.\n",
617                                 __func__);
618 #endif
619
620         ms->addr = addr;
621         ms->hugepage_sz = alloc_sz;
622         ms->len = alloc_sz;
623         ms->nchannel = rte_memory_get_nchannel();
624         ms->nrank = rte_memory_get_nrank();
625         ms->iova = iova;
626         ms->socket_id = socket_id;
627
628         return 0;
629
630 mapped:
631         munmap(addr, alloc_sz);
632 unmapped:
633         flags = MAP_FIXED;
634         new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
635         if (new_addr != addr) {
636                 if (new_addr != NULL)
637                         munmap(new_addr, alloc_sz);
638                 /* we're leaving a hole in our virtual address space. if
639                  * somebody else maps this hole now, we could accidentally
640                  * override it in the future.
641                  */
642                 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
643         }
644         /* roll back the ref count */
645         if (internal_config.single_file_segments)
646                 fd_list[list_idx].count--;
647 resized:
648         /* some codepaths will return negative fd, so exit early */
649         if (fd < 0)
650                 return -1;
651
652         if (internal_config.single_file_segments) {
653                 resize_hugefile(fd, map_offset, alloc_sz, false);
654                 /* ignore failure, can't make it any worse */
655
656                 /* if refcount is at zero, close the file */
657                 if (fd_list[list_idx].count == 0)
658                         close_hugefile(fd, path, list_idx);
659         } else {
660                 /* only remove file if we can take out a write lock */
661                 if (internal_config.hugepage_unlink == 0 &&
662                                 internal_config.in_memory == 0 &&
663                                 lock(fd, LOCK_EX) == 1)
664                         unlink(path);
665                 close(fd);
666                 fd_list[list_idx].fds[seg_idx] = -1;
667         }
668         return -1;
669 }
670
671 static int
672 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
673                 unsigned int list_idx, unsigned int seg_idx)
674 {
675         uint64_t map_offset;
676         char path[PATH_MAX];
677         int fd, ret = 0;
678         bool exit_early;
679
680         /* erase page data */
681         memset(ms->addr, 0, ms->len);
682
683         if (mmap(ms->addr, ms->len, PROT_NONE,
684                         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
685                                 MAP_FAILED) {
686                 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
687                 return -1;
688         }
689
690         if (madvise(ms->addr, ms->len, MADV_DONTDUMP) != 0)
691                 RTE_LOG(DEBUG, EAL, "madvise failed: %s\n", strerror(errno));
692
693         exit_early = false;
694
695         /* if we're using anonymous hugepages, nothing to be done */
696         if (internal_config.in_memory && !memfd_create_supported)
697                 exit_early = true;
698
699         /* if we've already unlinked the page, nothing needs to be done */
700         if (!internal_config.in_memory && internal_config.hugepage_unlink)
701                 exit_early = true;
702
703         if (exit_early) {
704                 memset(ms, 0, sizeof(*ms));
705                 return 0;
706         }
707
708         /* if we are not in single file segments mode, we're going to unmap the
709          * segment and thus drop the lock on original fd, but hugepage dir is
710          * now locked so we can take out another one without races.
711          */
712         fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
713         if (fd < 0)
714                 return -1;
715
716         if (internal_config.single_file_segments) {
717                 map_offset = seg_idx * ms->len;
718                 if (resize_hugefile(fd, map_offset, ms->len, false))
719                         return -1;
720
721                 if (--(fd_list[list_idx].count) == 0)
722                         close_hugefile(fd, path, list_idx);
723
724                 ret = 0;
725         } else {
726                 /* if we're able to take out a write lock, we're the last one
727                  * holding onto this page.
728                  */
729                 if (!internal_config.in_memory) {
730                         ret = lock(fd, LOCK_EX);
731                         if (ret >= 0) {
732                                 /* no one else is using this page */
733                                 if (ret == 1)
734                                         unlink(path);
735                         }
736                 }
737                 /* closing fd will drop the lock */
738                 close(fd);
739                 fd_list[list_idx].fds[seg_idx] = -1;
740         }
741
742         memset(ms, 0, sizeof(*ms));
743
744         return ret < 0 ? -1 : 0;
745 }
746
747 struct alloc_walk_param {
748         struct hugepage_info *hi;
749         struct rte_memseg **ms;
750         size_t page_sz;
751         unsigned int segs_allocated;
752         unsigned int n_segs;
753         int socket;
754         bool exact;
755 };
756 static int
757 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
758 {
759         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
760         struct alloc_walk_param *wa = arg;
761         struct rte_memseg_list *cur_msl;
762         size_t page_sz;
763         int cur_idx, start_idx, j, dir_fd = -1;
764         unsigned int msl_idx, need, i;
765
766         if (msl->page_sz != wa->page_sz)
767                 return 0;
768         if (msl->socket_id != wa->socket)
769                 return 0;
770
771         page_sz = (size_t)msl->page_sz;
772
773         msl_idx = msl - mcfg->memsegs;
774         cur_msl = &mcfg->memsegs[msl_idx];
775
776         need = wa->n_segs;
777
778         /* try finding space in memseg list */
779         if (wa->exact) {
780                 /* if we require exact number of pages in a list, find them */
781                 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0,
782                                 need);
783                 if (cur_idx < 0)
784                         return 0;
785                 start_idx = cur_idx;
786         } else {
787                 int cur_len;
788
789                 /* we don't require exact number of pages, so we're going to go
790                  * for best-effort allocation. that means finding the biggest
791                  * unused block, and going with that.
792                  */
793                 cur_idx = rte_fbarray_find_biggest_free(&cur_msl->memseg_arr,
794                                 0);
795                 if (cur_idx < 0)
796                         return 0;
797                 start_idx = cur_idx;
798                 /* adjust the size to possibly be smaller than original
799                  * request, but do not allow it to be bigger.
800                  */
801                 cur_len = rte_fbarray_find_contig_free(&cur_msl->memseg_arr,
802                                 cur_idx);
803                 need = RTE_MIN(need, (unsigned int)cur_len);
804         }
805
806         /* do not allow any page allocations during the time we're allocating,
807          * because file creation and locking operations are not atomic,
808          * and we might be the first or the last ones to use a particular page,
809          * so we need to ensure atomicity of every operation.
810          *
811          * during init, we already hold a write lock, so don't try to take out
812          * another one.
813          */
814         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
815                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
816                 if (dir_fd < 0) {
817                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
818                                 __func__, wa->hi->hugedir, strerror(errno));
819                         return -1;
820                 }
821                 /* blocking writelock */
822                 if (flock(dir_fd, LOCK_EX)) {
823                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
824                                 __func__, wa->hi->hugedir, strerror(errno));
825                         close(dir_fd);
826                         return -1;
827                 }
828         }
829
830         for (i = 0; i < need; i++, cur_idx++) {
831                 struct rte_memseg *cur;
832                 void *map_addr;
833
834                 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
835                 map_addr = RTE_PTR_ADD(cur_msl->base_va,
836                                 cur_idx * page_sz);
837
838                 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
839                                 msl_idx, cur_idx)) {
840                         RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
841                                 need, i);
842
843                         /* if exact number wasn't requested, stop */
844                         if (!wa->exact)
845                                 goto out;
846
847                         /* clean up */
848                         for (j = start_idx; j < cur_idx; j++) {
849                                 struct rte_memseg *tmp;
850                                 struct rte_fbarray *arr =
851                                                 &cur_msl->memseg_arr;
852
853                                 tmp = rte_fbarray_get(arr, j);
854                                 rte_fbarray_set_free(arr, j);
855
856                                 /* free_seg may attempt to create a file, which
857                                  * may fail.
858                                  */
859                                 if (free_seg(tmp, wa->hi, msl_idx, j))
860                                         RTE_LOG(DEBUG, EAL, "Cannot free page\n");
861                         }
862                         /* clear the list */
863                         if (wa->ms)
864                                 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
865
866                         if (dir_fd >= 0)
867                                 close(dir_fd);
868                         return -1;
869                 }
870                 if (wa->ms)
871                         wa->ms[i] = cur;
872
873                 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
874         }
875 out:
876         wa->segs_allocated = i;
877         if (i > 0)
878                 cur_msl->version++;
879         if (dir_fd >= 0)
880                 close(dir_fd);
881         /* if we didn't allocate any segments, move on to the next list */
882         return i > 0;
883 }
884
885 struct free_walk_param {
886         struct hugepage_info *hi;
887         struct rte_memseg *ms;
888 };
889 static int
890 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
891 {
892         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
893         struct rte_memseg_list *found_msl;
894         struct free_walk_param *wa = arg;
895         uintptr_t start_addr, end_addr;
896         int msl_idx, seg_idx, ret, dir_fd = -1;
897
898         start_addr = (uintptr_t) msl->base_va;
899         end_addr = start_addr + msl->len;
900
901         if ((uintptr_t)wa->ms->addr < start_addr ||
902                         (uintptr_t)wa->ms->addr >= end_addr)
903                 return 0;
904
905         msl_idx = msl - mcfg->memsegs;
906         seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
907
908         /* msl is const */
909         found_msl = &mcfg->memsegs[msl_idx];
910
911         /* do not allow any page allocations during the time we're freeing,
912          * because file creation and locking operations are not atomic,
913          * and we might be the first or the last ones to use a particular page,
914          * so we need to ensure atomicity of every operation.
915          *
916          * during init, we already hold a write lock, so don't try to take out
917          * another one.
918          */
919         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
920                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
921                 if (dir_fd < 0) {
922                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
923                                 __func__, wa->hi->hugedir, strerror(errno));
924                         return -1;
925                 }
926                 /* blocking writelock */
927                 if (flock(dir_fd, LOCK_EX)) {
928                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
929                                 __func__, wa->hi->hugedir, strerror(errno));
930                         close(dir_fd);
931                         return -1;
932                 }
933         }
934
935         found_msl->version++;
936
937         rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
938
939         ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
940
941         if (dir_fd >= 0)
942                 close(dir_fd);
943
944         if (ret < 0)
945                 return -1;
946
947         return 1;
948 }
949
950 int
951 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
952                 int socket, bool exact)
953 {
954         int i, ret = -1;
955 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
956         bool have_numa = false;
957         int oldpolicy;
958         struct bitmask *oldmask;
959 #endif
960         struct alloc_walk_param wa;
961         struct hugepage_info *hi = NULL;
962
963         memset(&wa, 0, sizeof(wa));
964
965         /* dynamic allocation not supported in legacy mode */
966         if (internal_config.legacy_mem)
967                 return -1;
968
969         for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
970                 if (page_sz ==
971                                 internal_config.hugepage_info[i].hugepage_sz) {
972                         hi = &internal_config.hugepage_info[i];
973                         break;
974                 }
975         }
976         if (!hi) {
977                 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
978                         __func__);
979                 return -1;
980         }
981
982 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
983         if (check_numa()) {
984                 oldmask = numa_allocate_nodemask();
985                 prepare_numa(&oldpolicy, oldmask, socket);
986                 have_numa = true;
987         }
988 #endif
989
990         wa.exact = exact;
991         wa.hi = hi;
992         wa.ms = ms;
993         wa.n_segs = n_segs;
994         wa.page_sz = page_sz;
995         wa.socket = socket;
996         wa.segs_allocated = 0;
997
998         /* memalloc is locked, so it's safe to use thread-unsafe version */
999         ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1000         if (ret == 0) {
1001                 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1002                         __func__);
1003                 ret = -1;
1004         } else if (ret > 0) {
1005                 ret = (int)wa.segs_allocated;
1006         }
1007
1008 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1009         if (have_numa)
1010                 restore_numa(&oldpolicy, oldmask);
1011 #endif
1012         return ret;
1013 }
1014
1015 struct rte_memseg *
1016 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1017 {
1018         struct rte_memseg *ms;
1019         if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1020                 return NULL;
1021         /* return pointer to newly allocated memseg */
1022         return ms;
1023 }
1024
1025 int
1026 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1027 {
1028         int seg, ret = 0;
1029
1030         /* dynamic free not supported in legacy mode */
1031         if (internal_config.legacy_mem)
1032                 return -1;
1033
1034         for (seg = 0; seg < n_segs; seg++) {
1035                 struct rte_memseg *cur = ms[seg];
1036                 struct hugepage_info *hi = NULL;
1037                 struct free_walk_param wa;
1038                 int i, walk_res;
1039
1040                 /* if this page is marked as unfreeable, fail */
1041                 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1042                         RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1043                         ret = -1;
1044                         continue;
1045                 }
1046
1047                 memset(&wa, 0, sizeof(wa));
1048
1049                 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
1050                                 i++) {
1051                         hi = &internal_config.hugepage_info[i];
1052                         if (cur->hugepage_sz == hi->hugepage_sz)
1053                                 break;
1054                 }
1055                 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1056                         RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1057                         ret = -1;
1058                         continue;
1059                 }
1060
1061                 wa.ms = cur;
1062                 wa.hi = hi;
1063
1064                 /* memalloc is locked, so it's safe to use thread-unsafe version
1065                  */
1066                 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1067                                 &wa);
1068                 if (walk_res == 1)
1069                         continue;
1070                 if (walk_res == 0)
1071                         RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1072                 ret = -1;
1073         }
1074         return ret;
1075 }
1076
1077 int
1078 eal_memalloc_free_seg(struct rte_memseg *ms)
1079 {
1080         /* dynamic free not supported in legacy mode */
1081         if (internal_config.legacy_mem)
1082                 return -1;
1083
1084         return eal_memalloc_free_seg_bulk(&ms, 1);
1085 }
1086
1087 static int
1088 sync_chunk(struct rte_memseg_list *primary_msl,
1089                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1090                 unsigned int msl_idx, bool used, int start, int end)
1091 {
1092         struct rte_fbarray *l_arr, *p_arr;
1093         int i, ret, chunk_len, diff_len;
1094
1095         l_arr = &local_msl->memseg_arr;
1096         p_arr = &primary_msl->memseg_arr;
1097
1098         /* we need to aggregate allocations/deallocations into bigger chunks,
1099          * as we don't want to spam the user with per-page callbacks.
1100          *
1101          * to avoid any potential issues, we also want to trigger
1102          * deallocation callbacks *before* we actually deallocate
1103          * memory, so that the user application could wrap up its use
1104          * before it goes away.
1105          */
1106
1107         chunk_len = end - start;
1108
1109         /* find how many contiguous pages we can map/unmap for this chunk */
1110         diff_len = used ?
1111                         rte_fbarray_find_contig_free(l_arr, start) :
1112                         rte_fbarray_find_contig_used(l_arr, start);
1113
1114         /* has to be at least one page */
1115         if (diff_len < 1)
1116                 return -1;
1117
1118         diff_len = RTE_MIN(chunk_len, diff_len);
1119
1120         /* if we are freeing memory, notify the application */
1121         if (!used) {
1122                 struct rte_memseg *ms;
1123                 void *start_va;
1124                 size_t len, page_sz;
1125
1126                 ms = rte_fbarray_get(l_arr, start);
1127                 start_va = ms->addr;
1128                 page_sz = (size_t)primary_msl->page_sz;
1129                 len = page_sz * diff_len;
1130
1131                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1132                                 start_va, len);
1133         }
1134
1135         for (i = 0; i < diff_len; i++) {
1136                 struct rte_memseg *p_ms, *l_ms;
1137                 int seg_idx = start + i;
1138
1139                 l_ms = rte_fbarray_get(l_arr, seg_idx);
1140                 p_ms = rte_fbarray_get(p_arr, seg_idx);
1141
1142                 if (l_ms == NULL || p_ms == NULL)
1143                         return -1;
1144
1145                 if (used) {
1146                         ret = alloc_seg(l_ms, p_ms->addr,
1147                                         p_ms->socket_id, hi,
1148                                         msl_idx, seg_idx);
1149                         if (ret < 0)
1150                                 return -1;
1151                         rte_fbarray_set_used(l_arr, seg_idx);
1152                 } else {
1153                         ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1154                         rte_fbarray_set_free(l_arr, seg_idx);
1155                         if (ret < 0)
1156                                 return -1;
1157                 }
1158         }
1159
1160         /* if we just allocated memory, notify the application */
1161         if (used) {
1162                 struct rte_memseg *ms;
1163                 void *start_va;
1164                 size_t len, page_sz;
1165
1166                 ms = rte_fbarray_get(l_arr, start);
1167                 start_va = ms->addr;
1168                 page_sz = (size_t)primary_msl->page_sz;
1169                 len = page_sz * diff_len;
1170
1171                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1172                                 start_va, len);
1173         }
1174
1175         /* calculate how much we can advance until next chunk */
1176         diff_len = used ?
1177                         rte_fbarray_find_contig_used(l_arr, start) :
1178                         rte_fbarray_find_contig_free(l_arr, start);
1179         ret = RTE_MIN(chunk_len, diff_len);
1180
1181         return ret;
1182 }
1183
1184 static int
1185 sync_status(struct rte_memseg_list *primary_msl,
1186                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1187                 unsigned int msl_idx, bool used)
1188 {
1189         struct rte_fbarray *l_arr, *p_arr;
1190         int p_idx, l_chunk_len, p_chunk_len, ret;
1191         int start, end;
1192
1193         /* this is a little bit tricky, but the basic idea is - walk both lists
1194          * and spot any places where there are discrepancies. walking both lists
1195          * and noting discrepancies in a single go is a hard problem, so we do
1196          * it in two passes - first we spot any places where allocated segments
1197          * mismatch (i.e. ensure that everything that's allocated in the primary
1198          * is also allocated in the secondary), and then we do it by looking at
1199          * free segments instead.
1200          *
1201          * we also need to aggregate changes into chunks, as we have to call
1202          * callbacks per allocation, not per page.
1203          */
1204         l_arr = &local_msl->memseg_arr;
1205         p_arr = &primary_msl->memseg_arr;
1206
1207         if (used)
1208                 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1209         else
1210                 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1211
1212         while (p_idx >= 0) {
1213                 int next_chunk_search_idx;
1214
1215                 if (used) {
1216                         p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1217                                         p_idx);
1218                         l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1219                                         p_idx);
1220                 } else {
1221                         p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1222                                         p_idx);
1223                         l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1224                                         p_idx);
1225                 }
1226                 /* best case scenario - no differences (or bigger, which will be
1227                  * fixed during next iteration), look for next chunk
1228                  */
1229                 if (l_chunk_len >= p_chunk_len) {
1230                         next_chunk_search_idx = p_idx + p_chunk_len;
1231                         goto next_chunk;
1232                 }
1233
1234                 /* if both chunks start at the same point, skip parts we know
1235                  * are identical, and sync the rest. each call to sync_chunk
1236                  * will only sync contiguous segments, so we need to call this
1237                  * until we are sure there are no more differences in this
1238                  * chunk.
1239                  */
1240                 start = p_idx + l_chunk_len;
1241                 end = p_idx + p_chunk_len;
1242                 do {
1243                         ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1244                                         used, start, end);
1245                         start += ret;
1246                 } while (start < end && ret >= 0);
1247                 /* if ret is negative, something went wrong */
1248                 if (ret < 0)
1249                         return -1;
1250
1251                 next_chunk_search_idx = p_idx + p_chunk_len;
1252 next_chunk:
1253                 /* skip to end of this chunk */
1254                 if (used) {
1255                         p_idx = rte_fbarray_find_next_used(p_arr,
1256                                         next_chunk_search_idx);
1257                 } else {
1258                         p_idx = rte_fbarray_find_next_free(p_arr,
1259                                         next_chunk_search_idx);
1260                 }
1261         }
1262         return 0;
1263 }
1264
1265 static int
1266 sync_existing(struct rte_memseg_list *primary_msl,
1267                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1268                 unsigned int msl_idx)
1269 {
1270         int ret, dir_fd;
1271
1272         /* do not allow any page allocations during the time we're allocating,
1273          * because file creation and locking operations are not atomic,
1274          * and we might be the first or the last ones to use a particular page,
1275          * so we need to ensure atomicity of every operation.
1276          */
1277         dir_fd = open(hi->hugedir, O_RDONLY);
1278         if (dir_fd < 0) {
1279                 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1280                         hi->hugedir, strerror(errno));
1281                 return -1;
1282         }
1283         /* blocking writelock */
1284         if (flock(dir_fd, LOCK_EX)) {
1285                 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1286                         hi->hugedir, strerror(errno));
1287                 close(dir_fd);
1288                 return -1;
1289         }
1290
1291         /* ensure all allocated space is the same in both lists */
1292         ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1293         if (ret < 0)
1294                 goto fail;
1295
1296         /* ensure all unallocated space is the same in both lists */
1297         ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1298         if (ret < 0)
1299                 goto fail;
1300
1301         /* update version number */
1302         local_msl->version = primary_msl->version;
1303
1304         close(dir_fd);
1305
1306         return 0;
1307 fail:
1308         close(dir_fd);
1309         return -1;
1310 }
1311
1312 static int
1313 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1314 {
1315         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1316         struct rte_memseg_list *primary_msl, *local_msl;
1317         struct hugepage_info *hi = NULL;
1318         unsigned int i;
1319         int msl_idx;
1320
1321         if (msl->external)
1322                 return 0;
1323
1324         msl_idx = msl - mcfg->memsegs;
1325         primary_msl = &mcfg->memsegs[msl_idx];
1326         local_msl = &local_memsegs[msl_idx];
1327
1328         for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1329                 uint64_t cur_sz =
1330                         internal_config.hugepage_info[i].hugepage_sz;
1331                 uint64_t msl_sz = primary_msl->page_sz;
1332                 if (msl_sz == cur_sz) {
1333                         hi = &internal_config.hugepage_info[i];
1334                         break;
1335                 }
1336         }
1337         if (!hi) {
1338                 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1339                 return -1;
1340         }
1341
1342         /* if versions don't match, synchronize everything */
1343         if (local_msl->version != primary_msl->version &&
1344                         sync_existing(primary_msl, local_msl, hi, msl_idx))
1345                 return -1;
1346         return 0;
1347 }
1348
1349
1350 int
1351 eal_memalloc_sync_with_primary(void)
1352 {
1353         /* nothing to be done in primary */
1354         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1355                 return 0;
1356
1357         /* memalloc is locked, so it's safe to call thread-unsafe version */
1358         if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1359                 return -1;
1360         return 0;
1361 }
1362
1363 static int
1364 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1365                 void *arg __rte_unused)
1366 {
1367         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1368         struct rte_memseg_list *primary_msl, *local_msl;
1369         char name[PATH_MAX];
1370         int msl_idx, ret;
1371
1372         if (msl->external)
1373                 return 0;
1374
1375         msl_idx = msl - mcfg->memsegs;
1376         primary_msl = &mcfg->memsegs[msl_idx];
1377         local_msl = &local_memsegs[msl_idx];
1378
1379         /* create distinct fbarrays for each secondary */
1380         snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1381                 primary_msl->memseg_arr.name, getpid());
1382
1383         ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1384                 primary_msl->memseg_arr.len,
1385                 primary_msl->memseg_arr.elt_sz);
1386         if (ret < 0) {
1387                 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1388                 return -1;
1389         }
1390         local_msl->base_va = primary_msl->base_va;
1391         local_msl->len = primary_msl->len;
1392
1393         return 0;
1394 }
1395
1396 static int
1397 alloc_list(int list_idx, int len)
1398 {
1399         int *data;
1400         int i;
1401
1402         /* single-file segments mode does not need fd list */
1403         if (!internal_config.single_file_segments) {
1404                 /* ensure we have space to store fd per each possible segment */
1405                 data = malloc(sizeof(int) * len);
1406                 if (data == NULL) {
1407                         RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1408                         return -1;
1409                 }
1410                 /* set all fd's as invalid */
1411                 for (i = 0; i < len; i++)
1412                         data[i] = -1;
1413                 fd_list[list_idx].fds = data;
1414                 fd_list[list_idx].len = len;
1415         } else {
1416                 fd_list[list_idx].fds = NULL;
1417                 fd_list[list_idx].len = 0;
1418         }
1419
1420         fd_list[list_idx].count = 0;
1421         fd_list[list_idx].memseg_list_fd = -1;
1422
1423         return 0;
1424 }
1425
1426 static int
1427 fd_list_create_walk(const struct rte_memseg_list *msl,
1428                 void *arg __rte_unused)
1429 {
1430         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1431         unsigned int len;
1432         int msl_idx;
1433
1434         if (msl->external)
1435                 return 0;
1436
1437         msl_idx = msl - mcfg->memsegs;
1438         len = msl->memseg_arr.len;
1439
1440         return alloc_list(msl_idx, len);
1441 }
1442
1443 int
1444 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1445 {
1446         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1447
1448         /* single file segments mode doesn't support individual segment fd's */
1449         if (internal_config.single_file_segments)
1450                 return -ENOTSUP;
1451
1452         /* if list is not allocated, allocate it */
1453         if (fd_list[list_idx].len == 0) {
1454                 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1455
1456                 if (alloc_list(list_idx, len) < 0)
1457                         return -ENOMEM;
1458         }
1459         fd_list[list_idx].fds[seg_idx] = fd;
1460
1461         return 0;
1462 }
1463
1464 int
1465 eal_memalloc_set_seg_list_fd(int list_idx, int fd)
1466 {
1467         /* non-single file segment mode doesn't support segment list fd's */
1468         if (!internal_config.single_file_segments)
1469                 return -ENOTSUP;
1470
1471         fd_list[list_idx].memseg_list_fd = fd;
1472
1473         return 0;
1474 }
1475
1476 int
1477 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1478 {
1479         int fd;
1480
1481         if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1482 #ifndef MEMFD_SUPPORTED
1483                 /* in in-memory or no-huge mode, we rely on memfd support */
1484                 return -ENOTSUP;
1485 #endif
1486                 /* memfd supported, but hugetlbfs memfd may not be */
1487                 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1488                         return -ENOTSUP;
1489         }
1490
1491         if (internal_config.single_file_segments) {
1492                 fd = fd_list[list_idx].memseg_list_fd;
1493         } else if (fd_list[list_idx].len == 0) {
1494                 /* list not initialized */
1495                 fd = -1;
1496         } else {
1497                 fd = fd_list[list_idx].fds[seg_idx];
1498         }
1499         if (fd < 0)
1500                 return -ENODEV;
1501         return fd;
1502 }
1503
1504 static int
1505 test_memfd_create(void)
1506 {
1507 #ifdef MEMFD_SUPPORTED
1508         unsigned int i;
1509         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1510                 uint64_t pagesz = internal_config.hugepage_info[i].hugepage_sz;
1511                 int pagesz_flag = pagesz_flags(pagesz);
1512                 int flags;
1513
1514                 flags = pagesz_flag | RTE_MFD_HUGETLB;
1515                 int fd = memfd_create("test", flags);
1516                 if (fd < 0) {
1517                         /* we failed - let memalloc know this isn't working */
1518                         if (errno == EINVAL) {
1519                                 memfd_create_supported = 0;
1520                                 return 0; /* not supported */
1521                         }
1522
1523                         /* we got other error - something's wrong */
1524                         return -1; /* error */
1525                 }
1526                 close(fd);
1527                 return 1; /* supported */
1528         }
1529 #endif
1530         return 0; /* not supported */
1531 }
1532
1533 int
1534 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1535 {
1536         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1537
1538         if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1539 #ifndef MEMFD_SUPPORTED
1540                 /* in in-memory or no-huge mode, we rely on memfd support */
1541                 return -ENOTSUP;
1542 #endif
1543                 /* memfd supported, but hugetlbfs memfd may not be */
1544                 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1545                         return -ENOTSUP;
1546         }
1547
1548         if (internal_config.single_file_segments) {
1549                 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1550
1551                 /* segment not active? */
1552                 if (fd_list[list_idx].memseg_list_fd < 0)
1553                         return -ENOENT;
1554                 *offset = pgsz * seg_idx;
1555         } else {
1556                 /* fd_list not initialized? */
1557                 if (fd_list[list_idx].len == 0)
1558                         return -ENODEV;
1559
1560                 /* segment not active? */
1561                 if (fd_list[list_idx].fds[seg_idx] < 0)
1562                         return -ENOENT;
1563                 *offset = 0;
1564         }
1565         return 0;
1566 }
1567
1568 int
1569 eal_memalloc_init(void)
1570 {
1571         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1572                 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1573                         return -1;
1574         if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1575                         internal_config.in_memory) {
1576                 int mfd_res = test_memfd_create();
1577
1578                 if (mfd_res < 0) {
1579                         RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1580                         return -1;
1581                 }
1582                 if (mfd_res == 1)
1583                         RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1584                 else
1585                         RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1586
1587                 /* we only support single-file segments mode with in-memory mode
1588                  * if we support hugetlbfs with memfd_create. this code will
1589                  * test if we do.
1590                  */
1591                 if (internal_config.single_file_segments &&
1592                                 mfd_res != 1) {
1593                         RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1594                         return -1;
1595                 }
1596                 /* this cannot ever happen but better safe than sorry */
1597                 if (!anonymous_hugepages_supported) {
1598                         RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1599                         return -1;
1600                 }
1601         }
1602
1603         /* initialize all of the fd lists */
1604         if (rte_memseg_list_walk(fd_list_create_walk, NULL))
1605                 return -1;
1606         return 0;
1607 }