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>
39 #include <rte_errno.h>
40 #include <rte_memory.h>
41 #include <rte_spinlock.h>
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"
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 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 huge_wrap_sigsetjmp(void)
121 return sigsetjmp(huge_jmpenv, 1);
124 static struct sigaction huge_action_old;
125 static int huge_need_recover;
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);
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);
252 const struct internal_config *internal_conf =
253 eal_get_internal_configuration();
255 if (internal_conf->single_file_segments) {
256 fd = fd_list[list_idx].memseg_list_fd;
259 snprintf(segname, sizeof(segname), "seg_%i", list_idx);
260 fd = memfd_create(segname, flags);
262 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
263 __func__, strerror(errno));
266 fd_list[list_idx].memseg_list_fd = fd;
269 fd = fd_list[list_idx].fds[seg_idx];
272 snprintf(segname, sizeof(segname), "seg_%i-%i",
274 fd = memfd_create(segname, flags);
276 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
277 __func__, strerror(errno));
280 fd_list[list_idx].fds[seg_idx] = fd;
289 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
290 unsigned int list_idx, unsigned int seg_idx,
297 const struct internal_config *internal_conf =
298 eal_get_internal_configuration();
303 /* for in-memory mode, we only make it here when we're sure we support
304 * memfd, and this is a special case.
306 if (internal_conf->in_memory)
307 return get_seg_memfd(hi, list_idx, seg_idx);
309 if (internal_conf->single_file_segments) {
310 out_fd = &fd_list[list_idx].memseg_list_fd;
311 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
313 out_fd = &fd_list[list_idx].fds[seg_idx];
314 eal_get_hugefile_path(path, buflen, hi->hugedir,
315 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
322 * There is no TOCTOU between stat() and unlink()/open()
323 * because the hugepage directory is locked.
325 ret = stat(path, &st);
326 if (ret < 0 && errno != ENOENT) {
327 RTE_LOG(DEBUG, EAL, "%s(): stat() for '%s' failed: %s\n",
328 __func__, path, strerror(errno));
331 if (!internal_conf->hugepage_file.unlink_existing && ret == 0 &&
336 * The kernel clears a hugepage only when it is mapped
337 * from a particular file for the first time.
338 * If the file already exists, the old content will be mapped.
339 * If the memory manager assumes all mapped pages to be clean,
340 * the file must be removed and created anew.
341 * Otherwise, the primary caller must be notified
342 * that mapped pages will be dirty
343 * (secondary callers receive the segment state from the primary one).
344 * When multiple hugepages are mapped from the same file,
345 * whether they will be dirty depends on the part that is mapped.
347 if (!internal_conf->single_file_segments &&
348 internal_conf->hugepage_file.unlink_existing &&
349 rte_eal_process_type() == RTE_PROC_PRIMARY &&
351 /* coverity[toctou] */
352 if (unlink(path) < 0) {
353 RTE_LOG(DEBUG, EAL, "%s(): could not remove '%s': %s\n",
354 __func__, path, strerror(errno));
359 /* coverity[toctou] */
360 fd = open(path, O_CREAT | O_RDWR, 0600);
362 RTE_LOG(ERR, EAL, "%s(): open '%s' failed: %s\n",
363 __func__, path, strerror(errno));
366 /* take out a read lock */
367 if (lock(fd, LOCK_SH) < 0) {
368 RTE_LOG(ERR, EAL, "%s(): lock '%s' failed: %s\n",
369 __func__, path, strerror(errno));
378 resize_hugefile_in_memory(int fd, uint64_t fa_offset,
379 uint64_t page_sz, bool grow)
381 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
385 /* grow or shrink the file */
386 ret = fallocate(fd, flags, fa_offset, page_sz);
389 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
398 resize_hugefile_in_filesystem(int fd, uint64_t fa_offset, uint64_t page_sz,
399 bool grow, bool *dirty)
401 const struct internal_config *internal_conf =
402 eal_get_internal_configuration();
406 if (fallocate_supported == 0) {
407 /* we cannot deallocate memory if fallocate() is not
408 * supported, and hugepage file is already locked at
409 * creation, so no further synchronization needed.
413 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
417 uint64_t new_size = fa_offset + page_sz;
418 uint64_t cur_size = get_file_size(fd);
420 /* fallocate isn't supported, fall back to ftruncate */
422 *dirty = new_size <= cur_size;
423 if (new_size > cur_size &&
424 ftruncate(fd, new_size) < 0) {
425 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
426 __func__, strerror(errno));
430 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
435 * technically, it is perfectly safe for both primary
436 * and secondary to grow and shrink the page files:
437 * growing the file repeatedly has no effect because
438 * a page can only be allocated once, while mmap ensures
439 * that secondaries hold on to the page even after the
440 * page itself is removed from the filesystem.
442 * however, leaving growing/shrinking to the primary
443 * tends to expose bugs in fdlist page count handling,
444 * so leave this here just in case.
446 if (rte_eal_process_type() != RTE_PROC_PRIMARY)
449 /* grow or shrink the file */
450 ret = fallocate(fd, flags, fa_offset, page_sz);
453 if (fallocate_supported == -1 &&
455 RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
458 fallocate_supported = 0;
460 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
466 fallocate_supported = 1;
468 * It is unknown which portions of an existing
469 * hugepage file were allocated previously,
470 * so all pages within the file are considered
471 * dirty, unless the file is a fresh one.
474 *dirty &= !internal_conf->hugepage_file.unlink_existing;
483 close_hugefile(int fd, char *path, int list_idx)
485 const struct internal_config *internal_conf =
486 eal_get_internal_configuration();
488 * primary process must unlink the file, but only when not in in-memory
489 * mode (as in that case there is no file to unlink).
491 if (!internal_conf->in_memory &&
492 rte_eal_process_type() == RTE_PROC_PRIMARY &&
494 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
495 __func__, path, strerror(errno));
498 fd_list[list_idx].memseg_list_fd = -1;
502 resize_hugefile(int fd, uint64_t fa_offset, uint64_t page_sz, bool grow,
505 /* in-memory mode is a special case, because we can be sure that
506 * fallocate() is supported.
508 const struct internal_config *internal_conf =
509 eal_get_internal_configuration();
511 if (internal_conf->in_memory) {
514 return resize_hugefile_in_memory(fd, fa_offset,
518 return resize_hugefile_in_filesystem(fd, fa_offset, page_sz,
523 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
524 struct hugepage_info *hi, unsigned int list_idx,
525 unsigned int seg_idx)
527 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
528 int cur_socket_id = 0;
540 const struct internal_config *internal_conf =
541 eal_get_internal_configuration();
543 alloc_sz = hi->hugepage_sz;
545 /* these are checked at init, but code analyzers don't know that */
546 if (internal_conf->in_memory && !anonymous_hugepages_supported) {
547 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
550 if (internal_conf->in_memory && !memfd_create_supported &&
551 internal_conf->single_file_segments) {
552 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
556 /* in-memory without memfd is a special case */
559 if (internal_conf->in_memory && !memfd_create_supported) {
560 const int in_memory_flags = MAP_HUGETLB | MAP_FIXED |
561 MAP_PRIVATE | MAP_ANONYMOUS;
564 pagesz_flag = pagesz_flags(alloc_sz);
567 mmap_flags = in_memory_flags | pagesz_flag;
569 /* single-file segments codepath will never be active
570 * here because in-memory mode is incompatible with the
571 * fallback path, and it's stopped at EAL initialization
576 /* takes out a read lock on segment or segment list */
577 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx,
580 RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
584 if (internal_conf->single_file_segments) {
585 map_offset = seg_idx * alloc_sz;
586 ret = resize_hugefile(fd, map_offset, alloc_sz, true,
591 fd_list[list_idx].count++;
594 if (ftruncate(fd, alloc_sz) < 0) {
595 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
596 __func__, strerror(errno));
599 if (internal_conf->hugepage_file.unlink_before_mapping &&
600 !internal_conf->in_memory) {
602 RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
603 __func__, strerror(errno));
608 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
611 huge_register_sigbus();
614 * map the segment, and populate page tables, the kernel fills
615 * this segment with zeros if it's a new page.
617 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
620 if (va == MAP_FAILED) {
621 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
623 /* mmap failed, but the previous region might have been
624 * unmapped anyway. try to remap it
629 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
630 munmap(va, alloc_sz);
634 /* In linux, hugetlb limitations, like cgroup, are
635 * enforced at fault time instead of mmap(), even
636 * with the option of MAP_POPULATE. Kernel will send
637 * a SIGBUS signal. To avoid to be killed, save stack
638 * environment here, if SIGBUS happens, we can jump
641 if (huge_wrap_sigsetjmp()) {
642 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
643 (unsigned int)(alloc_sz >> 20));
647 /* we need to trigger a write to the page to enforce page fault and
648 * ensure that page is accessible to us, but we can't overwrite value
649 * that is already there, so read the old value, and write itback.
650 * kernel populates the page with zeroes initially.
652 *(volatile int *)addr = *(volatile int *)addr;
654 iova = rte_mem_virt2iova(addr);
655 if (iova == RTE_BAD_PHYS_ADDR) {
656 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
661 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
663 * If the kernel has been built without NUMA support, get_mempolicy()
664 * will return an error. If check_numa() returns false, memory
665 * allocation is not NUMA aware and the socket_id should not be
669 ret = get_mempolicy(&cur_socket_id, NULL, 0, addr,
670 MPOL_F_NODE | MPOL_F_ADDR);
672 RTE_LOG(DEBUG, EAL, "%s(): get_mempolicy: %s\n",
673 __func__, strerror(errno));
675 } else if (cur_socket_id != socket_id) {
677 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
678 __func__, socket_id, cur_socket_id);
683 if (rte_socket_count() > 1)
684 RTE_LOG(DEBUG, EAL, "%s(): not checking hugepage NUMA node.\n",
688 huge_recover_sigbus();
691 ms->hugepage_sz = alloc_sz;
693 ms->nchannel = rte_memory_get_nchannel();
694 ms->nrank = rte_memory_get_nrank();
696 ms->socket_id = socket_id;
697 ms->flags = dirty ? RTE_MEMSEG_FLAG_DIRTY : 0;
702 munmap(addr, alloc_sz);
704 huge_recover_sigbus();
705 flags = EAL_RESERVE_FORCE_ADDRESS;
706 new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
707 if (new_addr != addr) {
708 if (new_addr != NULL)
709 munmap(new_addr, alloc_sz);
710 /* we're leaving a hole in our virtual address space. if
711 * somebody else maps this hole now, we could accidentally
712 * override it in the future.
714 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
716 /* roll back the ref count */
717 if (internal_conf->single_file_segments)
718 fd_list[list_idx].count--;
720 /* some codepaths will return negative fd, so exit early */
724 if (internal_conf->single_file_segments) {
725 resize_hugefile(fd, map_offset, alloc_sz, false, NULL);
726 /* ignore failure, can't make it any worse */
728 /* if refcount is at zero, close the file */
729 if (fd_list[list_idx].count == 0)
730 close_hugefile(fd, path, list_idx);
732 /* only remove file if we can take out a write lock */
733 if (!internal_conf->hugepage_file.unlink_before_mapping &&
734 internal_conf->in_memory == 0 &&
735 lock(fd, LOCK_EX) == 1)
738 fd_list[list_idx].fds[seg_idx] = -1;
744 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
745 unsigned int list_idx, unsigned int seg_idx)
750 const struct internal_config *internal_conf =
751 eal_get_internal_configuration();
753 /* erase page data */
754 memset(ms->addr, 0, ms->len);
756 if (mmap(ms->addr, ms->len, PROT_NONE,
757 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
759 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
763 eal_mem_set_dump(ms->addr, ms->len, false);
765 /* if we're using anonymous hugepages, nothing to be done */
766 if (internal_conf->in_memory && !memfd_create_supported) {
767 memset(ms, 0, sizeof(*ms));
771 /* if we are not in single file segments mode, we're going to unmap the
772 * segment and thus drop the lock on original fd, but hugepage dir is
773 * now locked so we can take out another one without races.
775 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx, NULL);
779 if (internal_conf->single_file_segments) {
780 map_offset = seg_idx * ms->len;
781 if (resize_hugefile(fd, map_offset, ms->len, false, NULL))
784 if (--(fd_list[list_idx].count) == 0)
785 close_hugefile(fd, path, list_idx);
789 /* if we're able to take out a write lock, we're the last one
790 * holding onto this page.
792 if (!internal_conf->in_memory &&
793 internal_conf->hugepage_file.unlink_existing &&
794 !internal_conf->hugepage_file.unlink_before_mapping) {
795 ret = lock(fd, LOCK_EX);
797 /* no one else is using this page */
802 /* closing fd will drop the lock */
804 fd_list[list_idx].fds[seg_idx] = -1;
807 memset(ms, 0, sizeof(*ms));
809 return ret < 0 ? -1 : 0;
812 struct alloc_walk_param {
813 struct hugepage_info *hi;
814 struct rte_memseg **ms;
816 unsigned int segs_allocated;
822 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
824 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
825 struct alloc_walk_param *wa = arg;
826 struct rte_memseg_list *cur_msl;
828 int cur_idx, start_idx, j, dir_fd = -1;
829 unsigned int msl_idx, need, i;
830 const struct internal_config *internal_conf =
831 eal_get_internal_configuration();
833 if (msl->page_sz != wa->page_sz)
835 if (msl->socket_id != wa->socket)
838 page_sz = (size_t)msl->page_sz;
840 msl_idx = msl - mcfg->memsegs;
841 cur_msl = &mcfg->memsegs[msl_idx];
845 /* try finding space in memseg list */
847 /* if we require exact number of pages in a list, find them */
848 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0,
856 /* we don't require exact number of pages, so we're going to go
857 * for best-effort allocation. that means finding the biggest
858 * unused block, and going with that.
860 cur_idx = rte_fbarray_find_biggest_free(&cur_msl->memseg_arr,
865 /* adjust the size to possibly be smaller than original
866 * request, but do not allow it to be bigger.
868 cur_len = rte_fbarray_find_contig_free(&cur_msl->memseg_arr,
870 need = RTE_MIN(need, (unsigned int)cur_len);
873 /* do not allow any page allocations during the time we're allocating,
874 * because file creation and locking operations are not atomic,
875 * and we might be the first or the last ones to use a particular page,
876 * so we need to ensure atomicity of every operation.
878 * during init, we already hold a write lock, so don't try to take out
881 if (wa->hi->lock_descriptor == -1 && !internal_conf->in_memory) {
882 dir_fd = open(wa->hi->hugedir, O_RDONLY);
884 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
885 __func__, wa->hi->hugedir, strerror(errno));
888 /* blocking writelock */
889 if (flock(dir_fd, LOCK_EX)) {
890 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
891 __func__, wa->hi->hugedir, strerror(errno));
897 for (i = 0; i < need; i++, cur_idx++) {
898 struct rte_memseg *cur;
901 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
902 map_addr = RTE_PTR_ADD(cur_msl->base_va,
905 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
907 RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
910 /* if exact number wasn't requested, stop */
915 for (j = start_idx; j < cur_idx; j++) {
916 struct rte_memseg *tmp;
917 struct rte_fbarray *arr =
918 &cur_msl->memseg_arr;
920 tmp = rte_fbarray_get(arr, j);
921 rte_fbarray_set_free(arr, j);
923 /* free_seg may attempt to create a file, which
926 if (free_seg(tmp, wa->hi, msl_idx, j))
927 RTE_LOG(DEBUG, EAL, "Cannot free page\n");
931 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
940 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
943 wa->segs_allocated = i;
948 /* if we didn't allocate any segments, move on to the next list */
952 struct free_walk_param {
953 struct hugepage_info *hi;
954 struct rte_memseg *ms;
957 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
959 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
960 struct rte_memseg_list *found_msl;
961 struct free_walk_param *wa = arg;
962 uintptr_t start_addr, end_addr;
963 int msl_idx, seg_idx, ret, dir_fd = -1;
964 const struct internal_config *internal_conf =
965 eal_get_internal_configuration();
967 start_addr = (uintptr_t) msl->base_va;
968 end_addr = start_addr + msl->len;
970 if ((uintptr_t)wa->ms->addr < start_addr ||
971 (uintptr_t)wa->ms->addr >= end_addr)
974 msl_idx = msl - mcfg->memsegs;
975 seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
978 found_msl = &mcfg->memsegs[msl_idx];
980 /* do not allow any page allocations during the time we're freeing,
981 * because file creation and locking operations are not atomic,
982 * and we might be the first or the last ones to use a particular page,
983 * so we need to ensure atomicity of every operation.
985 * during init, we already hold a write lock, so don't try to take out
988 if (wa->hi->lock_descriptor == -1 && !internal_conf->in_memory) {
989 dir_fd = open(wa->hi->hugedir, O_RDONLY);
991 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
992 __func__, wa->hi->hugedir, strerror(errno));
995 /* blocking writelock */
996 if (flock(dir_fd, LOCK_EX)) {
997 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
998 __func__, wa->hi->hugedir, strerror(errno));
1004 found_msl->version++;
1006 rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
1008 ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
1020 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
1021 int socket, bool exact)
1024 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1025 bool have_numa = false;
1027 struct bitmask *oldmask;
1029 struct alloc_walk_param wa;
1030 struct hugepage_info *hi = NULL;
1031 struct internal_config *internal_conf =
1032 eal_get_internal_configuration();
1034 memset(&wa, 0, sizeof(wa));
1036 /* dynamic allocation not supported in legacy mode */
1037 if (internal_conf->legacy_mem)
1040 for (i = 0; i < (int) RTE_DIM(internal_conf->hugepage_info); i++) {
1042 internal_conf->hugepage_info[i].hugepage_sz) {
1043 hi = &internal_conf->hugepage_info[i];
1048 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
1053 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1055 oldmask = numa_allocate_nodemask();
1056 prepare_numa(&oldpolicy, oldmask, socket);
1065 wa.page_sz = page_sz;
1067 wa.segs_allocated = 0;
1069 /* memalloc is locked, so it's safe to use thread-unsafe version */
1070 ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1072 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1075 } else if (ret > 0) {
1076 ret = (int)wa.segs_allocated;
1079 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1081 restore_numa(&oldpolicy, oldmask);
1087 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1089 struct rte_memseg *ms;
1090 if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1092 /* return pointer to newly allocated memseg */
1097 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1100 struct internal_config *internal_conf =
1101 eal_get_internal_configuration();
1103 /* dynamic free not supported in legacy mode */
1104 if (internal_conf->legacy_mem)
1107 for (seg = 0; seg < n_segs; seg++) {
1108 struct rte_memseg *cur = ms[seg];
1109 struct hugepage_info *hi = NULL;
1110 struct free_walk_param wa;
1113 /* if this page is marked as unfreeable, fail */
1114 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1115 RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1120 memset(&wa, 0, sizeof(wa));
1122 for (i = 0; i < (int)RTE_DIM(internal_conf->hugepage_info);
1124 hi = &internal_conf->hugepage_info[i];
1125 if (cur->hugepage_sz == hi->hugepage_sz)
1128 if (i == (int)RTE_DIM(internal_conf->hugepage_info)) {
1129 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1137 /* memalloc is locked, so it's safe to use thread-unsafe version
1139 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1144 RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1151 eal_memalloc_free_seg(struct rte_memseg *ms)
1153 const struct internal_config *internal_conf =
1154 eal_get_internal_configuration();
1156 /* dynamic free not supported in legacy mode */
1157 if (internal_conf->legacy_mem)
1160 return eal_memalloc_free_seg_bulk(&ms, 1);
1164 sync_chunk(struct rte_memseg_list *primary_msl,
1165 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1166 unsigned int msl_idx, bool used, int start, int end)
1168 struct rte_fbarray *l_arr, *p_arr;
1169 int i, ret, chunk_len, diff_len;
1171 l_arr = &local_msl->memseg_arr;
1172 p_arr = &primary_msl->memseg_arr;
1174 /* we need to aggregate allocations/deallocations into bigger chunks,
1175 * as we don't want to spam the user with per-page callbacks.
1177 * to avoid any potential issues, we also want to trigger
1178 * deallocation callbacks *before* we actually deallocate
1179 * memory, so that the user application could wrap up its use
1180 * before it goes away.
1183 chunk_len = end - start;
1185 /* find how many contiguous pages we can map/unmap for this chunk */
1187 rte_fbarray_find_contig_free(l_arr, start) :
1188 rte_fbarray_find_contig_used(l_arr, start);
1190 /* has to be at least one page */
1194 diff_len = RTE_MIN(chunk_len, diff_len);
1196 /* if we are freeing memory, notify the application */
1198 struct rte_memseg *ms;
1200 size_t len, page_sz;
1202 ms = rte_fbarray_get(l_arr, start);
1203 start_va = ms->addr;
1204 page_sz = (size_t)primary_msl->page_sz;
1205 len = page_sz * diff_len;
1207 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1211 for (i = 0; i < diff_len; i++) {
1212 struct rte_memseg *p_ms, *l_ms;
1213 int seg_idx = start + i;
1215 l_ms = rte_fbarray_get(l_arr, seg_idx);
1216 p_ms = rte_fbarray_get(p_arr, seg_idx);
1218 if (l_ms == NULL || p_ms == NULL)
1222 ret = alloc_seg(l_ms, p_ms->addr,
1223 p_ms->socket_id, hi,
1227 rte_fbarray_set_used(l_arr, seg_idx);
1229 ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1230 rte_fbarray_set_free(l_arr, seg_idx);
1236 /* if we just allocated memory, notify the application */
1238 struct rte_memseg *ms;
1240 size_t len, page_sz;
1242 ms = rte_fbarray_get(l_arr, start);
1243 start_va = ms->addr;
1244 page_sz = (size_t)primary_msl->page_sz;
1245 len = page_sz * diff_len;
1247 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1251 /* calculate how much we can advance until next chunk */
1253 rte_fbarray_find_contig_used(l_arr, start) :
1254 rte_fbarray_find_contig_free(l_arr, start);
1255 ret = RTE_MIN(chunk_len, diff_len);
1261 sync_status(struct rte_memseg_list *primary_msl,
1262 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1263 unsigned int msl_idx, bool used)
1265 struct rte_fbarray *l_arr, *p_arr;
1266 int p_idx, l_chunk_len, p_chunk_len, ret;
1269 /* this is a little bit tricky, but the basic idea is - walk both lists
1270 * and spot any places where there are discrepancies. walking both lists
1271 * and noting discrepancies in a single go is a hard problem, so we do
1272 * it in two passes - first we spot any places where allocated segments
1273 * mismatch (i.e. ensure that everything that's allocated in the primary
1274 * is also allocated in the secondary), and then we do it by looking at
1275 * free segments instead.
1277 * we also need to aggregate changes into chunks, as we have to call
1278 * callbacks per allocation, not per page.
1280 l_arr = &local_msl->memseg_arr;
1281 p_arr = &primary_msl->memseg_arr;
1284 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1286 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1288 while (p_idx >= 0) {
1289 int next_chunk_search_idx;
1292 p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1294 l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1297 p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1299 l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1302 /* best case scenario - no differences (or bigger, which will be
1303 * fixed during next iteration), look for next chunk
1305 if (l_chunk_len >= p_chunk_len) {
1306 next_chunk_search_idx = p_idx + p_chunk_len;
1310 /* if both chunks start at the same point, skip parts we know
1311 * are identical, and sync the rest. each call to sync_chunk
1312 * will only sync contiguous segments, so we need to call this
1313 * until we are sure there are no more differences in this
1316 start = p_idx + l_chunk_len;
1317 end = p_idx + p_chunk_len;
1319 ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1322 } while (start < end && ret >= 0);
1323 /* if ret is negative, something went wrong */
1327 next_chunk_search_idx = p_idx + p_chunk_len;
1329 /* skip to end of this chunk */
1331 p_idx = rte_fbarray_find_next_used(p_arr,
1332 next_chunk_search_idx);
1334 p_idx = rte_fbarray_find_next_free(p_arr,
1335 next_chunk_search_idx);
1342 sync_existing(struct rte_memseg_list *primary_msl,
1343 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1344 unsigned int msl_idx)
1348 /* do not allow any page allocations during the time we're allocating,
1349 * because file creation and locking operations are not atomic,
1350 * and we might be the first or the last ones to use a particular page,
1351 * so we need to ensure atomicity of every operation.
1353 dir_fd = open(hi->hugedir, O_RDONLY);
1355 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1356 hi->hugedir, strerror(errno));
1359 /* blocking writelock */
1360 if (flock(dir_fd, LOCK_EX)) {
1361 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1362 hi->hugedir, strerror(errno));
1367 /* ensure all allocated space is the same in both lists */
1368 ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1372 /* ensure all unallocated space is the same in both lists */
1373 ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1377 /* update version number */
1378 local_msl->version = primary_msl->version;
1389 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1391 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1392 struct rte_memseg_list *primary_msl, *local_msl;
1393 struct hugepage_info *hi = NULL;
1396 struct internal_config *internal_conf =
1397 eal_get_internal_configuration();
1402 msl_idx = msl - mcfg->memsegs;
1403 primary_msl = &mcfg->memsegs[msl_idx];
1404 local_msl = &local_memsegs[msl_idx];
1406 for (i = 0; i < RTE_DIM(internal_conf->hugepage_info); i++) {
1408 internal_conf->hugepage_info[i].hugepage_sz;
1409 uint64_t msl_sz = primary_msl->page_sz;
1410 if (msl_sz == cur_sz) {
1411 hi = &internal_conf->hugepage_info[i];
1416 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1420 /* if versions don't match, synchronize everything */
1421 if (local_msl->version != primary_msl->version &&
1422 sync_existing(primary_msl, local_msl, hi, msl_idx))
1429 eal_memalloc_sync_with_primary(void)
1431 /* nothing to be done in primary */
1432 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1435 /* memalloc is locked, so it's safe to call thread-unsafe version */
1436 if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1442 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1443 void *arg __rte_unused)
1445 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1446 struct rte_memseg_list *primary_msl, *local_msl;
1447 char name[PATH_MAX];
1453 msl_idx = msl - mcfg->memsegs;
1454 primary_msl = &mcfg->memsegs[msl_idx];
1455 local_msl = &local_memsegs[msl_idx];
1457 /* create distinct fbarrays for each secondary */
1458 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1459 primary_msl->memseg_arr.name, getpid());
1461 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1462 primary_msl->memseg_arr.len,
1463 primary_msl->memseg_arr.elt_sz);
1465 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1468 local_msl->base_va = primary_msl->base_va;
1469 local_msl->len = primary_msl->len;
1475 secondary_msl_destroy_walk(const struct rte_memseg_list *msl,
1476 void *arg __rte_unused)
1478 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1479 struct rte_memseg_list *local_msl;
1485 msl_idx = msl - mcfg->memsegs;
1486 local_msl = &local_memsegs[msl_idx];
1488 ret = rte_fbarray_destroy(&local_msl->memseg_arr);
1490 RTE_LOG(ERR, EAL, "Cannot destroy local memory map\n");
1493 local_msl->base_va = NULL;
1500 alloc_list(int list_idx, int len)
1504 const struct internal_config *internal_conf =
1505 eal_get_internal_configuration();
1507 /* single-file segments mode does not need fd list */
1508 if (!internal_conf->single_file_segments) {
1509 /* ensure we have space to store fd per each possible segment */
1510 data = malloc(sizeof(int) * len);
1512 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1515 /* set all fd's as invalid */
1516 for (i = 0; i < len; i++)
1518 fd_list[list_idx].fds = data;
1519 fd_list[list_idx].len = len;
1521 fd_list[list_idx].fds = NULL;
1522 fd_list[list_idx].len = 0;
1525 fd_list[list_idx].count = 0;
1526 fd_list[list_idx].memseg_list_fd = -1;
1532 destroy_list(int list_idx)
1534 const struct internal_config *internal_conf =
1535 eal_get_internal_configuration();
1537 /* single-file segments mode does not need fd list */
1538 if (!internal_conf->single_file_segments) {
1539 int *fds = fd_list[list_idx].fds;
1541 /* go through each fd and ensure it's closed */
1542 for (i = 0; i < fd_list[list_idx].len; i++) {
1549 fd_list[list_idx].fds = NULL;
1550 fd_list[list_idx].len = 0;
1551 } else if (fd_list[list_idx].memseg_list_fd >= 0) {
1552 close(fd_list[list_idx].memseg_list_fd);
1553 fd_list[list_idx].count = 0;
1554 fd_list[list_idx].memseg_list_fd = -1;
1560 fd_list_create_walk(const struct rte_memseg_list *msl,
1561 void *arg __rte_unused)
1563 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1570 msl_idx = msl - mcfg->memsegs;
1571 len = msl->memseg_arr.len;
1573 return alloc_list(msl_idx, len);
1577 fd_list_destroy_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1579 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1585 msl_idx = msl - mcfg->memsegs;
1587 return destroy_list(msl_idx);
1591 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1593 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1594 const struct internal_config *internal_conf =
1595 eal_get_internal_configuration();
1597 /* single file segments mode doesn't support individual segment fd's */
1598 if (internal_conf->single_file_segments)
1601 /* if list is not allocated, allocate it */
1602 if (fd_list[list_idx].len == 0) {
1603 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1605 if (alloc_list(list_idx, len) < 0)
1608 fd_list[list_idx].fds[seg_idx] = fd;
1614 eal_memalloc_set_seg_list_fd(int list_idx, int fd)
1616 const struct internal_config *internal_conf =
1617 eal_get_internal_configuration();
1619 /* non-single file segment mode doesn't support segment list fd's */
1620 if (!internal_conf->single_file_segments)
1623 fd_list[list_idx].memseg_list_fd = fd;
1629 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1632 const struct internal_config *internal_conf =
1633 eal_get_internal_configuration();
1635 if (internal_conf->in_memory || internal_conf->no_hugetlbfs) {
1636 #ifndef MEMFD_SUPPORTED
1637 /* in in-memory or no-huge mode, we rely on memfd support */
1640 /* memfd supported, but hugetlbfs memfd may not be */
1641 if (!internal_conf->no_hugetlbfs && !memfd_create_supported)
1645 if (internal_conf->single_file_segments) {
1646 fd = fd_list[list_idx].memseg_list_fd;
1647 } else if (fd_list[list_idx].len == 0) {
1648 /* list not initialized */
1651 fd = fd_list[list_idx].fds[seg_idx];
1659 test_memfd_create(void)
1661 #ifdef MEMFD_SUPPORTED
1662 const struct internal_config *internal_conf =
1663 eal_get_internal_configuration();
1665 for (i = 0; i < internal_conf->num_hugepage_sizes; i++) {
1666 uint64_t pagesz = internal_conf->hugepage_info[i].hugepage_sz;
1667 int pagesz_flag = pagesz_flags(pagesz);
1670 flags = pagesz_flag | RTE_MFD_HUGETLB;
1671 int fd = memfd_create("test", flags);
1673 /* we failed - let memalloc know this isn't working */
1674 if (errno == EINVAL) {
1675 memfd_create_supported = 0;
1676 return 0; /* not supported */
1679 /* we got other error - something's wrong */
1680 return -1; /* error */
1683 return 1; /* supported */
1686 return 0; /* not supported */
1690 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1692 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1693 const struct internal_config *internal_conf =
1694 eal_get_internal_configuration();
1696 if (internal_conf->in_memory || internal_conf->no_hugetlbfs) {
1697 #ifndef MEMFD_SUPPORTED
1698 /* in in-memory or no-huge mode, we rely on memfd support */
1701 /* memfd supported, but hugetlbfs memfd may not be */
1702 if (!internal_conf->no_hugetlbfs && !memfd_create_supported)
1706 if (internal_conf->single_file_segments) {
1707 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1709 /* segment not active? */
1710 if (fd_list[list_idx].memseg_list_fd < 0)
1712 *offset = pgsz * seg_idx;
1714 /* fd_list not initialized? */
1715 if (fd_list[list_idx].len == 0)
1718 /* segment not active? */
1719 if (fd_list[list_idx].fds[seg_idx] < 0)
1727 eal_memalloc_cleanup(void)
1729 /* close all remaining fd's - these are per-process, so it's safe */
1730 if (rte_memseg_list_walk_thread_unsafe(fd_list_destroy_walk, NULL))
1733 /* destroy the shadow page table if we're a secondary process */
1734 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1737 if (rte_memseg_list_walk_thread_unsafe(secondary_msl_destroy_walk,
1745 eal_memalloc_init(void)
1747 const struct internal_config *internal_conf =
1748 eal_get_internal_configuration();
1750 if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1751 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1753 if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1754 internal_conf->in_memory) {
1755 int mfd_res = test_memfd_create();
1758 RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1762 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1764 RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1766 /* we only support single-file segments mode with in-memory mode
1767 * if we support hugetlbfs with memfd_create. this code will
1770 if (internal_conf->single_file_segments &&
1772 RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1775 /* this cannot ever happen but better safe than sorry */
1776 if (!anonymous_hugepages_supported) {
1777 RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1780 /* safety net, should be impossible to configure */
1781 if (internal_conf->hugepage_file.unlink_before_mapping &&
1782 !internal_conf->hugepage_file.unlink_existing) {
1783 RTE_LOG(ERR, EAL, "Unlinking existing hugepage files is prohibited, cannot unlink them before mapping.\n");
1788 /* initialize all of the fd lists */
1789 if (rte_memseg_list_walk(fd_list_create_walk, NULL))