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