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