New upstream version 18.11-rc4
[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         new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
757         if (new_addr != addr) {
758                 if (new_addr != NULL)
759                         munmap(new_addr, alloc_sz);
760                 /* we're leaving a hole in our virtual address space. if
761                  * somebody else maps this hole now, we could accidentally
762                  * override it in the future.
763                  */
764                 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
765         }
766 resized:
767         /* some codepaths will return negative fd, so exit early */
768         if (fd < 0)
769                 return -1;
770
771         if (internal_config.single_file_segments) {
772                 resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
773                                 alloc_sz, false);
774                 /* ignore failure, can't make it any worse */
775         } else {
776                 /* only remove file if we can take out a write lock */
777                 if (internal_config.hugepage_unlink == 0 &&
778                                 internal_config.in_memory == 0 &&
779                                 lock(fd, LOCK_EX) == 1)
780                         unlink(path);
781                 close(fd);
782                 fd_list[list_idx].fds[seg_idx] = -1;
783         }
784         return -1;
785 }
786
787 static int
788 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
789                 unsigned int list_idx, unsigned int seg_idx)
790 {
791         uint64_t map_offset;
792         char path[PATH_MAX];
793         int fd, ret = 0;
794         bool exit_early;
795
796         /* erase page data */
797         memset(ms->addr, 0, ms->len);
798
799         if (mmap(ms->addr, ms->len, PROT_READ,
800                         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
801                                 MAP_FAILED) {
802                 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
803                 return -1;
804         }
805
806         exit_early = false;
807
808         /* if we're using anonymous hugepages, nothing to be done */
809         if (internal_config.in_memory && !memfd_create_supported)
810                 exit_early = true;
811
812         /* if we've already unlinked the page, nothing needs to be done */
813         if (!internal_config.in_memory && internal_config.hugepage_unlink)
814                 exit_early = true;
815
816         if (exit_early) {
817                 memset(ms, 0, sizeof(*ms));
818                 return 0;
819         }
820
821         /* if we are not in single file segments mode, we're going to unmap the
822          * segment and thus drop the lock on original fd, but hugepage dir is
823          * now locked so we can take out another one without races.
824          */
825         fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
826         if (fd < 0)
827                 return -1;
828
829         if (internal_config.single_file_segments) {
830                 map_offset = seg_idx * ms->len;
831                 if (resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
832                                 ms->len, false))
833                         return -1;
834                 ret = 0;
835         } else {
836                 /* if we're able to take out a write lock, we're the last one
837                  * holding onto this page.
838                  */
839                 if (!internal_config.in_memory) {
840                         ret = lock(fd, LOCK_EX);
841                         if (ret >= 0) {
842                                 /* no one else is using this page */
843                                 if (ret == 1)
844                                         unlink(path);
845                         }
846                 }
847                 /* closing fd will drop the lock */
848                 close(fd);
849                 fd_list[list_idx].fds[seg_idx] = -1;
850         }
851
852         memset(ms, 0, sizeof(*ms));
853
854         return ret < 0 ? -1 : 0;
855 }
856
857 struct alloc_walk_param {
858         struct hugepage_info *hi;
859         struct rte_memseg **ms;
860         size_t page_sz;
861         unsigned int segs_allocated;
862         unsigned int n_segs;
863         int socket;
864         bool exact;
865 };
866 static int
867 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
868 {
869         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
870         struct alloc_walk_param *wa = arg;
871         struct rte_memseg_list *cur_msl;
872         size_t page_sz;
873         int cur_idx, start_idx, j, dir_fd = -1;
874         unsigned int msl_idx, need, i;
875
876         if (msl->page_sz != wa->page_sz)
877                 return 0;
878         if (msl->socket_id != wa->socket)
879                 return 0;
880
881         page_sz = (size_t)msl->page_sz;
882
883         msl_idx = msl - mcfg->memsegs;
884         cur_msl = &mcfg->memsegs[msl_idx];
885
886         need = wa->n_segs;
887
888         /* try finding space in memseg list */
889         cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0, need);
890         if (cur_idx < 0)
891                 return 0;
892         start_idx = cur_idx;
893
894         /* do not allow any page allocations during the time we're allocating,
895          * because file creation and locking operations are not atomic,
896          * and we might be the first or the last ones to use a particular page,
897          * so we need to ensure atomicity of every operation.
898          *
899          * during init, we already hold a write lock, so don't try to take out
900          * another one.
901          */
902         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
903                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
904                 if (dir_fd < 0) {
905                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
906                                 __func__, wa->hi->hugedir, strerror(errno));
907                         return -1;
908                 }
909                 /* blocking writelock */
910                 if (flock(dir_fd, LOCK_EX)) {
911                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
912                                 __func__, wa->hi->hugedir, strerror(errno));
913                         close(dir_fd);
914                         return -1;
915                 }
916         }
917
918         for (i = 0; i < need; i++, cur_idx++) {
919                 struct rte_memseg *cur;
920                 void *map_addr;
921
922                 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
923                 map_addr = RTE_PTR_ADD(cur_msl->base_va,
924                                 cur_idx * page_sz);
925
926                 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
927                                 msl_idx, cur_idx)) {
928                         RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
929                                 need, i);
930
931                         /* if exact number wasn't requested, stop */
932                         if (!wa->exact)
933                                 goto out;
934
935                         /* clean up */
936                         for (j = start_idx; j < cur_idx; j++) {
937                                 struct rte_memseg *tmp;
938                                 struct rte_fbarray *arr =
939                                                 &cur_msl->memseg_arr;
940
941                                 tmp = rte_fbarray_get(arr, j);
942                                 rte_fbarray_set_free(arr, j);
943
944                                 /* free_seg may attempt to create a file, which
945                                  * may fail.
946                                  */
947                                 if (free_seg(tmp, wa->hi, msl_idx, j))
948                                         RTE_LOG(DEBUG, EAL, "Cannot free page\n");
949                         }
950                         /* clear the list */
951                         if (wa->ms)
952                                 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
953
954                         if (dir_fd >= 0)
955                                 close(dir_fd);
956                         return -1;
957                 }
958                 if (wa->ms)
959                         wa->ms[i] = cur;
960
961                 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
962         }
963 out:
964         wa->segs_allocated = i;
965         if (i > 0)
966                 cur_msl->version++;
967         if (dir_fd >= 0)
968                 close(dir_fd);
969         return 1;
970 }
971
972 struct free_walk_param {
973         struct hugepage_info *hi;
974         struct rte_memseg *ms;
975 };
976 static int
977 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
978 {
979         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
980         struct rte_memseg_list *found_msl;
981         struct free_walk_param *wa = arg;
982         uintptr_t start_addr, end_addr;
983         int msl_idx, seg_idx, ret, dir_fd = -1;
984
985         start_addr = (uintptr_t) msl->base_va;
986         end_addr = start_addr + msl->len;
987
988         if ((uintptr_t)wa->ms->addr < start_addr ||
989                         (uintptr_t)wa->ms->addr >= end_addr)
990                 return 0;
991
992         msl_idx = msl - mcfg->memsegs;
993         seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
994
995         /* msl is const */
996         found_msl = &mcfg->memsegs[msl_idx];
997
998         /* do not allow any page allocations during the time we're freeing,
999          * because file creation and locking operations are not atomic,
1000          * and we might be the first or the last ones to use a particular page,
1001          * so we need to ensure atomicity of every operation.
1002          *
1003          * during init, we already hold a write lock, so don't try to take out
1004          * another one.
1005          */
1006         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
1007                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
1008                 if (dir_fd < 0) {
1009                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
1010                                 __func__, wa->hi->hugedir, strerror(errno));
1011                         return -1;
1012                 }
1013                 /* blocking writelock */
1014                 if (flock(dir_fd, LOCK_EX)) {
1015                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
1016                                 __func__, wa->hi->hugedir, strerror(errno));
1017                         close(dir_fd);
1018                         return -1;
1019                 }
1020         }
1021
1022         found_msl->version++;
1023
1024         rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
1025
1026         ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
1027
1028         if (dir_fd >= 0)
1029                 close(dir_fd);
1030
1031         if (ret < 0)
1032                 return -1;
1033
1034         return 1;
1035 }
1036
1037 int
1038 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
1039                 int socket, bool exact)
1040 {
1041         int i, ret = -1;
1042 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1043         bool have_numa = false;
1044         int oldpolicy;
1045         struct bitmask *oldmask;
1046 #endif
1047         struct alloc_walk_param wa;
1048         struct hugepage_info *hi = NULL;
1049
1050         memset(&wa, 0, sizeof(wa));
1051
1052         /* dynamic allocation not supported in legacy mode */
1053         if (internal_config.legacy_mem)
1054                 return -1;
1055
1056         for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
1057                 if (page_sz ==
1058                                 internal_config.hugepage_info[i].hugepage_sz) {
1059                         hi = &internal_config.hugepage_info[i];
1060                         break;
1061                 }
1062         }
1063         if (!hi) {
1064                 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
1065                         __func__);
1066                 return -1;
1067         }
1068
1069 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1070         if (check_numa()) {
1071                 oldmask = numa_allocate_nodemask();
1072                 prepare_numa(&oldpolicy, oldmask, socket);
1073                 have_numa = true;
1074         }
1075 #endif
1076
1077         wa.exact = exact;
1078         wa.hi = hi;
1079         wa.ms = ms;
1080         wa.n_segs = n_segs;
1081         wa.page_sz = page_sz;
1082         wa.socket = socket;
1083         wa.segs_allocated = 0;
1084
1085         /* memalloc is locked, so it's safe to use thread-unsafe version */
1086         ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1087         if (ret == 0) {
1088                 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1089                         __func__);
1090                 ret = -1;
1091         } else if (ret > 0) {
1092                 ret = (int)wa.segs_allocated;
1093         }
1094
1095 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1096         if (have_numa)
1097                 restore_numa(&oldpolicy, oldmask);
1098 #endif
1099         return ret;
1100 }
1101
1102 struct rte_memseg *
1103 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1104 {
1105         struct rte_memseg *ms;
1106         if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1107                 return NULL;
1108         /* return pointer to newly allocated memseg */
1109         return ms;
1110 }
1111
1112 int
1113 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1114 {
1115         int seg, ret = 0;
1116
1117         /* dynamic free not supported in legacy mode */
1118         if (internal_config.legacy_mem)
1119                 return -1;
1120
1121         for (seg = 0; seg < n_segs; seg++) {
1122                 struct rte_memseg *cur = ms[seg];
1123                 struct hugepage_info *hi = NULL;
1124                 struct free_walk_param wa;
1125                 int i, walk_res;
1126
1127                 /* if this page is marked as unfreeable, fail */
1128                 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1129                         RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1130                         ret = -1;
1131                         continue;
1132                 }
1133
1134                 memset(&wa, 0, sizeof(wa));
1135
1136                 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
1137                                 i++) {
1138                         hi = &internal_config.hugepage_info[i];
1139                         if (cur->hugepage_sz == hi->hugepage_sz)
1140                                 break;
1141                 }
1142                 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1143                         RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1144                         ret = -1;
1145                         continue;
1146                 }
1147
1148                 wa.ms = cur;
1149                 wa.hi = hi;
1150
1151                 /* memalloc is locked, so it's safe to use thread-unsafe version
1152                  */
1153                 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1154                                 &wa);
1155                 if (walk_res == 1)
1156                         continue;
1157                 if (walk_res == 0)
1158                         RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1159                 ret = -1;
1160         }
1161         return ret;
1162 }
1163
1164 int
1165 eal_memalloc_free_seg(struct rte_memseg *ms)
1166 {
1167         /* dynamic free not supported in legacy mode */
1168         if (internal_config.legacy_mem)
1169                 return -1;
1170
1171         return eal_memalloc_free_seg_bulk(&ms, 1);
1172 }
1173
1174 static int
1175 sync_chunk(struct rte_memseg_list *primary_msl,
1176                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1177                 unsigned int msl_idx, bool used, int start, int end)
1178 {
1179         struct rte_fbarray *l_arr, *p_arr;
1180         int i, ret, chunk_len, diff_len;
1181
1182         l_arr = &local_msl->memseg_arr;
1183         p_arr = &primary_msl->memseg_arr;
1184
1185         /* we need to aggregate allocations/deallocations into bigger chunks,
1186          * as we don't want to spam the user with per-page callbacks.
1187          *
1188          * to avoid any potential issues, we also want to trigger
1189          * deallocation callbacks *before* we actually deallocate
1190          * memory, so that the user application could wrap up its use
1191          * before it goes away.
1192          */
1193
1194         chunk_len = end - start;
1195
1196         /* find how many contiguous pages we can map/unmap for this chunk */
1197         diff_len = used ?
1198                         rte_fbarray_find_contig_free(l_arr, start) :
1199                         rte_fbarray_find_contig_used(l_arr, start);
1200
1201         /* has to be at least one page */
1202         if (diff_len < 1)
1203                 return -1;
1204
1205         diff_len = RTE_MIN(chunk_len, diff_len);
1206
1207         /* if we are freeing memory, notify the application */
1208         if (!used) {
1209                 struct rte_memseg *ms;
1210                 void *start_va;
1211                 size_t len, page_sz;
1212
1213                 ms = rte_fbarray_get(l_arr, start);
1214                 start_va = ms->addr;
1215                 page_sz = (size_t)primary_msl->page_sz;
1216                 len = page_sz * diff_len;
1217
1218                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1219                                 start_va, len);
1220         }
1221
1222         for (i = 0; i < diff_len; i++) {
1223                 struct rte_memseg *p_ms, *l_ms;
1224                 int seg_idx = start + i;
1225
1226                 l_ms = rte_fbarray_get(l_arr, seg_idx);
1227                 p_ms = rte_fbarray_get(p_arr, seg_idx);
1228
1229                 if (l_ms == NULL || p_ms == NULL)
1230                         return -1;
1231
1232                 if (used) {
1233                         ret = alloc_seg(l_ms, p_ms->addr,
1234                                         p_ms->socket_id, hi,
1235                                         msl_idx, seg_idx);
1236                         if (ret < 0)
1237                                 return -1;
1238                         rte_fbarray_set_used(l_arr, seg_idx);
1239                 } else {
1240                         ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1241                         rte_fbarray_set_free(l_arr, seg_idx);
1242                         if (ret < 0)
1243                                 return -1;
1244                 }
1245         }
1246
1247         /* if we just allocated memory, notify the application */
1248         if (used) {
1249                 struct rte_memseg *ms;
1250                 void *start_va;
1251                 size_t len, page_sz;
1252
1253                 ms = rte_fbarray_get(l_arr, start);
1254                 start_va = ms->addr;
1255                 page_sz = (size_t)primary_msl->page_sz;
1256                 len = page_sz * diff_len;
1257
1258                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1259                                 start_va, len);
1260         }
1261
1262         /* calculate how much we can advance until next chunk */
1263         diff_len = used ?
1264                         rte_fbarray_find_contig_used(l_arr, start) :
1265                         rte_fbarray_find_contig_free(l_arr, start);
1266         ret = RTE_MIN(chunk_len, diff_len);
1267
1268         return ret;
1269 }
1270
1271 static int
1272 sync_status(struct rte_memseg_list *primary_msl,
1273                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1274                 unsigned int msl_idx, bool used)
1275 {
1276         struct rte_fbarray *l_arr, *p_arr;
1277         int p_idx, l_chunk_len, p_chunk_len, ret;
1278         int start, end;
1279
1280         /* this is a little bit tricky, but the basic idea is - walk both lists
1281          * and spot any places where there are discrepancies. walking both lists
1282          * and noting discrepancies in a single go is a hard problem, so we do
1283          * it in two passes - first we spot any places where allocated segments
1284          * mismatch (i.e. ensure that everything that's allocated in the primary
1285          * is also allocated in the secondary), and then we do it by looking at
1286          * free segments instead.
1287          *
1288          * we also need to aggregate changes into chunks, as we have to call
1289          * callbacks per allocation, not per page.
1290          */
1291         l_arr = &local_msl->memseg_arr;
1292         p_arr = &primary_msl->memseg_arr;
1293
1294         if (used)
1295                 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1296         else
1297                 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1298
1299         while (p_idx >= 0) {
1300                 int next_chunk_search_idx;
1301
1302                 if (used) {
1303                         p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1304                                         p_idx);
1305                         l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1306                                         p_idx);
1307                 } else {
1308                         p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1309                                         p_idx);
1310                         l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1311                                         p_idx);
1312                 }
1313                 /* best case scenario - no differences (or bigger, which will be
1314                  * fixed during next iteration), look for next chunk
1315                  */
1316                 if (l_chunk_len >= p_chunk_len) {
1317                         next_chunk_search_idx = p_idx + p_chunk_len;
1318                         goto next_chunk;
1319                 }
1320
1321                 /* if both chunks start at the same point, skip parts we know
1322                  * are identical, and sync the rest. each call to sync_chunk
1323                  * will only sync contiguous segments, so we need to call this
1324                  * until we are sure there are no more differences in this
1325                  * chunk.
1326                  */
1327                 start = p_idx + l_chunk_len;
1328                 end = p_idx + p_chunk_len;
1329                 do {
1330                         ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1331                                         used, start, end);
1332                         start += ret;
1333                 } while (start < end && ret >= 0);
1334                 /* if ret is negative, something went wrong */
1335                 if (ret < 0)
1336                         return -1;
1337
1338                 next_chunk_search_idx = p_idx + p_chunk_len;
1339 next_chunk:
1340                 /* skip to end of this chunk */
1341                 if (used) {
1342                         p_idx = rte_fbarray_find_next_used(p_arr,
1343                                         next_chunk_search_idx);
1344                 } else {
1345                         p_idx = rte_fbarray_find_next_free(p_arr,
1346                                         next_chunk_search_idx);
1347                 }
1348         }
1349         return 0;
1350 }
1351
1352 static int
1353 sync_existing(struct rte_memseg_list *primary_msl,
1354                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1355                 unsigned int msl_idx)
1356 {
1357         int ret, dir_fd;
1358
1359         /* do not allow any page allocations during the time we're allocating,
1360          * because file creation and locking operations are not atomic,
1361          * and we might be the first or the last ones to use a particular page,
1362          * so we need to ensure atomicity of every operation.
1363          */
1364         dir_fd = open(hi->hugedir, O_RDONLY);
1365         if (dir_fd < 0) {
1366                 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1367                         hi->hugedir, strerror(errno));
1368                 return -1;
1369         }
1370         /* blocking writelock */
1371         if (flock(dir_fd, LOCK_EX)) {
1372                 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1373                         hi->hugedir, strerror(errno));
1374                 close(dir_fd);
1375                 return -1;
1376         }
1377
1378         /* ensure all allocated space is the same in both lists */
1379         ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1380         if (ret < 0)
1381                 goto fail;
1382
1383         /* ensure all unallocated space is the same in both lists */
1384         ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1385         if (ret < 0)
1386                 goto fail;
1387
1388         /* update version number */
1389         local_msl->version = primary_msl->version;
1390
1391         close(dir_fd);
1392
1393         return 0;
1394 fail:
1395         close(dir_fd);
1396         return -1;
1397 }
1398
1399 static int
1400 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1401 {
1402         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1403         struct rte_memseg_list *primary_msl, *local_msl;
1404         struct hugepage_info *hi = NULL;
1405         unsigned int i;
1406         int msl_idx;
1407
1408         if (msl->external)
1409                 return 0;
1410
1411         msl_idx = msl - mcfg->memsegs;
1412         primary_msl = &mcfg->memsegs[msl_idx];
1413         local_msl = &local_memsegs[msl_idx];
1414
1415         for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1416                 uint64_t cur_sz =
1417                         internal_config.hugepage_info[i].hugepage_sz;
1418                 uint64_t msl_sz = primary_msl->page_sz;
1419                 if (msl_sz == cur_sz) {
1420                         hi = &internal_config.hugepage_info[i];
1421                         break;
1422                 }
1423         }
1424         if (!hi) {
1425                 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1426                 return -1;
1427         }
1428
1429         /* if versions don't match, synchronize everything */
1430         if (local_msl->version != primary_msl->version &&
1431                         sync_existing(primary_msl, local_msl, hi, msl_idx))
1432                 return -1;
1433         return 0;
1434 }
1435
1436
1437 int
1438 eal_memalloc_sync_with_primary(void)
1439 {
1440         /* nothing to be done in primary */
1441         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1442                 return 0;
1443
1444         /* memalloc is locked, so it's safe to call thread-unsafe version */
1445         if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1446                 return -1;
1447         return 0;
1448 }
1449
1450 static int
1451 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1452                 void *arg __rte_unused)
1453 {
1454         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1455         struct rte_memseg_list *primary_msl, *local_msl;
1456         char name[PATH_MAX];
1457         int msl_idx, ret;
1458
1459         if (msl->external)
1460                 return 0;
1461
1462         msl_idx = msl - mcfg->memsegs;
1463         primary_msl = &mcfg->memsegs[msl_idx];
1464         local_msl = &local_memsegs[msl_idx];
1465
1466         /* create distinct fbarrays for each secondary */
1467         snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1468                 primary_msl->memseg_arr.name, getpid());
1469
1470         ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1471                 primary_msl->memseg_arr.len,
1472                 primary_msl->memseg_arr.elt_sz);
1473         if (ret < 0) {
1474                 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1475                 return -1;
1476         }
1477         local_msl->base_va = primary_msl->base_va;
1478         local_msl->len = primary_msl->len;
1479
1480         return 0;
1481 }
1482
1483 static int
1484 alloc_list(int list_idx, int len)
1485 {
1486         int *data;
1487         int i;
1488
1489         /* ensure we have space to store fd per each possible segment */
1490         data = malloc(sizeof(int) * len);
1491         if (data == NULL) {
1492                 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1493                 return -1;
1494         }
1495         /* set all fd's as invalid */
1496         for (i = 0; i < len; i++)
1497                 data[i] = -1;
1498
1499         fd_list[list_idx].fds = data;
1500         fd_list[list_idx].len = len;
1501         fd_list[list_idx].count = 0;
1502         fd_list[list_idx].memseg_list_fd = -1;
1503
1504         return 0;
1505 }
1506
1507 static int
1508 fd_list_create_walk(const struct rte_memseg_list *msl,
1509                 void *arg __rte_unused)
1510 {
1511         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1512         unsigned int len;
1513         int msl_idx;
1514
1515         if (msl->external)
1516                 return 0;
1517
1518         msl_idx = msl - mcfg->memsegs;
1519         len = msl->memseg_arr.len;
1520
1521         return alloc_list(msl_idx, len);
1522 }
1523
1524 int
1525 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1526 {
1527         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1528
1529         /* if list is not allocated, allocate it */
1530         if (fd_list[list_idx].len == 0) {
1531                 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1532
1533                 if (alloc_list(list_idx, len) < 0)
1534                         return -ENOMEM;
1535         }
1536         fd_list[list_idx].fds[seg_idx] = fd;
1537
1538         return 0;
1539 }
1540
1541 int
1542 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1543 {
1544         int fd;
1545         if (internal_config.single_file_segments) {
1546                 fd = fd_list[list_idx].memseg_list_fd;
1547         } else if (fd_list[list_idx].len == 0) {
1548                 /* list not initialized */
1549                 fd = -1;
1550         } else {
1551                 fd = fd_list[list_idx].fds[seg_idx];
1552         }
1553         if (fd < 0)
1554                 return -ENODEV;
1555         return fd;
1556 }
1557
1558 static int
1559 test_memfd_create(void)
1560 {
1561 #ifdef MEMFD_SUPPORTED
1562         unsigned int i;
1563         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1564                 uint64_t pagesz = internal_config.hugepage_info[i].hugepage_sz;
1565                 int pagesz_flag = pagesz_flags(pagesz);
1566                 int flags;
1567
1568                 flags = pagesz_flag | MFD_HUGETLB;
1569                 int fd = memfd_create("test", flags);
1570                 if (fd < 0) {
1571                         /* we failed - let memalloc know this isn't working */
1572                         if (errno == EINVAL) {
1573                                 memfd_create_supported = 0;
1574                                 return 0; /* not supported */
1575                         }
1576
1577                         /* we got other error - something's wrong */
1578                         return -1; /* error */
1579                 }
1580                 close(fd);
1581                 return 1; /* supported */
1582         }
1583 #endif
1584         return 0; /* not supported */
1585 }
1586
1587 int
1588 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1589 {
1590         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1591
1592         /* fd_list not initialized? */
1593         if (fd_list[list_idx].len == 0)
1594                 return -ENODEV;
1595         if (internal_config.single_file_segments) {
1596                 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1597
1598                 /* segment not active? */
1599                 if (fd_list[list_idx].memseg_list_fd < 0)
1600                         return -ENOENT;
1601                 *offset = pgsz * seg_idx;
1602         } else {
1603                 /* segment not active? */
1604                 if (fd_list[list_idx].fds[seg_idx] < 0)
1605                         return -ENOENT;
1606                 *offset = 0;
1607         }
1608         return 0;
1609 }
1610
1611 int
1612 eal_memalloc_init(void)
1613 {
1614         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1615                 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1616                         return -1;
1617         if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1618                         internal_config.in_memory) {
1619                 int mfd_res = test_memfd_create();
1620
1621                 if (mfd_res < 0) {
1622                         RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1623                         return -1;
1624                 }
1625                 if (mfd_res == 1)
1626                         RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1627                 else
1628                         RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1629
1630                 /* we only support single-file segments mode with in-memory mode
1631                  * if we support hugetlbfs with memfd_create. this code will
1632                  * test if we do.
1633                  */
1634                 if (internal_config.single_file_segments &&
1635                                 mfd_res != 1) {
1636                         RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1637                         return -1;
1638                 }
1639                 /* this cannot ever happen but better safe than sorry */
1640                 if (!anonymous_hugepages_supported) {
1641                         RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1642                         return -1;
1643                 }
1644         }
1645
1646         /* initialize all of the fd lists */
1647         if (rte_memseg_list_walk(fd_list_create_walk, NULL))
1648                 return -1;
1649         return 0;
1650 }