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