1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2017-2018 Intel Corporation
19 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
20 #include <linux/memfd.h>
21 #define MEMFD_SUPPORTED
23 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
27 #include <linux/falloc.h>
28 #include <linux/mman.h> /* for hugetlb-related mmap flags */
30 #include <rte_common.h>
33 #include <rte_memory.h>
35 #include "eal_filesystem.h"
36 #include "eal_internal_cfg.h"
37 #include "eal_memalloc.h"
38 #include "eal_memcfg.h"
39 #include "eal_private.h"
41 const int anonymous_hugepages_supported =
44 #define RTE_MAP_HUGE_SHIFT MAP_HUGE_SHIFT
47 #define RTE_MAP_HUGE_SHIFT 26
51 * we've already checked memfd support at compile-time, but we also need to
52 * check if we can create hugepage files with memfd.
54 * also, this is not a constant, because while we may be *compiled* with memfd
55 * hugetlbfs support, we might not be *running* on a system that supports memfd
56 * and/or memfd with hugetlbfs, so we need to be able to adjust this flag at
57 * runtime, and fall back to anonymous memory.
59 static int memfd_create_supported =
62 #define RTE_MFD_HUGETLB MFD_HUGETLB
65 #define RTE_MFD_HUGETLB 4U
69 * not all kernel version support fallocate on hugetlbfs, so fall back to
70 * ftruncate and disallow deallocation if fallocate is not supported.
72 static int fallocate_supported = -1; /* unknown */
75 * we have two modes - single file segments, and file-per-page mode.
77 * for single-file segments, we use memseg_list_fd to store the segment fd,
78 * while the fds[] will not be allocated, and len will be set to 0.
80 * for file-per-page mode, each page will have its own fd, so 'memseg_list_fd'
81 * will be invalid (set to -1), and we'll use 'fds' to keep track of page fd's.
83 * we cannot know how many pages a system will have in advance, but we do know
84 * that they come in lists, and we know lengths of these lists. so, simply store
85 * a malloc'd array of fd's indexed by list and segment index.
87 * they will be initialized at startup, and filled as we allocate/deallocate
91 int *fds; /**< dynamically allocated array of segment lock fd's */
92 int memseg_list_fd; /**< memseg list fd */
93 int len; /**< total length of the array */
94 int count; /**< entries used in an array */
95 } fd_list[RTE_MAX_MEMSEG_LISTS];
97 /** local copy of a memory map, used to synchronize memory hotplug in MP */
98 static struct rte_memseg_list local_memsegs[RTE_MAX_MEMSEG_LISTS];
100 static sigjmp_buf huge_jmpenv;
102 static void huge_sigbus_handler(int signo __rte_unused)
104 siglongjmp(huge_jmpenv, 1);
107 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
108 * non-static local variable in the stack frame calling sigsetjmp might be
109 * clobbered by a call to longjmp.
111 static int huge_wrap_sigsetjmp(void)
113 return sigsetjmp(huge_jmpenv, 1);
116 static struct sigaction huge_action_old;
117 static int huge_need_recover;
120 huge_register_sigbus(void)
123 struct sigaction action;
126 sigaddset(&mask, SIGBUS);
128 action.sa_mask = mask;
129 action.sa_handler = huge_sigbus_handler;
131 huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
135 huge_recover_sigbus(void)
137 if (huge_need_recover) {
138 sigaction(SIGBUS, &huge_action_old, NULL);
139 huge_need_recover = 0;
143 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
148 /* Check if kernel supports NUMA. */
149 if (numa_available() != 0) {
150 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
157 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
159 RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
160 if (get_mempolicy(oldpolicy, oldmask->maskp,
161 oldmask->size + 1, 0, 0) < 0) {
163 "Failed to get current mempolicy: %s. "
164 "Assuming MPOL_DEFAULT.\n", strerror(errno));
165 *oldpolicy = MPOL_DEFAULT;
168 "Setting policy MPOL_PREFERRED for socket %d\n",
170 numa_set_preferred(socket_id);
174 restore_numa(int *oldpolicy, struct bitmask *oldmask)
177 "Restoring previous memory policy: %d\n", *oldpolicy);
178 if (*oldpolicy == MPOL_DEFAULT) {
179 numa_set_localalloc();
180 } else if (set_mempolicy(*oldpolicy, oldmask->maskp,
181 oldmask->size + 1) < 0) {
182 RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
184 numa_set_localalloc();
186 numa_free_cpumask(oldmask);
191 * uses fstat to report the size of a file on disk
194 get_file_size(int fd)
197 if (fstat(fd, &st) < 0)
203 pagesz_flags(uint64_t page_sz)
205 /* as per mmap() manpage, all page sizes are log2 of page size
206 * shifted by MAP_HUGE_SHIFT
208 int log2 = rte_log2_u64(page_sz);
209 return log2 << RTE_MAP_HUGE_SHIFT;
212 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
213 static int lock(int fd, int type)
217 /* flock may be interrupted */
219 ret = flock(fd, type | LOCK_NB);
220 } while (ret && errno == EINTR);
222 if (ret && errno == EWOULDBLOCK) {
226 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
227 __func__, strerror(errno));
230 /* lock was successful */
235 get_seg_memfd(struct hugepage_info *hi __rte_unused,
236 unsigned int list_idx __rte_unused,
237 unsigned int seg_idx __rte_unused)
239 #ifdef MEMFD_SUPPORTED
241 char segname[250]; /* as per manpage, limit is 249 bytes plus null */
243 int flags = RTE_MFD_HUGETLB | pagesz_flags(hi->hugepage_sz);
244 const struct internal_config *internal_conf =
245 eal_get_internal_configuration();
247 if (internal_conf->single_file_segments) {
248 fd = fd_list[list_idx].memseg_list_fd;
251 snprintf(segname, sizeof(segname), "seg_%i", list_idx);
252 fd = memfd_create(segname, flags);
254 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
255 __func__, strerror(errno));
258 fd_list[list_idx].memseg_list_fd = fd;
261 fd = fd_list[list_idx].fds[seg_idx];
264 snprintf(segname, sizeof(segname), "seg_%i-%i",
266 fd = memfd_create(segname, flags);
268 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
269 __func__, strerror(errno));
272 fd_list[list_idx].fds[seg_idx] = fd;
281 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
282 unsigned int list_idx, unsigned int seg_idx,
289 const struct internal_config *internal_conf =
290 eal_get_internal_configuration();
295 /* for in-memory mode, we only make it here when we're sure we support
296 * memfd, and this is a special case.
298 if (internal_conf->in_memory)
299 return get_seg_memfd(hi, list_idx, seg_idx);
301 if (internal_conf->single_file_segments) {
302 out_fd = &fd_list[list_idx].memseg_list_fd;
303 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
305 out_fd = &fd_list[list_idx].fds[seg_idx];
306 eal_get_hugefile_path(path, buflen, hi->hugedir,
307 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
314 * There is no TOCTOU between stat() and unlink()/open()
315 * because the hugepage directory is locked.
317 ret = stat(path, &st);
318 if (ret < 0 && errno != ENOENT) {
319 RTE_LOG(DEBUG, EAL, "%s(): stat() for '%s' failed: %s\n",
320 __func__, path, strerror(errno));
323 if (!internal_conf->hugepage_file.unlink_existing && ret == 0 &&
328 * The kernel clears a hugepage only when it is mapped
329 * from a particular file for the first time.
330 * If the file already exists, the old content will be mapped.
331 * If the memory manager assumes all mapped pages to be clean,
332 * the file must be removed and created anew.
333 * Otherwise, the primary caller must be notified
334 * that mapped pages will be dirty
335 * (secondary callers receive the segment state from the primary one).
336 * When multiple hugepages are mapped from the same file,
337 * whether they will be dirty depends on the part that is mapped.
339 if (!internal_conf->single_file_segments &&
340 internal_conf->hugepage_file.unlink_existing &&
341 rte_eal_process_type() == RTE_PROC_PRIMARY &&
343 /* coverity[toctou] */
344 if (unlink(path) < 0) {
345 RTE_LOG(DEBUG, EAL, "%s(): could not remove '%s': %s\n",
346 __func__, path, strerror(errno));
351 /* coverity[toctou] */
352 fd = open(path, O_CREAT | O_RDWR, 0600);
354 RTE_LOG(ERR, EAL, "%s(): open '%s' failed: %s\n",
355 __func__, path, strerror(errno));
358 /* take out a read lock */
359 if (lock(fd, LOCK_SH) < 0) {
360 RTE_LOG(ERR, EAL, "%s(): lock '%s' failed: %s\n",
361 __func__, path, strerror(errno));
370 resize_hugefile_in_memory(int fd, uint64_t fa_offset,
371 uint64_t page_sz, bool grow)
373 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
377 /* grow or shrink the file */
378 ret = fallocate(fd, flags, fa_offset, page_sz);
381 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
390 resize_hugefile_in_filesystem(int fd, uint64_t fa_offset, uint64_t page_sz,
391 bool grow, bool *dirty)
393 const struct internal_config *internal_conf =
394 eal_get_internal_configuration();
398 if (fallocate_supported == 0) {
399 /* we cannot deallocate memory if fallocate() is not
400 * supported, and hugepage file is already locked at
401 * creation, so no further synchronization needed.
405 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
409 uint64_t new_size = fa_offset + page_sz;
410 uint64_t cur_size = get_file_size(fd);
412 /* fallocate isn't supported, fall back to ftruncate */
414 *dirty = new_size <= cur_size;
415 if (new_size > cur_size &&
416 ftruncate(fd, new_size) < 0) {
417 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
418 __func__, strerror(errno));
422 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
427 * technically, it is perfectly safe for both primary
428 * and secondary to grow and shrink the page files:
429 * growing the file repeatedly has no effect because
430 * a page can only be allocated once, while mmap ensures
431 * that secondaries hold on to the page even after the
432 * page itself is removed from the filesystem.
434 * however, leaving growing/shrinking to the primary
435 * tends to expose bugs in fdlist page count handling,
436 * so leave this here just in case.
438 if (rte_eal_process_type() != RTE_PROC_PRIMARY)
441 /* grow or shrink the file */
442 ret = fallocate(fd, flags, fa_offset, page_sz);
445 if (fallocate_supported == -1 &&
447 RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
450 fallocate_supported = 0;
452 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
458 fallocate_supported = 1;
460 * It is unknown which portions of an existing
461 * hugepage file were allocated previously,
462 * so all pages within the file are considered
463 * dirty, unless the file is a fresh one.
466 *dirty &= !internal_conf->hugepage_file.unlink_existing;
475 close_hugefile(int fd, char *path, int list_idx)
477 const struct internal_config *internal_conf =
478 eal_get_internal_configuration();
480 * primary process must unlink the file, but only when not in in-memory
481 * mode (as in that case there is no file to unlink).
483 if (!internal_conf->in_memory &&
484 rte_eal_process_type() == RTE_PROC_PRIMARY &&
486 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
487 __func__, path, strerror(errno));
490 fd_list[list_idx].memseg_list_fd = -1;
494 resize_hugefile(int fd, uint64_t fa_offset, uint64_t page_sz, bool grow,
497 /* in-memory mode is a special case, because we can be sure that
498 * fallocate() is supported.
500 const struct internal_config *internal_conf =
501 eal_get_internal_configuration();
503 if (internal_conf->in_memory) {
506 return resize_hugefile_in_memory(fd, fa_offset,
510 return resize_hugefile_in_filesystem(fd, fa_offset, page_sz,
515 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
516 struct hugepage_info *hi, unsigned int list_idx,
517 unsigned int seg_idx)
519 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
520 int cur_socket_id = 0;
532 const struct internal_config *internal_conf =
533 eal_get_internal_configuration();
535 alloc_sz = hi->hugepage_sz;
537 /* these are checked at init, but code analyzers don't know that */
538 if (internal_conf->in_memory && !anonymous_hugepages_supported) {
539 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
542 if (internal_conf->in_memory && !memfd_create_supported &&
543 internal_conf->single_file_segments) {
544 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
548 /* in-memory without memfd is a special case */
551 if (internal_conf->in_memory && !memfd_create_supported) {
552 const int in_memory_flags = MAP_HUGETLB | MAP_FIXED |
553 MAP_PRIVATE | MAP_ANONYMOUS;
556 pagesz_flag = pagesz_flags(alloc_sz);
559 mmap_flags = in_memory_flags | pagesz_flag;
561 /* single-file segments codepath will never be active
562 * here because in-memory mode is incompatible with the
563 * fallback path, and it's stopped at EAL initialization
568 /* takes out a read lock on segment or segment list */
569 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx,
572 RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
576 if (internal_conf->single_file_segments) {
577 map_offset = seg_idx * alloc_sz;
578 ret = resize_hugefile(fd, map_offset, alloc_sz, true,
583 fd_list[list_idx].count++;
586 if (ftruncate(fd, alloc_sz) < 0) {
587 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
588 __func__, strerror(errno));
591 if (internal_conf->hugepage_file.unlink_before_mapping &&
592 !internal_conf->in_memory) {
594 RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
595 __func__, strerror(errno));
600 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
603 huge_register_sigbus();
606 * map the segment, and populate page tables, the kernel fills
607 * this segment with zeros if it's a new page.
609 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
612 if (va == MAP_FAILED) {
613 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
615 /* mmap failed, but the previous region might have been
616 * unmapped anyway. try to remap it
621 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
622 munmap(va, alloc_sz);
626 /* In linux, hugetlb limitations, like cgroup, are
627 * enforced at fault time instead of mmap(), even
628 * with the option of MAP_POPULATE. Kernel will send
629 * a SIGBUS signal. To avoid to be killed, save stack
630 * environment here, if SIGBUS happens, we can jump
633 if (huge_wrap_sigsetjmp()) {
634 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
635 (unsigned int)(alloc_sz >> 20));
639 /* we need to trigger a write to the page to enforce page fault and
640 * ensure that page is accessible to us, but we can't overwrite value
641 * that is already there, so read the old value, and write itback.
642 * kernel populates the page with zeroes initially.
644 *(volatile int *)addr = *(volatile int *)addr;
646 iova = rte_mem_virt2iova(addr);
647 if (iova == RTE_BAD_PHYS_ADDR) {
648 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
653 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
655 * If the kernel has been built without NUMA support, get_mempolicy()
656 * will return an error. If check_numa() returns false, memory
657 * allocation is not NUMA aware and the socket_id should not be
661 ret = get_mempolicy(&cur_socket_id, NULL, 0, addr,
662 MPOL_F_NODE | MPOL_F_ADDR);
664 RTE_LOG(DEBUG, EAL, "%s(): get_mempolicy: %s\n",
665 __func__, strerror(errno));
667 } else if (cur_socket_id != socket_id) {
669 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
670 __func__, socket_id, cur_socket_id);
675 if (rte_socket_count() > 1)
676 RTE_LOG(DEBUG, EAL, "%s(): not checking hugepage NUMA node.\n",
680 huge_recover_sigbus();
683 ms->hugepage_sz = alloc_sz;
685 ms->nchannel = rte_memory_get_nchannel();
686 ms->nrank = rte_memory_get_nrank();
688 ms->socket_id = socket_id;
689 ms->flags = dirty ? RTE_MEMSEG_FLAG_DIRTY : 0;
694 munmap(addr, alloc_sz);
696 huge_recover_sigbus();
697 flags = EAL_RESERVE_FORCE_ADDRESS;
698 new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
699 if (new_addr != addr) {
700 if (new_addr != NULL)
701 munmap(new_addr, alloc_sz);
702 /* we're leaving a hole in our virtual address space. if
703 * somebody else maps this hole now, we could accidentally
704 * override it in the future.
706 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
708 /* roll back the ref count */
709 if (internal_conf->single_file_segments)
710 fd_list[list_idx].count--;
712 /* some codepaths will return negative fd, so exit early */
716 if (internal_conf->single_file_segments) {
717 resize_hugefile(fd, map_offset, alloc_sz, false, NULL);
718 /* ignore failure, can't make it any worse */
720 /* if refcount is at zero, close the file */
721 if (fd_list[list_idx].count == 0)
722 close_hugefile(fd, path, list_idx);
724 /* only remove file if we can take out a write lock */
725 if (!internal_conf->hugepage_file.unlink_before_mapping &&
726 internal_conf->in_memory == 0 &&
727 lock(fd, LOCK_EX) == 1)
730 fd_list[list_idx].fds[seg_idx] = -1;
736 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
737 unsigned int list_idx, unsigned int seg_idx)
742 const struct internal_config *internal_conf =
743 eal_get_internal_configuration();
745 /* erase page data */
746 memset(ms->addr, 0, ms->len);
748 if (mmap(ms->addr, ms->len, PROT_NONE,
749 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
751 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
755 eal_mem_set_dump(ms->addr, ms->len, false);
757 /* if we're using anonymous hugepages, nothing to be done */
758 if (internal_conf->in_memory && !memfd_create_supported) {
759 memset(ms, 0, sizeof(*ms));
763 /* if we are not in single file segments mode, we're going to unmap the
764 * segment and thus drop the lock on original fd, but hugepage dir is
765 * now locked so we can take out another one without races.
767 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx, NULL);
771 if (internal_conf->single_file_segments) {
772 map_offset = seg_idx * ms->len;
773 if (resize_hugefile(fd, map_offset, ms->len, false, NULL))
776 if (--(fd_list[list_idx].count) == 0)
777 close_hugefile(fd, path, list_idx);
781 /* if we're able to take out a write lock, we're the last one
782 * holding onto this page.
784 if (!internal_conf->in_memory &&
785 internal_conf->hugepage_file.unlink_existing &&
786 !internal_conf->hugepage_file.unlink_before_mapping) {
787 ret = lock(fd, LOCK_EX);
789 /* no one else is using this page */
794 /* closing fd will drop the lock */
796 fd_list[list_idx].fds[seg_idx] = -1;
799 memset(ms, 0, sizeof(*ms));
801 return ret < 0 ? -1 : 0;
804 struct alloc_walk_param {
805 struct hugepage_info *hi;
806 struct rte_memseg **ms;
808 unsigned int segs_allocated;
814 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
816 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
817 struct alloc_walk_param *wa = arg;
818 struct rte_memseg_list *cur_msl;
820 int cur_idx, start_idx, j, dir_fd = -1;
821 unsigned int msl_idx, need, i;
822 const struct internal_config *internal_conf =
823 eal_get_internal_configuration();
825 if (msl->page_sz != wa->page_sz)
827 if (msl->socket_id != wa->socket)
830 page_sz = (size_t)msl->page_sz;
832 msl_idx = msl - mcfg->memsegs;
833 cur_msl = &mcfg->memsegs[msl_idx];
837 /* try finding space in memseg list */
839 /* if we require exact number of pages in a list, find them */
840 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0,
848 /* we don't require exact number of pages, so we're going to go
849 * for best-effort allocation. that means finding the biggest
850 * unused block, and going with that.
852 cur_idx = rte_fbarray_find_biggest_free(&cur_msl->memseg_arr,
857 /* adjust the size to possibly be smaller than original
858 * request, but do not allow it to be bigger.
860 cur_len = rte_fbarray_find_contig_free(&cur_msl->memseg_arr,
862 need = RTE_MIN(need, (unsigned int)cur_len);
865 /* do not allow any page allocations during the time we're allocating,
866 * because file creation and locking operations are not atomic,
867 * and we might be the first or the last ones to use a particular page,
868 * so we need to ensure atomicity of every operation.
870 * during init, we already hold a write lock, so don't try to take out
873 if (wa->hi->lock_descriptor == -1 && !internal_conf->in_memory) {
874 dir_fd = open(wa->hi->hugedir, O_RDONLY);
876 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
877 __func__, wa->hi->hugedir, strerror(errno));
880 /* blocking writelock */
881 if (flock(dir_fd, LOCK_EX)) {
882 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
883 __func__, wa->hi->hugedir, strerror(errno));
889 for (i = 0; i < need; i++, cur_idx++) {
890 struct rte_memseg *cur;
893 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
894 map_addr = RTE_PTR_ADD(cur_msl->base_va,
897 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
899 RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
902 /* if exact number wasn't requested, stop */
907 for (j = start_idx; j < cur_idx; j++) {
908 struct rte_memseg *tmp;
909 struct rte_fbarray *arr =
910 &cur_msl->memseg_arr;
912 tmp = rte_fbarray_get(arr, j);
913 rte_fbarray_set_free(arr, j);
915 /* free_seg may attempt to create a file, which
918 if (free_seg(tmp, wa->hi, msl_idx, j))
919 RTE_LOG(DEBUG, EAL, "Cannot free page\n");
923 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
932 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
935 wa->segs_allocated = i;
940 /* if we didn't allocate any segments, move on to the next list */
944 struct free_walk_param {
945 struct hugepage_info *hi;
946 struct rte_memseg *ms;
949 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
951 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
952 struct rte_memseg_list *found_msl;
953 struct free_walk_param *wa = arg;
954 uintptr_t start_addr, end_addr;
955 int msl_idx, seg_idx, ret, dir_fd = -1;
956 const struct internal_config *internal_conf =
957 eal_get_internal_configuration();
959 start_addr = (uintptr_t) msl->base_va;
960 end_addr = start_addr + msl->len;
962 if ((uintptr_t)wa->ms->addr < start_addr ||
963 (uintptr_t)wa->ms->addr >= end_addr)
966 msl_idx = msl - mcfg->memsegs;
967 seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
970 found_msl = &mcfg->memsegs[msl_idx];
972 /* do not allow any page allocations during the time we're freeing,
973 * because file creation and locking operations are not atomic,
974 * and we might be the first or the last ones to use a particular page,
975 * so we need to ensure atomicity of every operation.
977 * during init, we already hold a write lock, so don't try to take out
980 if (wa->hi->lock_descriptor == -1 && !internal_conf->in_memory) {
981 dir_fd = open(wa->hi->hugedir, O_RDONLY);
983 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
984 __func__, wa->hi->hugedir, strerror(errno));
987 /* blocking writelock */
988 if (flock(dir_fd, LOCK_EX)) {
989 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
990 __func__, wa->hi->hugedir, strerror(errno));
996 found_msl->version++;
998 rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
1000 ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
1012 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
1013 int socket, bool exact)
1016 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1017 bool have_numa = false;
1019 struct bitmask *oldmask;
1021 struct alloc_walk_param wa;
1022 struct hugepage_info *hi = NULL;
1023 struct internal_config *internal_conf =
1024 eal_get_internal_configuration();
1026 memset(&wa, 0, sizeof(wa));
1028 /* dynamic allocation not supported in legacy mode */
1029 if (internal_conf->legacy_mem)
1032 for (i = 0; i < (int) RTE_DIM(internal_conf->hugepage_info); i++) {
1034 internal_conf->hugepage_info[i].hugepage_sz) {
1035 hi = &internal_conf->hugepage_info[i];
1040 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
1045 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1047 oldmask = numa_allocate_nodemask();
1048 prepare_numa(&oldpolicy, oldmask, socket);
1057 wa.page_sz = page_sz;
1059 wa.segs_allocated = 0;
1061 /* memalloc is locked, so it's safe to use thread-unsafe version */
1062 ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1064 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1067 } else if (ret > 0) {
1068 ret = (int)wa.segs_allocated;
1071 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1073 restore_numa(&oldpolicy, oldmask);
1079 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1081 struct rte_memseg *ms;
1082 if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1084 /* return pointer to newly allocated memseg */
1089 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1092 struct internal_config *internal_conf =
1093 eal_get_internal_configuration();
1095 /* dynamic free not supported in legacy mode */
1096 if (internal_conf->legacy_mem)
1099 for (seg = 0; seg < n_segs; seg++) {
1100 struct rte_memseg *cur = ms[seg];
1101 struct hugepage_info *hi = NULL;
1102 struct free_walk_param wa;
1105 /* if this page is marked as unfreeable, fail */
1106 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1107 RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1112 memset(&wa, 0, sizeof(wa));
1114 for (i = 0; i < (int)RTE_DIM(internal_conf->hugepage_info);
1116 hi = &internal_conf->hugepage_info[i];
1117 if (cur->hugepage_sz == hi->hugepage_sz)
1120 if (i == (int)RTE_DIM(internal_conf->hugepage_info)) {
1121 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1129 /* memalloc is locked, so it's safe to use thread-unsafe version
1131 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1136 RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1143 eal_memalloc_free_seg(struct rte_memseg *ms)
1145 const struct internal_config *internal_conf =
1146 eal_get_internal_configuration();
1148 /* dynamic free not supported in legacy mode */
1149 if (internal_conf->legacy_mem)
1152 return eal_memalloc_free_seg_bulk(&ms, 1);
1156 sync_chunk(struct rte_memseg_list *primary_msl,
1157 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1158 unsigned int msl_idx, bool used, int start, int end)
1160 struct rte_fbarray *l_arr, *p_arr;
1161 int i, ret, chunk_len, diff_len;
1163 l_arr = &local_msl->memseg_arr;
1164 p_arr = &primary_msl->memseg_arr;
1166 /* we need to aggregate allocations/deallocations into bigger chunks,
1167 * as we don't want to spam the user with per-page callbacks.
1169 * to avoid any potential issues, we also want to trigger
1170 * deallocation callbacks *before* we actually deallocate
1171 * memory, so that the user application could wrap up its use
1172 * before it goes away.
1175 chunk_len = end - start;
1177 /* find how many contiguous pages we can map/unmap for this chunk */
1179 rte_fbarray_find_contig_free(l_arr, start) :
1180 rte_fbarray_find_contig_used(l_arr, start);
1182 /* has to be at least one page */
1186 diff_len = RTE_MIN(chunk_len, diff_len);
1188 /* if we are freeing memory, notify the application */
1190 struct rte_memseg *ms;
1192 size_t len, page_sz;
1194 ms = rte_fbarray_get(l_arr, start);
1195 start_va = ms->addr;
1196 page_sz = (size_t)primary_msl->page_sz;
1197 len = page_sz * diff_len;
1199 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1203 for (i = 0; i < diff_len; i++) {
1204 struct rte_memseg *p_ms, *l_ms;
1205 int seg_idx = start + i;
1207 l_ms = rte_fbarray_get(l_arr, seg_idx);
1208 p_ms = rte_fbarray_get(p_arr, seg_idx);
1210 if (l_ms == NULL || p_ms == NULL)
1214 ret = alloc_seg(l_ms, p_ms->addr,
1215 p_ms->socket_id, hi,
1219 rte_fbarray_set_used(l_arr, seg_idx);
1221 ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1222 rte_fbarray_set_free(l_arr, seg_idx);
1228 /* if we just allocated memory, notify the application */
1230 struct rte_memseg *ms;
1232 size_t len, page_sz;
1234 ms = rte_fbarray_get(l_arr, start);
1235 start_va = ms->addr;
1236 page_sz = (size_t)primary_msl->page_sz;
1237 len = page_sz * diff_len;
1239 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1243 /* calculate how much we can advance until next chunk */
1245 rte_fbarray_find_contig_used(l_arr, start) :
1246 rte_fbarray_find_contig_free(l_arr, start);
1247 ret = RTE_MIN(chunk_len, diff_len);
1253 sync_status(struct rte_memseg_list *primary_msl,
1254 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1255 unsigned int msl_idx, bool used)
1257 struct rte_fbarray *l_arr, *p_arr;
1258 int p_idx, l_chunk_len, p_chunk_len, ret;
1261 /* this is a little bit tricky, but the basic idea is - walk both lists
1262 * and spot any places where there are discrepancies. walking both lists
1263 * and noting discrepancies in a single go is a hard problem, so we do
1264 * it in two passes - first we spot any places where allocated segments
1265 * mismatch (i.e. ensure that everything that's allocated in the primary
1266 * is also allocated in the secondary), and then we do it by looking at
1267 * free segments instead.
1269 * we also need to aggregate changes into chunks, as we have to call
1270 * callbacks per allocation, not per page.
1272 l_arr = &local_msl->memseg_arr;
1273 p_arr = &primary_msl->memseg_arr;
1276 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1278 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1280 while (p_idx >= 0) {
1281 int next_chunk_search_idx;
1284 p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1286 l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1289 p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1291 l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1294 /* best case scenario - no differences (or bigger, which will be
1295 * fixed during next iteration), look for next chunk
1297 if (l_chunk_len >= p_chunk_len) {
1298 next_chunk_search_idx = p_idx + p_chunk_len;
1302 /* if both chunks start at the same point, skip parts we know
1303 * are identical, and sync the rest. each call to sync_chunk
1304 * will only sync contiguous segments, so we need to call this
1305 * until we are sure there are no more differences in this
1308 start = p_idx + l_chunk_len;
1309 end = p_idx + p_chunk_len;
1311 ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1314 } while (start < end && ret >= 0);
1315 /* if ret is negative, something went wrong */
1319 next_chunk_search_idx = p_idx + p_chunk_len;
1321 /* skip to end of this chunk */
1323 p_idx = rte_fbarray_find_next_used(p_arr,
1324 next_chunk_search_idx);
1326 p_idx = rte_fbarray_find_next_free(p_arr,
1327 next_chunk_search_idx);
1334 sync_existing(struct rte_memseg_list *primary_msl,
1335 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1336 unsigned int msl_idx)
1340 /* do not allow any page allocations during the time we're allocating,
1341 * because file creation and locking operations are not atomic,
1342 * and we might be the first or the last ones to use a particular page,
1343 * so we need to ensure atomicity of every operation.
1345 dir_fd = open(hi->hugedir, O_RDONLY);
1347 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1348 hi->hugedir, strerror(errno));
1351 /* blocking writelock */
1352 if (flock(dir_fd, LOCK_EX)) {
1353 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1354 hi->hugedir, strerror(errno));
1359 /* ensure all allocated space is the same in both lists */
1360 ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1364 /* ensure all unallocated space is the same in both lists */
1365 ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1369 /* update version number */
1370 local_msl->version = primary_msl->version;
1381 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1383 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1384 struct rte_memseg_list *primary_msl, *local_msl;
1385 struct hugepage_info *hi = NULL;
1388 struct internal_config *internal_conf =
1389 eal_get_internal_configuration();
1394 msl_idx = msl - mcfg->memsegs;
1395 primary_msl = &mcfg->memsegs[msl_idx];
1396 local_msl = &local_memsegs[msl_idx];
1398 for (i = 0; i < RTE_DIM(internal_conf->hugepage_info); i++) {
1400 internal_conf->hugepage_info[i].hugepage_sz;
1401 uint64_t msl_sz = primary_msl->page_sz;
1402 if (msl_sz == cur_sz) {
1403 hi = &internal_conf->hugepage_info[i];
1408 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1412 /* if versions don't match, synchronize everything */
1413 if (local_msl->version != primary_msl->version &&
1414 sync_existing(primary_msl, local_msl, hi, msl_idx))
1421 eal_memalloc_sync_with_primary(void)
1423 /* nothing to be done in primary */
1424 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1427 /* memalloc is locked, so it's safe to call thread-unsafe version */
1428 if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1434 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1435 void *arg __rte_unused)
1437 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1438 struct rte_memseg_list *primary_msl, *local_msl;
1439 char name[PATH_MAX];
1445 msl_idx = msl - mcfg->memsegs;
1446 primary_msl = &mcfg->memsegs[msl_idx];
1447 local_msl = &local_memsegs[msl_idx];
1449 /* create distinct fbarrays for each secondary */
1450 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1451 primary_msl->memseg_arr.name, getpid());
1453 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1454 primary_msl->memseg_arr.len,
1455 primary_msl->memseg_arr.elt_sz);
1457 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1460 local_msl->base_va = primary_msl->base_va;
1461 local_msl->len = primary_msl->len;
1467 secondary_msl_destroy_walk(const struct rte_memseg_list *msl,
1468 void *arg __rte_unused)
1470 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1471 struct rte_memseg_list *local_msl;
1477 msl_idx = msl - mcfg->memsegs;
1478 local_msl = &local_memsegs[msl_idx];
1480 ret = rte_fbarray_destroy(&local_msl->memseg_arr);
1482 RTE_LOG(ERR, EAL, "Cannot destroy local memory map\n");
1485 local_msl->base_va = NULL;
1492 alloc_list(int list_idx, int len)
1496 const struct internal_config *internal_conf =
1497 eal_get_internal_configuration();
1499 /* single-file segments mode does not need fd list */
1500 if (!internal_conf->single_file_segments) {
1501 /* ensure we have space to store fd per each possible segment */
1502 data = malloc(sizeof(int) * len);
1504 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1507 /* set all fd's as invalid */
1508 for (i = 0; i < len; i++)
1510 fd_list[list_idx].fds = data;
1511 fd_list[list_idx].len = len;
1513 fd_list[list_idx].fds = NULL;
1514 fd_list[list_idx].len = 0;
1517 fd_list[list_idx].count = 0;
1518 fd_list[list_idx].memseg_list_fd = -1;
1524 destroy_list(int list_idx)
1526 const struct internal_config *internal_conf =
1527 eal_get_internal_configuration();
1529 /* single-file segments mode does not need fd list */
1530 if (!internal_conf->single_file_segments) {
1531 int *fds = fd_list[list_idx].fds;
1533 /* go through each fd and ensure it's closed */
1534 for (i = 0; i < fd_list[list_idx].len; i++) {
1541 fd_list[list_idx].fds = NULL;
1542 fd_list[list_idx].len = 0;
1543 } else if (fd_list[list_idx].memseg_list_fd >= 0) {
1544 close(fd_list[list_idx].memseg_list_fd);
1545 fd_list[list_idx].count = 0;
1546 fd_list[list_idx].memseg_list_fd = -1;
1552 fd_list_create_walk(const struct rte_memseg_list *msl,
1553 void *arg __rte_unused)
1555 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1562 msl_idx = msl - mcfg->memsegs;
1563 len = msl->memseg_arr.len;
1565 return alloc_list(msl_idx, len);
1569 fd_list_destroy_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1571 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1577 msl_idx = msl - mcfg->memsegs;
1579 return destroy_list(msl_idx);
1583 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1585 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1586 const struct internal_config *internal_conf =
1587 eal_get_internal_configuration();
1589 /* single file segments mode doesn't support individual segment fd's */
1590 if (internal_conf->single_file_segments)
1593 /* if list is not allocated, allocate it */
1594 if (fd_list[list_idx].len == 0) {
1595 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1597 if (alloc_list(list_idx, len) < 0)
1600 fd_list[list_idx].fds[seg_idx] = fd;
1606 eal_memalloc_set_seg_list_fd(int list_idx, int fd)
1608 const struct internal_config *internal_conf =
1609 eal_get_internal_configuration();
1611 /* non-single file segment mode doesn't support segment list fd's */
1612 if (!internal_conf->single_file_segments)
1615 fd_list[list_idx].memseg_list_fd = fd;
1621 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1624 const struct internal_config *internal_conf =
1625 eal_get_internal_configuration();
1627 if (internal_conf->in_memory || internal_conf->no_hugetlbfs) {
1628 #ifndef MEMFD_SUPPORTED
1629 /* in in-memory or no-huge mode, we rely on memfd support */
1632 /* memfd supported, but hugetlbfs memfd may not be */
1633 if (!internal_conf->no_hugetlbfs && !memfd_create_supported)
1637 if (internal_conf->single_file_segments) {
1638 fd = fd_list[list_idx].memseg_list_fd;
1639 } else if (fd_list[list_idx].len == 0) {
1640 /* list not initialized */
1643 fd = fd_list[list_idx].fds[seg_idx];
1651 test_memfd_create(void)
1653 #ifdef MEMFD_SUPPORTED
1654 const struct internal_config *internal_conf =
1655 eal_get_internal_configuration();
1657 for (i = 0; i < internal_conf->num_hugepage_sizes; i++) {
1658 uint64_t pagesz = internal_conf->hugepage_info[i].hugepage_sz;
1659 int pagesz_flag = pagesz_flags(pagesz);
1662 flags = pagesz_flag | RTE_MFD_HUGETLB;
1663 int fd = memfd_create("test", flags);
1665 /* we failed - let memalloc know this isn't working */
1666 if (errno == EINVAL) {
1667 memfd_create_supported = 0;
1668 return 0; /* not supported */
1671 /* we got other error - something's wrong */
1672 return -1; /* error */
1675 return 1; /* supported */
1678 return 0; /* not supported */
1682 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1684 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1685 const struct internal_config *internal_conf =
1686 eal_get_internal_configuration();
1688 if (internal_conf->in_memory || internal_conf->no_hugetlbfs) {
1689 #ifndef MEMFD_SUPPORTED
1690 /* in in-memory or no-huge mode, we rely on memfd support */
1693 /* memfd supported, but hugetlbfs memfd may not be */
1694 if (!internal_conf->no_hugetlbfs && !memfd_create_supported)
1698 if (internal_conf->single_file_segments) {
1699 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1701 /* segment not active? */
1702 if (fd_list[list_idx].memseg_list_fd < 0)
1704 *offset = pgsz * seg_idx;
1706 /* fd_list not initialized? */
1707 if (fd_list[list_idx].len == 0)
1710 /* segment not active? */
1711 if (fd_list[list_idx].fds[seg_idx] < 0)
1719 eal_memalloc_cleanup(void)
1721 /* close all remaining fd's - these are per-process, so it's safe */
1722 if (rte_memseg_list_walk_thread_unsafe(fd_list_destroy_walk, NULL))
1725 /* destroy the shadow page table if we're a secondary process */
1726 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1729 if (rte_memseg_list_walk_thread_unsafe(secondary_msl_destroy_walk,
1737 eal_memalloc_init(void)
1739 const struct internal_config *internal_conf =
1740 eal_get_internal_configuration();
1742 if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1743 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1745 if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1746 internal_conf->in_memory) {
1747 int mfd_res = test_memfd_create();
1750 RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1754 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1756 RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1758 /* we only support single-file segments mode with in-memory mode
1759 * if we support hugetlbfs with memfd_create. this code will
1762 if (internal_conf->single_file_segments &&
1764 RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1767 /* this cannot ever happen but better safe than sorry */
1768 if (!anonymous_hugepages_supported) {
1769 RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1772 /* safety net, should be impossible to configure */
1773 if (internal_conf->hugepage_file.unlink_before_mapping &&
1774 !internal_conf->hugepage_file.unlink_existing) {
1775 RTE_LOG(ERR, EAL, "Unlinking existing hugepage files is prohibited, cannot unlink them before mapping.\n");
1780 /* initialize all of the fd lists */
1781 if (rte_memseg_list_walk(fd_list_create_walk, NULL))