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