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