1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2017-2018 Intel Corporation
14 #include <sys/types.h>
16 #include <sys/queue.h>
21 #include <sys/ioctl.h>
25 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
26 #include <linux/memfd.h>
27 #define MEMFD_SUPPORTED
29 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
33 #include <linux/falloc.h>
34 #include <linux/mman.h> /* for hugetlb-related mmap flags */
36 #include <rte_common.h>
38 #include <rte_eal_memconfig.h>
40 #include <rte_errno.h>
41 #include <rte_memory.h>
42 #include <rte_spinlock.h>
44 #include "eal_filesystem.h"
45 #include "eal_internal_cfg.h"
46 #include "eal_memalloc.h"
47 #include "eal_private.h"
49 const int anonymous_hugepages_supported =
52 #define RTE_MAP_HUGE_SHIFT MAP_HUGE_SHIFT
55 #define RTE_MAP_HUGE_SHIFT 26
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.
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.
67 static int memfd_create_supported =
70 #define RTE_MFD_HUGETLB MFD_HUGETLB
73 #define RTE_MFD_HUGETLB 4U
77 * not all kernel version support fallocate on hugetlbfs, so fall back to
78 * ftruncate and disallow deallocation if fallocate is not supported.
80 static int fallocate_supported = -1; /* unknown */
83 * we have two modes - single file segments, and file-per-page mode.
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.
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.
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.
95 * they will be initialized at startup, and filled as we allocate/deallocate
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];
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];
108 static sigjmp_buf huge_jmpenv;
110 static void __rte_unused huge_sigbus_handler(int signo __rte_unused)
112 siglongjmp(huge_jmpenv, 1);
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.
119 static int __rte_unused huge_wrap_sigsetjmp(void)
121 return sigsetjmp(huge_jmpenv, 1);
124 static struct sigaction huge_action_old;
125 static int huge_need_recover;
127 static void __rte_unused
128 huge_register_sigbus(void)
131 struct sigaction action;
134 sigaddset(&mask, SIGBUS);
136 action.sa_mask = mask;
137 action.sa_handler = huge_sigbus_handler;
139 huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
142 static void __rte_unused
143 huge_recover_sigbus(void)
145 if (huge_need_recover) {
146 sigaction(SIGBUS, &huge_action_old, NULL);
147 huge_need_recover = 0;
151 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
156 /* Check if kernel supports NUMA. */
157 if (numa_available() != 0) {
158 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
165 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
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) {
171 "Failed to get current mempolicy: %s. "
172 "Assuming MPOL_DEFAULT.\n", strerror(errno));
173 *oldpolicy = MPOL_DEFAULT;
176 "Setting policy MPOL_PREFERRED for socket %d\n",
178 numa_set_preferred(socket_id);
182 restore_numa(int *oldpolicy, struct bitmask *oldmask)
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",
192 numa_set_localalloc();
194 numa_free_cpumask(oldmask);
199 * uses fstat to report the size of a file on disk
202 get_file_size(int fd)
205 if (fstat(fd, &st) < 0)
211 pagesz_flags(uint64_t page_sz)
213 /* as per mmap() manpage, all page sizes are log2 of page size
214 * shifted by MAP_HUGE_SHIFT
216 int log2 = rte_log2_u64(page_sz);
217 return log2 << RTE_MAP_HUGE_SHIFT;
220 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
221 static int lock(int fd, int type)
225 /* flock may be interrupted */
227 ret = flock(fd, type | LOCK_NB);
228 } while (ret && errno == EINTR);
230 if (ret && errno == EWOULDBLOCK) {
234 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
235 __func__, strerror(errno));
238 /* lock was successful */
243 get_seg_memfd(struct hugepage_info *hi __rte_unused,
244 unsigned int list_idx __rte_unused,
245 unsigned int seg_idx __rte_unused)
247 #ifdef MEMFD_SUPPORTED
249 char segname[250]; /* as per manpage, limit is 249 bytes plus null */
251 int flags = RTE_MFD_HUGETLB | pagesz_flags(hi->hugepage_sz);
253 if (internal_config.single_file_segments) {
254 fd = fd_list[list_idx].memseg_list_fd;
257 snprintf(segname, sizeof(segname), "seg_%i", list_idx);
258 fd = memfd_create(segname, flags);
260 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
261 __func__, strerror(errno));
264 fd_list[list_idx].memseg_list_fd = fd;
267 fd = fd_list[list_idx].fds[seg_idx];
270 snprintf(segname, sizeof(segname), "seg_%i-%i",
272 fd = memfd_create(segname, flags);
274 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
275 __func__, strerror(errno));
278 fd_list[list_idx].fds[seg_idx] = fd;
287 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
288 unsigned int list_idx, unsigned int seg_idx)
292 /* for in-memory mode, we only make it here when we're sure we support
293 * memfd, and this is a special case.
295 if (internal_config.in_memory)
296 return get_seg_memfd(hi, list_idx, seg_idx);
298 if (internal_config.single_file_segments) {
299 /* create a hugepage file path */
300 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
302 fd = fd_list[list_idx].memseg_list_fd;
305 fd = open(path, O_CREAT | O_RDWR, 0600);
307 RTE_LOG(ERR, EAL, "%s(): open failed: %s\n",
308 __func__, strerror(errno));
311 /* take out a read lock and keep it indefinitely */
312 if (lock(fd, LOCK_SH) < 0) {
313 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
314 __func__, strerror(errno));
318 fd_list[list_idx].memseg_list_fd = fd;
321 /* create a hugepage file path */
322 eal_get_hugefile_path(path, buflen, hi->hugedir,
323 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
325 fd = fd_list[list_idx].fds[seg_idx];
328 fd = open(path, O_CREAT | O_RDWR, 0600);
330 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
331 __func__, strerror(errno));
334 /* take out a read lock */
335 if (lock(fd, LOCK_SH) < 0) {
336 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
337 __func__, strerror(errno));
341 fd_list[list_idx].fds[seg_idx] = fd;
348 resize_hugefile_in_memory(int fd, uint64_t fa_offset,
349 uint64_t page_sz, bool grow)
351 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
355 /* grow or shrink the file */
356 ret = fallocate(fd, flags, fa_offset, page_sz);
359 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
368 resize_hugefile_in_filesystem(int fd, uint64_t fa_offset, uint64_t page_sz,
374 if (fallocate_supported == 0) {
375 /* we cannot deallocate memory if fallocate() is not
376 * supported, and hugepage file is already locked at
377 * creation, so no further synchronization needed.
381 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
385 uint64_t new_size = fa_offset + page_sz;
386 uint64_t cur_size = get_file_size(fd);
388 /* fallocate isn't supported, fall back to ftruncate */
389 if (new_size > cur_size &&
390 ftruncate(fd, new_size) < 0) {
391 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
392 __func__, strerror(errno));
396 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
401 * technically, it is perfectly safe for both primary
402 * and secondary to grow and shrink the page files:
403 * growing the file repeatedly has no effect because
404 * a page can only be allocated once, while mmap ensures
405 * that secondaries hold on to the page even after the
406 * page itself is removed from the filesystem.
408 * however, leaving growing/shrinking to the primary
409 * tends to expose bugs in fdlist page count handling,
410 * so leave this here just in case.
412 if (rte_eal_process_type() != RTE_PROC_PRIMARY)
415 /* grow or shrink the file */
416 ret = fallocate(fd, flags, fa_offset, page_sz);
419 if (fallocate_supported == -1 &&
421 RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
424 fallocate_supported = 0;
426 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
432 fallocate_supported = 1;
440 close_hugefile(int fd, char *path, int list_idx)
443 * primary process must unlink the file, but only when not in in-memory
444 * mode (as in that case there is no file to unlink).
446 if (!internal_config.in_memory &&
447 rte_eal_process_type() == RTE_PROC_PRIMARY &&
449 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
450 __func__, path, strerror(errno));
453 fd_list[list_idx].memseg_list_fd = -1;
457 resize_hugefile(int fd, uint64_t fa_offset, uint64_t page_sz, bool grow)
459 /* in-memory mode is a special case, because we can be sure that
460 * fallocate() is supported.
462 if (internal_config.in_memory)
463 return resize_hugefile_in_memory(fd, fa_offset,
466 return resize_hugefile_in_filesystem(fd, fa_offset, page_sz,
471 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
472 struct hugepage_info *hi, unsigned int list_idx,
473 unsigned int seg_idx)
475 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
476 int cur_socket_id = 0;
488 alloc_sz = hi->hugepage_sz;
490 /* these are checked at init, but code analyzers don't know that */
491 if (internal_config.in_memory && !anonymous_hugepages_supported) {
492 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
495 if (internal_config.in_memory && !memfd_create_supported &&
496 internal_config.single_file_segments) {
497 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
501 /* in-memory without memfd is a special case */
504 if (internal_config.in_memory && !memfd_create_supported) {
505 const int in_memory_flags = MAP_HUGETLB | MAP_FIXED |
506 MAP_PRIVATE | MAP_ANONYMOUS;
509 pagesz_flag = pagesz_flags(alloc_sz);
511 mmap_flags = in_memory_flags | pagesz_flag;
513 /* single-file segments codepath will never be active
514 * here because in-memory mode is incompatible with the
515 * fallback path, and it's stopped at EAL initialization
520 /* takes out a read lock on segment or segment list */
521 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
523 RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
527 if (internal_config.single_file_segments) {
528 map_offset = seg_idx * alloc_sz;
529 ret = resize_hugefile(fd, map_offset, alloc_sz, true);
533 fd_list[list_idx].count++;
536 if (ftruncate(fd, alloc_sz) < 0) {
537 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
538 __func__, strerror(errno));
541 if (internal_config.hugepage_unlink &&
542 !internal_config.in_memory) {
544 RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
545 __func__, strerror(errno));
550 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
554 * map the segment, and populate page tables, the kernel fills
555 * this segment with zeros if it's a new page.
557 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
560 if (va == MAP_FAILED) {
561 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
563 /* mmap failed, but the previous region might have been
564 * unmapped anyway. try to remap it
569 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
570 munmap(va, alloc_sz);
574 /* In linux, hugetlb limitations, like cgroup, are
575 * enforced at fault time instead of mmap(), even
576 * with the option of MAP_POPULATE. Kernel will send
577 * a SIGBUS signal. To avoid to be killed, save stack
578 * environment here, if SIGBUS happens, we can jump
581 if (huge_wrap_sigsetjmp()) {
582 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
583 (unsigned int)(alloc_sz >> 20));
587 /* we need to trigger a write to the page to enforce page fault and
588 * ensure that page is accessible to us, but we can't overwrite value
589 * that is already there, so read the old value, and write itback.
590 * kernel populates the page with zeroes initially.
592 *(volatile int *)addr = *(volatile int *)addr;
594 iova = rte_mem_virt2iova(addr);
595 if (iova == RTE_BAD_PHYS_ADDR) {
596 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
601 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
602 move_pages(getpid(), 1, &addr, NULL, &cur_socket_id, 0);
604 if (cur_socket_id != socket_id) {
606 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
607 __func__, socket_id, cur_socket_id);
611 if (rte_socket_count() > 1)
612 RTE_LOG(DEBUG, EAL, "%s(): not checking hugepage NUMA node.\n",
617 ms->hugepage_sz = alloc_sz;
619 ms->nchannel = rte_memory_get_nchannel();
620 ms->nrank = rte_memory_get_nrank();
622 ms->socket_id = socket_id;
627 munmap(addr, alloc_sz);
630 new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
631 if (new_addr != addr) {
632 if (new_addr != NULL)
633 munmap(new_addr, alloc_sz);
634 /* we're leaving a hole in our virtual address space. if
635 * somebody else maps this hole now, we could accidentally
636 * override it in the future.
638 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
640 /* roll back the ref count */
641 if (internal_config.single_file_segments)
642 fd_list[list_idx].count--;
644 /* some codepaths will return negative fd, so exit early */
648 if (internal_config.single_file_segments) {
649 resize_hugefile(fd, map_offset, alloc_sz, false);
650 /* ignore failure, can't make it any worse */
652 /* if refcount is at zero, close the file */
653 if (fd_list[list_idx].count == 0)
654 close_hugefile(fd, path, list_idx);
656 /* only remove file if we can take out a write lock */
657 if (internal_config.hugepage_unlink == 0 &&
658 internal_config.in_memory == 0 &&
659 lock(fd, LOCK_EX) == 1)
662 fd_list[list_idx].fds[seg_idx] = -1;
668 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
669 unsigned int list_idx, unsigned int seg_idx)
676 /* erase page data */
677 memset(ms->addr, 0, ms->len);
679 if (mmap(ms->addr, ms->len, PROT_READ,
680 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
682 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
688 /* if we're using anonymous hugepages, nothing to be done */
689 if (internal_config.in_memory && !memfd_create_supported)
692 /* if we've already unlinked the page, nothing needs to be done */
693 if (!internal_config.in_memory && internal_config.hugepage_unlink)
697 memset(ms, 0, sizeof(*ms));
701 /* if we are not in single file segments mode, we're going to unmap the
702 * segment and thus drop the lock on original fd, but hugepage dir is
703 * now locked so we can take out another one without races.
705 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
709 if (internal_config.single_file_segments) {
710 map_offset = seg_idx * ms->len;
711 if (resize_hugefile(fd, map_offset, ms->len, false))
714 if (--(fd_list[list_idx].count) == 0)
715 close_hugefile(fd, path, list_idx);
719 /* if we're able to take out a write lock, we're the last one
720 * holding onto this page.
722 if (!internal_config.in_memory) {
723 ret = lock(fd, LOCK_EX);
725 /* no one else is using this page */
730 /* closing fd will drop the lock */
732 fd_list[list_idx].fds[seg_idx] = -1;
735 memset(ms, 0, sizeof(*ms));
737 return ret < 0 ? -1 : 0;
740 struct alloc_walk_param {
741 struct hugepage_info *hi;
742 struct rte_memseg **ms;
744 unsigned int segs_allocated;
750 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
752 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
753 struct alloc_walk_param *wa = arg;
754 struct rte_memseg_list *cur_msl;
756 int cur_idx, start_idx, j, dir_fd = -1;
757 unsigned int msl_idx, need, i;
759 if (msl->page_sz != wa->page_sz)
761 if (msl->socket_id != wa->socket)
764 page_sz = (size_t)msl->page_sz;
766 msl_idx = msl - mcfg->memsegs;
767 cur_msl = &mcfg->memsegs[msl_idx];
771 /* try finding space in memseg list */
773 /* if we require exact number of pages in a list, find them */
774 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0,
782 /* we don't require exact number of pages, so we're going to go
783 * for best-effort allocation. that means finding the biggest
784 * unused block, and going with that.
786 cur_idx = rte_fbarray_find_biggest_free(&cur_msl->memseg_arr,
791 /* adjust the size to possibly be smaller than original
792 * request, but do not allow it to be bigger.
794 cur_len = rte_fbarray_find_contig_free(&cur_msl->memseg_arr,
796 need = RTE_MIN(need, (unsigned int)cur_len);
799 /* do not allow any page allocations during the time we're allocating,
800 * because file creation and locking operations are not atomic,
801 * and we might be the first or the last ones to use a particular page,
802 * so we need to ensure atomicity of every operation.
804 * during init, we already hold a write lock, so don't try to take out
807 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
808 dir_fd = open(wa->hi->hugedir, O_RDONLY);
810 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
811 __func__, wa->hi->hugedir, strerror(errno));
814 /* blocking writelock */
815 if (flock(dir_fd, LOCK_EX)) {
816 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
817 __func__, wa->hi->hugedir, strerror(errno));
823 for (i = 0; i < need; i++, cur_idx++) {
824 struct rte_memseg *cur;
827 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
828 map_addr = RTE_PTR_ADD(cur_msl->base_va,
831 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
833 RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
836 /* if exact number wasn't requested, stop */
841 for (j = start_idx; j < cur_idx; j++) {
842 struct rte_memseg *tmp;
843 struct rte_fbarray *arr =
844 &cur_msl->memseg_arr;
846 tmp = rte_fbarray_get(arr, j);
847 rte_fbarray_set_free(arr, j);
849 /* free_seg may attempt to create a file, which
852 if (free_seg(tmp, wa->hi, msl_idx, j))
853 RTE_LOG(DEBUG, EAL, "Cannot free page\n");
857 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
866 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
869 wa->segs_allocated = i;
874 /* if we didn't allocate any segments, move on to the next list */
878 struct free_walk_param {
879 struct hugepage_info *hi;
880 struct rte_memseg *ms;
883 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
885 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
886 struct rte_memseg_list *found_msl;
887 struct free_walk_param *wa = arg;
888 uintptr_t start_addr, end_addr;
889 int msl_idx, seg_idx, ret, dir_fd = -1;
891 start_addr = (uintptr_t) msl->base_va;
892 end_addr = start_addr + msl->len;
894 if ((uintptr_t)wa->ms->addr < start_addr ||
895 (uintptr_t)wa->ms->addr >= end_addr)
898 msl_idx = msl - mcfg->memsegs;
899 seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
902 found_msl = &mcfg->memsegs[msl_idx];
904 /* do not allow any page allocations during the time we're freeing,
905 * because file creation and locking operations are not atomic,
906 * and we might be the first or the last ones to use a particular page,
907 * so we need to ensure atomicity of every operation.
909 * during init, we already hold a write lock, so don't try to take out
912 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
913 dir_fd = open(wa->hi->hugedir, O_RDONLY);
915 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
916 __func__, wa->hi->hugedir, strerror(errno));
919 /* blocking writelock */
920 if (flock(dir_fd, LOCK_EX)) {
921 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
922 __func__, wa->hi->hugedir, strerror(errno));
928 found_msl->version++;
930 rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
932 ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
944 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
945 int socket, bool exact)
948 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
949 bool have_numa = false;
951 struct bitmask *oldmask;
953 struct alloc_walk_param wa;
954 struct hugepage_info *hi = NULL;
956 memset(&wa, 0, sizeof(wa));
958 /* dynamic allocation not supported in legacy mode */
959 if (internal_config.legacy_mem)
962 for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
964 internal_config.hugepage_info[i].hugepage_sz) {
965 hi = &internal_config.hugepage_info[i];
970 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
975 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
977 oldmask = numa_allocate_nodemask();
978 prepare_numa(&oldpolicy, oldmask, socket);
987 wa.page_sz = page_sz;
989 wa.segs_allocated = 0;
991 /* memalloc is locked, so it's safe to use thread-unsafe version */
992 ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
994 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
997 } else if (ret > 0) {
998 ret = (int)wa.segs_allocated;
1001 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1003 restore_numa(&oldpolicy, oldmask);
1009 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1011 struct rte_memseg *ms;
1012 if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1014 /* return pointer to newly allocated memseg */
1019 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1023 /* dynamic free not supported in legacy mode */
1024 if (internal_config.legacy_mem)
1027 for (seg = 0; seg < n_segs; seg++) {
1028 struct rte_memseg *cur = ms[seg];
1029 struct hugepage_info *hi = NULL;
1030 struct free_walk_param wa;
1033 /* if this page is marked as unfreeable, fail */
1034 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1035 RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1040 memset(&wa, 0, sizeof(wa));
1042 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
1044 hi = &internal_config.hugepage_info[i];
1045 if (cur->hugepage_sz == hi->hugepage_sz)
1048 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1049 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1057 /* memalloc is locked, so it's safe to use thread-unsafe version
1059 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1064 RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1071 eal_memalloc_free_seg(struct rte_memseg *ms)
1073 /* dynamic free not supported in legacy mode */
1074 if (internal_config.legacy_mem)
1077 return eal_memalloc_free_seg_bulk(&ms, 1);
1081 sync_chunk(struct rte_memseg_list *primary_msl,
1082 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1083 unsigned int msl_idx, bool used, int start, int end)
1085 struct rte_fbarray *l_arr, *p_arr;
1086 int i, ret, chunk_len, diff_len;
1088 l_arr = &local_msl->memseg_arr;
1089 p_arr = &primary_msl->memseg_arr;
1091 /* we need to aggregate allocations/deallocations into bigger chunks,
1092 * as we don't want to spam the user with per-page callbacks.
1094 * to avoid any potential issues, we also want to trigger
1095 * deallocation callbacks *before* we actually deallocate
1096 * memory, so that the user application could wrap up its use
1097 * before it goes away.
1100 chunk_len = end - start;
1102 /* find how many contiguous pages we can map/unmap for this chunk */
1104 rte_fbarray_find_contig_free(l_arr, start) :
1105 rte_fbarray_find_contig_used(l_arr, start);
1107 /* has to be at least one page */
1111 diff_len = RTE_MIN(chunk_len, diff_len);
1113 /* if we are freeing memory, notify the application */
1115 struct rte_memseg *ms;
1117 size_t len, page_sz;
1119 ms = rte_fbarray_get(l_arr, start);
1120 start_va = ms->addr;
1121 page_sz = (size_t)primary_msl->page_sz;
1122 len = page_sz * diff_len;
1124 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1128 for (i = 0; i < diff_len; i++) {
1129 struct rte_memseg *p_ms, *l_ms;
1130 int seg_idx = start + i;
1132 l_ms = rte_fbarray_get(l_arr, seg_idx);
1133 p_ms = rte_fbarray_get(p_arr, seg_idx);
1135 if (l_ms == NULL || p_ms == NULL)
1139 ret = alloc_seg(l_ms, p_ms->addr,
1140 p_ms->socket_id, hi,
1144 rte_fbarray_set_used(l_arr, seg_idx);
1146 ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1147 rte_fbarray_set_free(l_arr, seg_idx);
1153 /* if we just allocated memory, notify the application */
1155 struct rte_memseg *ms;
1157 size_t len, page_sz;
1159 ms = rte_fbarray_get(l_arr, start);
1160 start_va = ms->addr;
1161 page_sz = (size_t)primary_msl->page_sz;
1162 len = page_sz * diff_len;
1164 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1168 /* calculate how much we can advance until next chunk */
1170 rte_fbarray_find_contig_used(l_arr, start) :
1171 rte_fbarray_find_contig_free(l_arr, start);
1172 ret = RTE_MIN(chunk_len, diff_len);
1178 sync_status(struct rte_memseg_list *primary_msl,
1179 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1180 unsigned int msl_idx, bool used)
1182 struct rte_fbarray *l_arr, *p_arr;
1183 int p_idx, l_chunk_len, p_chunk_len, ret;
1186 /* this is a little bit tricky, but the basic idea is - walk both lists
1187 * and spot any places where there are discrepancies. walking both lists
1188 * and noting discrepancies in a single go is a hard problem, so we do
1189 * it in two passes - first we spot any places where allocated segments
1190 * mismatch (i.e. ensure that everything that's allocated in the primary
1191 * is also allocated in the secondary), and then we do it by looking at
1192 * free segments instead.
1194 * we also need to aggregate changes into chunks, as we have to call
1195 * callbacks per allocation, not per page.
1197 l_arr = &local_msl->memseg_arr;
1198 p_arr = &primary_msl->memseg_arr;
1201 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1203 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1205 while (p_idx >= 0) {
1206 int next_chunk_search_idx;
1209 p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1211 l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1214 p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1216 l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1219 /* best case scenario - no differences (or bigger, which will be
1220 * fixed during next iteration), look for next chunk
1222 if (l_chunk_len >= p_chunk_len) {
1223 next_chunk_search_idx = p_idx + p_chunk_len;
1227 /* if both chunks start at the same point, skip parts we know
1228 * are identical, and sync the rest. each call to sync_chunk
1229 * will only sync contiguous segments, so we need to call this
1230 * until we are sure there are no more differences in this
1233 start = p_idx + l_chunk_len;
1234 end = p_idx + p_chunk_len;
1236 ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1239 } while (start < end && ret >= 0);
1240 /* if ret is negative, something went wrong */
1244 next_chunk_search_idx = p_idx + p_chunk_len;
1246 /* skip to end of this chunk */
1248 p_idx = rte_fbarray_find_next_used(p_arr,
1249 next_chunk_search_idx);
1251 p_idx = rte_fbarray_find_next_free(p_arr,
1252 next_chunk_search_idx);
1259 sync_existing(struct rte_memseg_list *primary_msl,
1260 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1261 unsigned int msl_idx)
1265 /* do not allow any page allocations during the time we're allocating,
1266 * because file creation and locking operations are not atomic,
1267 * and we might be the first or the last ones to use a particular page,
1268 * so we need to ensure atomicity of every operation.
1270 dir_fd = open(hi->hugedir, O_RDONLY);
1272 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1273 hi->hugedir, strerror(errno));
1276 /* blocking writelock */
1277 if (flock(dir_fd, LOCK_EX)) {
1278 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1279 hi->hugedir, strerror(errno));
1284 /* ensure all allocated space is the same in both lists */
1285 ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1289 /* ensure all unallocated space is the same in both lists */
1290 ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1294 /* update version number */
1295 local_msl->version = primary_msl->version;
1306 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1308 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1309 struct rte_memseg_list *primary_msl, *local_msl;
1310 struct hugepage_info *hi = NULL;
1317 msl_idx = msl - mcfg->memsegs;
1318 primary_msl = &mcfg->memsegs[msl_idx];
1319 local_msl = &local_memsegs[msl_idx];
1321 for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1323 internal_config.hugepage_info[i].hugepage_sz;
1324 uint64_t msl_sz = primary_msl->page_sz;
1325 if (msl_sz == cur_sz) {
1326 hi = &internal_config.hugepage_info[i];
1331 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1335 /* if versions don't match, synchronize everything */
1336 if (local_msl->version != primary_msl->version &&
1337 sync_existing(primary_msl, local_msl, hi, msl_idx))
1344 eal_memalloc_sync_with_primary(void)
1346 /* nothing to be done in primary */
1347 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1350 /* memalloc is locked, so it's safe to call thread-unsafe version */
1351 if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1357 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1358 void *arg __rte_unused)
1360 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1361 struct rte_memseg_list *primary_msl, *local_msl;
1362 char name[PATH_MAX];
1368 msl_idx = msl - mcfg->memsegs;
1369 primary_msl = &mcfg->memsegs[msl_idx];
1370 local_msl = &local_memsegs[msl_idx];
1372 /* create distinct fbarrays for each secondary */
1373 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1374 primary_msl->memseg_arr.name, getpid());
1376 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1377 primary_msl->memseg_arr.len,
1378 primary_msl->memseg_arr.elt_sz);
1380 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1383 local_msl->base_va = primary_msl->base_va;
1384 local_msl->len = primary_msl->len;
1390 alloc_list(int list_idx, int len)
1395 /* single-file segments mode does not need fd list */
1396 if (!internal_config.single_file_segments) {
1397 /* ensure we have space to store fd per each possible segment */
1398 data = malloc(sizeof(int) * len);
1400 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1403 /* set all fd's as invalid */
1404 for (i = 0; i < len; i++)
1406 fd_list[list_idx].fds = data;
1407 fd_list[list_idx].len = len;
1409 fd_list[list_idx].fds = NULL;
1410 fd_list[list_idx].len = 0;
1413 fd_list[list_idx].count = 0;
1414 fd_list[list_idx].memseg_list_fd = -1;
1420 fd_list_create_walk(const struct rte_memseg_list *msl,
1421 void *arg __rte_unused)
1423 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1430 msl_idx = msl - mcfg->memsegs;
1431 len = msl->memseg_arr.len;
1433 return alloc_list(msl_idx, len);
1437 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1439 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1441 /* single file segments mode doesn't support individual segment fd's */
1442 if (internal_config.single_file_segments)
1445 /* if list is not allocated, allocate it */
1446 if (fd_list[list_idx].len == 0) {
1447 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1449 if (alloc_list(list_idx, len) < 0)
1452 fd_list[list_idx].fds[seg_idx] = fd;
1458 eal_memalloc_set_seg_list_fd(int list_idx, int fd)
1460 /* non-single file segment mode doesn't support segment list fd's */
1461 if (!internal_config.single_file_segments)
1464 fd_list[list_idx].memseg_list_fd = fd;
1470 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1474 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1475 #ifndef MEMFD_SUPPORTED
1476 /* in in-memory or no-huge mode, we rely on memfd support */
1479 /* memfd supported, but hugetlbfs memfd may not be */
1480 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1484 if (internal_config.single_file_segments) {
1485 fd = fd_list[list_idx].memseg_list_fd;
1486 } else if (fd_list[list_idx].len == 0) {
1487 /* list not initialized */
1490 fd = fd_list[list_idx].fds[seg_idx];
1498 test_memfd_create(void)
1500 #ifdef MEMFD_SUPPORTED
1502 for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1503 uint64_t pagesz = internal_config.hugepage_info[i].hugepage_sz;
1504 int pagesz_flag = pagesz_flags(pagesz);
1507 flags = pagesz_flag | RTE_MFD_HUGETLB;
1508 int fd = memfd_create("test", flags);
1510 /* we failed - let memalloc know this isn't working */
1511 if (errno == EINVAL) {
1512 memfd_create_supported = 0;
1513 return 0; /* not supported */
1516 /* we got other error - something's wrong */
1517 return -1; /* error */
1520 return 1; /* supported */
1523 return 0; /* not supported */
1527 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1529 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1531 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1532 #ifndef MEMFD_SUPPORTED
1533 /* in in-memory or no-huge mode, we rely on memfd support */
1536 /* memfd supported, but hugetlbfs memfd may not be */
1537 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1541 if (internal_config.single_file_segments) {
1542 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1544 /* segment not active? */
1545 if (fd_list[list_idx].memseg_list_fd < 0)
1547 *offset = pgsz * seg_idx;
1549 /* fd_list not initialized? */
1550 if (fd_list[list_idx].len == 0)
1553 /* segment not active? */
1554 if (fd_list[list_idx].fds[seg_idx] < 0)
1562 eal_memalloc_init(void)
1564 if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1565 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1567 if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1568 internal_config.in_memory) {
1569 int mfd_res = test_memfd_create();
1572 RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1576 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1578 RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1580 /* we only support single-file segments mode with in-memory mode
1581 * if we support hugetlbfs with memfd_create. this code will
1584 if (internal_config.single_file_segments &&
1586 RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1589 /* this cannot ever happen but better safe than sorry */
1590 if (!anonymous_hugepages_supported) {
1591 RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1596 /* initialize all of the fd lists */
1597 if (rte_memseg_list_walk(fd_list_create_walk, NULL))