1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright(c) 2017-2018 Intel Corporation
5 #define _FILE_OFFSET_BITS 64
15 #include <sys/types.h>
17 #include <sys/queue.h>
22 #include <sys/ioctl.h>
26 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
27 #include <linux/memfd.h>
28 #define MEMFD_SUPPORTED
30 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
34 #include <linux/falloc.h>
35 #include <linux/mman.h> /* for hugetlb-related mmap flags */
37 #include <rte_common.h>
39 #include <rte_eal_memconfig.h>
41 #include <rte_errno.h>
42 #include <rte_memory.h>
43 #include <rte_spinlock.h>
45 #include "eal_filesystem.h"
46 #include "eal_internal_cfg.h"
47 #include "eal_memalloc.h"
48 #include "eal_private.h"
50 const int anonymous_hugepages_supported =
53 #define RTE_MAP_HUGE_SHIFT MAP_HUGE_SHIFT
56 #define RTE_MAP_HUGE_SHIFT 26
60 * we've already checked memfd support at compile-time, but we also need to
61 * check if we can create hugepage files with memfd.
63 * also, this is not a constant, because while we may be *compiled* with memfd
64 * hugetlbfs support, we might not be *running* on a system that supports memfd
65 * and/or memfd with hugetlbfs, so we need to be able to adjust this flag at
66 * runtime, and fall back to anonymous memory.
68 static int memfd_create_supported =
71 #define RTE_MFD_HUGETLB MFD_HUGETLB
74 #define RTE_MFD_HUGETLB 4U
78 * not all kernel version support fallocate on hugetlbfs, so fall back to
79 * ftruncate and disallow deallocation if fallocate is not supported.
81 static int fallocate_supported = -1; /* unknown */
84 * we have two modes - single file segments, and file-per-page mode.
86 * for single-file segments, we need some kind of mechanism to keep track of
87 * which hugepages can be freed back to the system, and which cannot. we cannot
88 * use flock() because they don't allow locking parts of a file, and we cannot
89 * use fcntl() due to issues with their semantics, so we will have to rely on a
90 * bunch of lockfiles for each page. so, we will use 'fds' array to keep track
91 * of per-page lockfiles. we will store the actual segment list fd in the
92 * 'memseg_list_fd' field.
94 * for file-per-page mode, each page will have its own fd, so 'memseg_list_fd'
95 * will be invalid (set to -1), and we'll use 'fds' to keep track of page fd's.
97 * we cannot know how many pages a system will have in advance, but we do know
98 * that they come in lists, and we know lengths of these lists. so, simply store
99 * a malloc'd array of fd's indexed by list and segment index.
101 * they will be initialized at startup, and filled as we allocate/deallocate
105 int *fds; /**< dynamically allocated array of segment lock fd's */
106 int memseg_list_fd; /**< memseg list fd */
107 int len; /**< total length of the array */
108 int count; /**< entries used in an array */
109 } fd_list[RTE_MAX_MEMSEG_LISTS];
111 /** local copy of a memory map, used to synchronize memory hotplug in MP */
112 static struct rte_memseg_list local_memsegs[RTE_MAX_MEMSEG_LISTS];
114 static sigjmp_buf huge_jmpenv;
116 static void __rte_unused huge_sigbus_handler(int signo __rte_unused)
118 siglongjmp(huge_jmpenv, 1);
121 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
122 * non-static local variable in the stack frame calling sigsetjmp might be
123 * clobbered by a call to longjmp.
125 static int __rte_unused huge_wrap_sigsetjmp(void)
127 return sigsetjmp(huge_jmpenv, 1);
130 static struct sigaction huge_action_old;
131 static int huge_need_recover;
133 static void __rte_unused
134 huge_register_sigbus(void)
137 struct sigaction action;
140 sigaddset(&mask, SIGBUS);
142 action.sa_mask = mask;
143 action.sa_handler = huge_sigbus_handler;
145 huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
148 static void __rte_unused
149 huge_recover_sigbus(void)
151 if (huge_need_recover) {
152 sigaction(SIGBUS, &huge_action_old, NULL);
153 huge_need_recover = 0;
157 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
162 /* Check if kernel supports NUMA. */
163 if (numa_available() != 0) {
164 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
171 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
173 RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
174 if (get_mempolicy(oldpolicy, oldmask->maskp,
175 oldmask->size + 1, 0, 0) < 0) {
177 "Failed to get current mempolicy: %s. "
178 "Assuming MPOL_DEFAULT.\n", strerror(errno));
179 *oldpolicy = MPOL_DEFAULT;
182 "Setting policy MPOL_PREFERRED for socket %d\n",
184 numa_set_preferred(socket_id);
188 restore_numa(int *oldpolicy, struct bitmask *oldmask)
191 "Restoring previous memory policy: %d\n", *oldpolicy);
192 if (*oldpolicy == MPOL_DEFAULT) {
193 numa_set_localalloc();
194 } else if (set_mempolicy(*oldpolicy, oldmask->maskp,
195 oldmask->size + 1) < 0) {
196 RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
198 numa_set_localalloc();
200 numa_free_cpumask(oldmask);
205 * uses fstat to report the size of a file on disk
208 get_file_size(int fd)
211 if (fstat(fd, &st) < 0)
217 pagesz_flags(uint64_t page_sz)
219 /* as per mmap() manpage, all page sizes are log2 of page size
220 * shifted by MAP_HUGE_SHIFT
222 int log2 = rte_log2_u64(page_sz);
223 return log2 << RTE_MAP_HUGE_SHIFT;
226 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
227 static int lock(int fd, int type)
231 /* flock may be interrupted */
233 ret = flock(fd, type | LOCK_NB);
234 } while (ret && errno == EINTR);
236 if (ret && errno == EWOULDBLOCK) {
240 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
241 __func__, strerror(errno));
244 /* lock was successful */
248 static int get_segment_lock_fd(int list_idx, int seg_idx)
250 char path[PATH_MAX] = {0};
253 if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
255 if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
258 fd = fd_list[list_idx].fds[seg_idx];
259 /* does this lock already exist? */
263 eal_get_hugefile_lock_path(path, sizeof(path),
264 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
266 fd = open(path, O_CREAT | O_RDWR, 0660);
268 RTE_LOG(ERR, EAL, "%s(): error creating lockfile '%s': %s\n",
269 __func__, path, strerror(errno));
272 /* take out a read lock */
273 if (lock(fd, LOCK_SH) != 1) {
274 RTE_LOG(ERR, EAL, "%s(): failed to take out a readlock on '%s': %s\n",
275 __func__, path, strerror(errno));
279 /* store it for future reference */
280 fd_list[list_idx].fds[seg_idx] = fd;
281 fd_list[list_idx].count++;
285 static int unlock_segment(int list_idx, int seg_idx)
289 if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
291 if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
294 fd = fd_list[list_idx].fds[seg_idx];
296 /* upgrade lock to exclusive to see if we can remove the lockfile */
297 ret = lock(fd, LOCK_EX);
299 /* we've succeeded in taking exclusive lock, this lockfile may
302 char path[PATH_MAX] = {0};
303 eal_get_hugefile_lock_path(path, sizeof(path),
304 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
306 RTE_LOG(ERR, EAL, "%s(): error removing lockfile '%s': %s\n",
307 __func__, path, strerror(errno));
310 /* we don't want to leak the fd, so even if we fail to lock, close fd
311 * and remove it from list anyway.
314 fd_list[list_idx].fds[seg_idx] = -1;
315 fd_list[list_idx].count--;
323 get_seg_memfd(struct hugepage_info *hi __rte_unused,
324 unsigned int list_idx __rte_unused,
325 unsigned int seg_idx __rte_unused)
327 #ifdef MEMFD_SUPPORTED
329 char segname[250]; /* as per manpage, limit is 249 bytes plus null */
331 int flags = RTE_MFD_HUGETLB | pagesz_flags(hi->hugepage_sz);
333 if (internal_config.single_file_segments) {
334 fd = fd_list[list_idx].memseg_list_fd;
337 snprintf(segname, sizeof(segname), "seg_%i", list_idx);
338 fd = memfd_create(segname, flags);
340 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
341 __func__, strerror(errno));
344 fd_list[list_idx].memseg_list_fd = fd;
347 fd = fd_list[list_idx].fds[seg_idx];
350 snprintf(segname, sizeof(segname), "seg_%i-%i",
352 fd = memfd_create(segname, flags);
354 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
355 __func__, strerror(errno));
358 fd_list[list_idx].fds[seg_idx] = fd;
367 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
368 unsigned int list_idx, unsigned int seg_idx)
372 /* for in-memory mode, we only make it here when we're sure we support
373 * memfd, and this is a special case.
375 if (internal_config.in_memory)
376 return get_seg_memfd(hi, list_idx, seg_idx);
378 if (internal_config.single_file_segments) {
379 /* create a hugepage file path */
380 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
382 fd = fd_list[list_idx].memseg_list_fd;
385 fd = open(path, O_CREAT | O_RDWR, 0600);
387 RTE_LOG(ERR, EAL, "%s(): open failed: %s\n",
388 __func__, strerror(errno));
391 /* take out a read lock and keep it indefinitely */
392 if (lock(fd, LOCK_SH) < 0) {
393 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
394 __func__, strerror(errno));
398 fd_list[list_idx].memseg_list_fd = fd;
401 /* create a hugepage file path */
402 eal_get_hugefile_path(path, buflen, hi->hugedir,
403 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
405 fd = fd_list[list_idx].fds[seg_idx];
408 fd = open(path, O_CREAT | O_RDWR, 0600);
410 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
411 __func__, strerror(errno));
414 /* take out a read lock */
415 if (lock(fd, LOCK_SH) < 0) {
416 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
417 __func__, strerror(errno));
421 fd_list[list_idx].fds[seg_idx] = fd;
428 resize_hugefile_in_memory(int fd, int list_idx, uint64_t fa_offset,
429 uint64_t page_sz, bool grow)
431 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
435 /* grow or shrink the file */
436 ret = fallocate(fd, flags, fa_offset, page_sz);
439 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
444 /* increase/decrease total segment count */
445 fd_list[list_idx].count += (grow ? 1 : -1);
446 if (!grow && fd_list[list_idx].count == 0) {
447 close(fd_list[list_idx].memseg_list_fd);
448 fd_list[list_idx].memseg_list_fd = -1;
454 resize_hugefile_in_filesystem(int fd, char *path, int list_idx, int seg_idx,
455 uint64_t fa_offset, uint64_t page_sz, bool grow)
460 if (fallocate_supported == 0) {
461 /* we cannot deallocate memory if fallocate() is not
462 * supported, and hugepage file is already locked at
463 * creation, so no further synchronization needed.
467 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
471 uint64_t new_size = fa_offset + page_sz;
472 uint64_t cur_size = get_file_size(fd);
474 /* fallocate isn't supported, fall back to ftruncate */
475 if (new_size > cur_size &&
476 ftruncate(fd, new_size) < 0) {
477 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
478 __func__, strerror(errno));
482 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
486 /* if fallocate() is supported, we need to take out a
487 * read lock on allocate (to prevent other processes
488 * from deallocating this page), and take out a write
489 * lock on deallocate (to ensure nobody else is using
492 * read locks on page itself are already taken out at
493 * file creation, in get_seg_fd().
495 * we cannot rely on simple use of flock() call, because
496 * we need to be able to lock a section of the file,
497 * and we cannot use fcntl() locks, because of numerous
498 * problems with their semantics, so we will use
499 * deterministically named lock files for each section
502 * if we're shrinking the file, we want to upgrade our
503 * lock from shared to exclusive.
505 * lock_fd is an fd for a lockfile, not for the segment
508 lock_fd = get_segment_lock_fd(list_idx, seg_idx);
511 /* we are using this lockfile to determine
512 * whether this particular page is locked, as we
513 * are in single file segments mode and thus
514 * cannot use regular flock() to get this info.
516 * we want to try and take out an exclusive lock
517 * on the lock file to determine if we're the
518 * last ones using this page, and if not, we
519 * won't be shrinking it, and will instead exit
522 ret = lock(lock_fd, LOCK_EX);
524 /* drop the lock on the lockfile, so that even
525 * if we couldn't shrink the file ourselves, we
526 * are signalling to other processes that we're
527 * no longer using this page.
529 if (unlock_segment(list_idx, seg_idx))
530 RTE_LOG(ERR, EAL, "Could not unlock segment\n");
532 /* additionally, if this was the last lock on
533 * this segment list, we can safely close the
534 * page file fd, so that one of the processes
535 * could then delete the file after shrinking.
537 if (ret < 1 && fd_list[list_idx].count == 0) {
539 fd_list[list_idx].memseg_list_fd = -1;
543 RTE_LOG(ERR, EAL, "Could not lock segment\n");
547 /* failed to lock, not an error. */
551 /* grow or shrink the file */
552 ret = fallocate(fd, flags, fa_offset, page_sz);
555 if (fallocate_supported == -1 &&
557 RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
560 fallocate_supported = 0;
562 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
568 fallocate_supported = 1;
570 /* we've grew/shrunk the file, and we hold an
571 * exclusive lock now. check if there are no
572 * more segments active in this segment list,
573 * and remove the file if there aren't.
575 if (fd_list[list_idx].count == 0) {
577 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
581 fd_list[list_idx].memseg_list_fd = -1;
592 resize_hugefile(int fd, char *path, int list_idx, int seg_idx,
593 uint64_t fa_offset, uint64_t page_sz, bool grow)
596 /* in-memory mode is a special case, because we don't need to perform
597 * any locking, and we can be sure that fallocate() is supported.
599 if (internal_config.in_memory)
600 return resize_hugefile_in_memory(fd, list_idx, fa_offset,
603 return resize_hugefile_in_filesystem(fd, path, list_idx, seg_idx,
604 fa_offset, page_sz, grow);
608 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
609 struct hugepage_info *hi, unsigned int list_idx,
610 unsigned int seg_idx)
612 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
613 int cur_socket_id = 0;
625 alloc_sz = hi->hugepage_sz;
627 /* these are checked at init, but code analyzers don't know that */
628 if (internal_config.in_memory && !anonymous_hugepages_supported) {
629 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
632 if (internal_config.in_memory && !memfd_create_supported &&
633 internal_config.single_file_segments) {
634 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
638 /* in-memory without memfd is a special case */
641 if (internal_config.in_memory && !memfd_create_supported) {
642 const int in_memory_flags = MAP_HUGETLB | MAP_FIXED |
643 MAP_PRIVATE | MAP_ANONYMOUS;
646 pagesz_flag = pagesz_flags(alloc_sz);
648 mmap_flags = in_memory_flags | pagesz_flag;
650 /* single-file segments codepath will never be active
651 * here because in-memory mode is incompatible with the
652 * fallback path, and it's stopped at EAL initialization
657 /* takes out a read lock on segment or segment list */
658 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
660 RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
664 if (internal_config.single_file_segments) {
665 map_offset = seg_idx * alloc_sz;
666 ret = resize_hugefile(fd, path, list_idx, seg_idx,
667 map_offset, alloc_sz, true);
672 if (ftruncate(fd, alloc_sz) < 0) {
673 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
674 __func__, strerror(errno));
677 if (internal_config.hugepage_unlink &&
678 !internal_config.in_memory) {
680 RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
681 __func__, strerror(errno));
686 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
690 * map the segment, and populate page tables, the kernel fills
691 * this segment with zeros if it's a new page.
693 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
696 if (va == MAP_FAILED) {
697 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
699 /* mmap failed, but the previous region might have been
700 * unmapped anyway. try to remap it
705 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
706 munmap(va, alloc_sz);
710 /* In linux, hugetlb limitations, like cgroup, are
711 * enforced at fault time instead of mmap(), even
712 * with the option of MAP_POPULATE. Kernel will send
713 * a SIGBUS signal. To avoid to be killed, save stack
714 * environment here, if SIGBUS happens, we can jump
717 if (huge_wrap_sigsetjmp()) {
718 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
719 (unsigned int)(alloc_sz >> 20));
723 /* we need to trigger a write to the page to enforce page fault and
724 * ensure that page is accessible to us, but we can't overwrite value
725 * that is already there, so read the old value, and write itback.
726 * kernel populates the page with zeroes initially.
728 *(volatile int *)addr = *(volatile int *)addr;
730 iova = rte_mem_virt2iova(addr);
731 if (iova == RTE_BAD_PHYS_ADDR) {
732 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
737 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
738 move_pages(getpid(), 1, &addr, NULL, &cur_socket_id, 0);
740 if (cur_socket_id != socket_id) {
742 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
743 __func__, socket_id, cur_socket_id);
747 if (rte_socket_count() > 1)
748 RTE_LOG(DEBUG, EAL, "%s(): not checking hugepage NUMA node.\n",
753 ms->hugepage_sz = alloc_sz;
755 ms->nchannel = rte_memory_get_nchannel();
756 ms->nrank = rte_memory_get_nrank();
758 ms->socket_id = socket_id;
763 munmap(addr, alloc_sz);
766 new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
767 if (new_addr != addr) {
768 if (new_addr != NULL)
769 munmap(new_addr, alloc_sz);
770 /* we're leaving a hole in our virtual address space. if
771 * somebody else maps this hole now, we could accidentally
772 * override it in the future.
774 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
777 /* some codepaths will return negative fd, so exit early */
781 if (internal_config.single_file_segments) {
782 resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
784 /* ignore failure, can't make it any worse */
786 /* only remove file if we can take out a write lock */
787 if (internal_config.hugepage_unlink == 0 &&
788 internal_config.in_memory == 0 &&
789 lock(fd, LOCK_EX) == 1)
792 fd_list[list_idx].fds[seg_idx] = -1;
798 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
799 unsigned int list_idx, unsigned int seg_idx)
806 /* erase page data */
807 memset(ms->addr, 0, ms->len);
809 if (mmap(ms->addr, ms->len, PROT_READ,
810 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
812 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
818 /* if we're using anonymous hugepages, nothing to be done */
819 if (internal_config.in_memory && !memfd_create_supported)
822 /* if we've already unlinked the page, nothing needs to be done */
823 if (!internal_config.in_memory && internal_config.hugepage_unlink)
827 memset(ms, 0, sizeof(*ms));
831 /* if we are not in single file segments mode, we're going to unmap the
832 * segment and thus drop the lock on original fd, but hugepage dir is
833 * now locked so we can take out another one without races.
835 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
839 if (internal_config.single_file_segments) {
840 map_offset = seg_idx * ms->len;
841 if (resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
846 /* if we're able to take out a write lock, we're the last one
847 * holding onto this page.
849 if (!internal_config.in_memory) {
850 ret = lock(fd, LOCK_EX);
852 /* no one else is using this page */
857 /* closing fd will drop the lock */
859 fd_list[list_idx].fds[seg_idx] = -1;
862 memset(ms, 0, sizeof(*ms));
864 return ret < 0 ? -1 : 0;
867 struct alloc_walk_param {
868 struct hugepage_info *hi;
869 struct rte_memseg **ms;
871 unsigned int segs_allocated;
877 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
879 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
880 struct alloc_walk_param *wa = arg;
881 struct rte_memseg_list *cur_msl;
883 int cur_idx, start_idx, j, dir_fd = -1;
884 unsigned int msl_idx, need, i;
886 if (msl->page_sz != wa->page_sz)
888 if (msl->socket_id != wa->socket)
891 page_sz = (size_t)msl->page_sz;
893 msl_idx = msl - mcfg->memsegs;
894 cur_msl = &mcfg->memsegs[msl_idx];
898 /* try finding space in memseg list */
900 /* if we require exact number of pages in a list, find them */
901 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0,
909 /* we don't require exact number of pages, so we're going to go
910 * for best-effort allocation. that means finding the biggest
911 * unused block, and going with that.
913 cur_idx = rte_fbarray_find_biggest_free(&cur_msl->memseg_arr,
918 /* adjust the size to possibly be smaller than original
919 * request, but do not allow it to be bigger.
921 cur_len = rte_fbarray_find_contig_free(&cur_msl->memseg_arr,
923 need = RTE_MIN(need, (unsigned int)cur_len);
926 /* do not allow any page allocations during the time we're allocating,
927 * because file creation and locking operations are not atomic,
928 * and we might be the first or the last ones to use a particular page,
929 * so we need to ensure atomicity of every operation.
931 * during init, we already hold a write lock, so don't try to take out
934 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
935 dir_fd = open(wa->hi->hugedir, O_RDONLY);
937 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
938 __func__, wa->hi->hugedir, strerror(errno));
941 /* blocking writelock */
942 if (flock(dir_fd, LOCK_EX)) {
943 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
944 __func__, wa->hi->hugedir, strerror(errno));
950 for (i = 0; i < need; i++, cur_idx++) {
951 struct rte_memseg *cur;
954 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
955 map_addr = RTE_PTR_ADD(cur_msl->base_va,
958 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
960 RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
963 /* if exact number wasn't requested, stop */
968 for (j = start_idx; j < cur_idx; j++) {
969 struct rte_memseg *tmp;
970 struct rte_fbarray *arr =
971 &cur_msl->memseg_arr;
973 tmp = rte_fbarray_get(arr, j);
974 rte_fbarray_set_free(arr, j);
976 /* free_seg may attempt to create a file, which
979 if (free_seg(tmp, wa->hi, msl_idx, j))
980 RTE_LOG(DEBUG, EAL, "Cannot free page\n");
984 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
993 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
996 wa->segs_allocated = i;
1001 /* if we didn't allocate any segments, move on to the next list */
1005 struct free_walk_param {
1006 struct hugepage_info *hi;
1007 struct rte_memseg *ms;
1010 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
1012 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1013 struct rte_memseg_list *found_msl;
1014 struct free_walk_param *wa = arg;
1015 uintptr_t start_addr, end_addr;
1016 int msl_idx, seg_idx, ret, dir_fd = -1;
1018 start_addr = (uintptr_t) msl->base_va;
1019 end_addr = start_addr + msl->len;
1021 if ((uintptr_t)wa->ms->addr < start_addr ||
1022 (uintptr_t)wa->ms->addr >= end_addr)
1025 msl_idx = msl - mcfg->memsegs;
1026 seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
1029 found_msl = &mcfg->memsegs[msl_idx];
1031 /* do not allow any page allocations during the time we're freeing,
1032 * because file creation and locking operations are not atomic,
1033 * and we might be the first or the last ones to use a particular page,
1034 * so we need to ensure atomicity of every operation.
1036 * during init, we already hold a write lock, so don't try to take out
1039 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
1040 dir_fd = open(wa->hi->hugedir, O_RDONLY);
1042 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
1043 __func__, wa->hi->hugedir, strerror(errno));
1046 /* blocking writelock */
1047 if (flock(dir_fd, LOCK_EX)) {
1048 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
1049 __func__, wa->hi->hugedir, strerror(errno));
1055 found_msl->version++;
1057 rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
1059 ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
1071 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
1072 int socket, bool exact)
1075 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1076 bool have_numa = false;
1078 struct bitmask *oldmask;
1080 struct alloc_walk_param wa;
1081 struct hugepage_info *hi = NULL;
1083 memset(&wa, 0, sizeof(wa));
1085 /* dynamic allocation not supported in legacy mode */
1086 if (internal_config.legacy_mem)
1089 for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
1091 internal_config.hugepage_info[i].hugepage_sz) {
1092 hi = &internal_config.hugepage_info[i];
1097 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
1102 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1104 oldmask = numa_allocate_nodemask();
1105 prepare_numa(&oldpolicy, oldmask, socket);
1114 wa.page_sz = page_sz;
1116 wa.segs_allocated = 0;
1118 /* memalloc is locked, so it's safe to use thread-unsafe version */
1119 ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1121 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1124 } else if (ret > 0) {
1125 ret = (int)wa.segs_allocated;
1128 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1130 restore_numa(&oldpolicy, oldmask);
1136 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1138 struct rte_memseg *ms;
1139 if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1141 /* return pointer to newly allocated memseg */
1146 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1150 /* dynamic free not supported in legacy mode */
1151 if (internal_config.legacy_mem)
1154 for (seg = 0; seg < n_segs; seg++) {
1155 struct rte_memseg *cur = ms[seg];
1156 struct hugepage_info *hi = NULL;
1157 struct free_walk_param wa;
1160 /* if this page is marked as unfreeable, fail */
1161 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1162 RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1167 memset(&wa, 0, sizeof(wa));
1169 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
1171 hi = &internal_config.hugepage_info[i];
1172 if (cur->hugepage_sz == hi->hugepage_sz)
1175 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1176 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1184 /* memalloc is locked, so it's safe to use thread-unsafe version
1186 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1191 RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1198 eal_memalloc_free_seg(struct rte_memseg *ms)
1200 /* dynamic free not supported in legacy mode */
1201 if (internal_config.legacy_mem)
1204 return eal_memalloc_free_seg_bulk(&ms, 1);
1208 sync_chunk(struct rte_memseg_list *primary_msl,
1209 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1210 unsigned int msl_idx, bool used, int start, int end)
1212 struct rte_fbarray *l_arr, *p_arr;
1213 int i, ret, chunk_len, diff_len;
1215 l_arr = &local_msl->memseg_arr;
1216 p_arr = &primary_msl->memseg_arr;
1218 /* we need to aggregate allocations/deallocations into bigger chunks,
1219 * as we don't want to spam the user with per-page callbacks.
1221 * to avoid any potential issues, we also want to trigger
1222 * deallocation callbacks *before* we actually deallocate
1223 * memory, so that the user application could wrap up its use
1224 * before it goes away.
1227 chunk_len = end - start;
1229 /* find how many contiguous pages we can map/unmap for this chunk */
1231 rte_fbarray_find_contig_free(l_arr, start) :
1232 rte_fbarray_find_contig_used(l_arr, start);
1234 /* has to be at least one page */
1238 diff_len = RTE_MIN(chunk_len, diff_len);
1240 /* if we are freeing memory, notify the application */
1242 struct rte_memseg *ms;
1244 size_t len, page_sz;
1246 ms = rte_fbarray_get(l_arr, start);
1247 start_va = ms->addr;
1248 page_sz = (size_t)primary_msl->page_sz;
1249 len = page_sz * diff_len;
1251 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1255 for (i = 0; i < diff_len; i++) {
1256 struct rte_memseg *p_ms, *l_ms;
1257 int seg_idx = start + i;
1259 l_ms = rte_fbarray_get(l_arr, seg_idx);
1260 p_ms = rte_fbarray_get(p_arr, seg_idx);
1262 if (l_ms == NULL || p_ms == NULL)
1266 ret = alloc_seg(l_ms, p_ms->addr,
1267 p_ms->socket_id, hi,
1271 rte_fbarray_set_used(l_arr, seg_idx);
1273 ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1274 rte_fbarray_set_free(l_arr, seg_idx);
1280 /* if we just allocated memory, notify the application */
1282 struct rte_memseg *ms;
1284 size_t len, page_sz;
1286 ms = rte_fbarray_get(l_arr, start);
1287 start_va = ms->addr;
1288 page_sz = (size_t)primary_msl->page_sz;
1289 len = page_sz * diff_len;
1291 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1295 /* calculate how much we can advance until next chunk */
1297 rte_fbarray_find_contig_used(l_arr, start) :
1298 rte_fbarray_find_contig_free(l_arr, start);
1299 ret = RTE_MIN(chunk_len, diff_len);
1305 sync_status(struct rte_memseg_list *primary_msl,
1306 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1307 unsigned int msl_idx, bool used)
1309 struct rte_fbarray *l_arr, *p_arr;
1310 int p_idx, l_chunk_len, p_chunk_len, ret;
1313 /* this is a little bit tricky, but the basic idea is - walk both lists
1314 * and spot any places where there are discrepancies. walking both lists
1315 * and noting discrepancies in a single go is a hard problem, so we do
1316 * it in two passes - first we spot any places where allocated segments
1317 * mismatch (i.e. ensure that everything that's allocated in the primary
1318 * is also allocated in the secondary), and then we do it by looking at
1319 * free segments instead.
1321 * we also need to aggregate changes into chunks, as we have to call
1322 * callbacks per allocation, not per page.
1324 l_arr = &local_msl->memseg_arr;
1325 p_arr = &primary_msl->memseg_arr;
1328 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1330 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1332 while (p_idx >= 0) {
1333 int next_chunk_search_idx;
1336 p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1338 l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1341 p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1343 l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1346 /* best case scenario - no differences (or bigger, which will be
1347 * fixed during next iteration), look for next chunk
1349 if (l_chunk_len >= p_chunk_len) {
1350 next_chunk_search_idx = p_idx + p_chunk_len;
1354 /* if both chunks start at the same point, skip parts we know
1355 * are identical, and sync the rest. each call to sync_chunk
1356 * will only sync contiguous segments, so we need to call this
1357 * until we are sure there are no more differences in this
1360 start = p_idx + l_chunk_len;
1361 end = p_idx + p_chunk_len;
1363 ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1366 } while (start < end && ret >= 0);
1367 /* if ret is negative, something went wrong */
1371 next_chunk_search_idx = p_idx + p_chunk_len;
1373 /* skip to end of this chunk */
1375 p_idx = rte_fbarray_find_next_used(p_arr,
1376 next_chunk_search_idx);
1378 p_idx = rte_fbarray_find_next_free(p_arr,
1379 next_chunk_search_idx);
1386 sync_existing(struct rte_memseg_list *primary_msl,
1387 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1388 unsigned int msl_idx)
1392 /* do not allow any page allocations during the time we're allocating,
1393 * because file creation and locking operations are not atomic,
1394 * and we might be the first or the last ones to use a particular page,
1395 * so we need to ensure atomicity of every operation.
1397 dir_fd = open(hi->hugedir, O_RDONLY);
1399 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1400 hi->hugedir, strerror(errno));
1403 /* blocking writelock */
1404 if (flock(dir_fd, LOCK_EX)) {
1405 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1406 hi->hugedir, strerror(errno));
1411 /* ensure all allocated space is the same in both lists */
1412 ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1416 /* ensure all unallocated space is the same in both lists */
1417 ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1421 /* update version number */
1422 local_msl->version = primary_msl->version;
1433 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1435 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1436 struct rte_memseg_list *primary_msl, *local_msl;
1437 struct hugepage_info *hi = NULL;
1444 msl_idx = msl - mcfg->memsegs;
1445 primary_msl = &mcfg->memsegs[msl_idx];
1446 local_msl = &local_memsegs[msl_idx];
1448 for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1450 internal_config.hugepage_info[i].hugepage_sz;
1451 uint64_t msl_sz = primary_msl->page_sz;
1452 if (msl_sz == cur_sz) {
1453 hi = &internal_config.hugepage_info[i];
1458 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1462 /* if versions don't match, synchronize everything */
1463 if (local_msl->version != primary_msl->version &&
1464 sync_existing(primary_msl, local_msl, hi, msl_idx))
1471 eal_memalloc_sync_with_primary(void)
1473 /* nothing to be done in primary */
1474 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1477 /* memalloc is locked, so it's safe to call thread-unsafe version */
1478 if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1484 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1485 void *arg __rte_unused)
1487 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1488 struct rte_memseg_list *primary_msl, *local_msl;
1489 char name[PATH_MAX];
1495 msl_idx = msl - mcfg->memsegs;
1496 primary_msl = &mcfg->memsegs[msl_idx];
1497 local_msl = &local_memsegs[msl_idx];
1499 /* create distinct fbarrays for each secondary */
1500 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1501 primary_msl->memseg_arr.name, getpid());
1503 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1504 primary_msl->memseg_arr.len,
1505 primary_msl->memseg_arr.elt_sz);
1507 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1510 local_msl->base_va = primary_msl->base_va;
1511 local_msl->len = primary_msl->len;
1517 alloc_list(int list_idx, int len)
1522 /* ensure we have space to store fd per each possible segment */
1523 data = malloc(sizeof(int) * len);
1525 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1528 /* set all fd's as invalid */
1529 for (i = 0; i < len; i++)
1532 fd_list[list_idx].fds = data;
1533 fd_list[list_idx].len = len;
1534 fd_list[list_idx].count = 0;
1535 fd_list[list_idx].memseg_list_fd = -1;
1541 fd_list_create_walk(const struct rte_memseg_list *msl,
1542 void *arg __rte_unused)
1544 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1551 msl_idx = msl - mcfg->memsegs;
1552 len = msl->memseg_arr.len;
1554 return alloc_list(msl_idx, len);
1558 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1560 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1562 /* single file segments mode doesn't support individual segment fd's */
1563 if (internal_config.single_file_segments)
1566 /* if list is not allocated, allocate it */
1567 if (fd_list[list_idx].len == 0) {
1568 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1570 if (alloc_list(list_idx, len) < 0)
1573 fd_list[list_idx].fds[seg_idx] = fd;
1579 eal_memalloc_set_seg_list_fd(int list_idx, int fd)
1581 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1583 /* non-single file segment mode doesn't support segment list fd's */
1584 if (!internal_config.single_file_segments)
1587 /* if list is not allocated, allocate it */
1588 if (fd_list[list_idx].len == 0) {
1589 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1591 if (alloc_list(list_idx, len) < 0)
1595 fd_list[list_idx].memseg_list_fd = fd;
1601 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1605 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1606 #ifndef MEMFD_SUPPORTED
1607 /* in in-memory or no-huge mode, we rely on memfd support */
1610 /* memfd supported, but hugetlbfs memfd may not be */
1611 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1615 if (internal_config.single_file_segments) {
1616 fd = fd_list[list_idx].memseg_list_fd;
1617 } else if (fd_list[list_idx].len == 0) {
1618 /* list not initialized */
1621 fd = fd_list[list_idx].fds[seg_idx];
1629 test_memfd_create(void)
1631 #ifdef MEMFD_SUPPORTED
1633 for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1634 uint64_t pagesz = internal_config.hugepage_info[i].hugepage_sz;
1635 int pagesz_flag = pagesz_flags(pagesz);
1638 flags = pagesz_flag | RTE_MFD_HUGETLB;
1639 int fd = memfd_create("test", flags);
1641 /* we failed - let memalloc know this isn't working */
1642 if (errno == EINVAL) {
1643 memfd_create_supported = 0;
1644 return 0; /* not supported */
1647 /* we got other error - something's wrong */
1648 return -1; /* error */
1651 return 1; /* supported */
1654 return 0; /* not supported */
1658 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1660 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1662 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1663 #ifndef MEMFD_SUPPORTED
1664 /* in in-memory or no-huge mode, we rely on memfd support */
1667 /* memfd supported, but hugetlbfs memfd may not be */
1668 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1672 /* fd_list not initialized? */
1673 if (fd_list[list_idx].len == 0)
1675 if (internal_config.single_file_segments) {
1676 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1678 /* segment not active? */
1679 if (fd_list[list_idx].memseg_list_fd < 0)
1681 *offset = pgsz * seg_idx;
1683 /* segment not active? */
1684 if (fd_list[list_idx].fds[seg_idx] < 0)
1692 eal_memalloc_init(void)
1694 if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1695 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1697 if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1698 internal_config.in_memory) {
1699 int mfd_res = test_memfd_create();
1702 RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1706 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1708 RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1710 /* we only support single-file segments mode with in-memory mode
1711 * if we support hugetlbfs with memfd_create. this code will
1714 if (internal_config.single_file_segments &&
1716 RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1719 /* this cannot ever happen but better safe than sorry */
1720 if (!anonymous_hugepages_supported) {
1721 RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1726 /* initialize all of the fd lists */
1727 if (rte_memseg_list_walk(fd_list_create_walk, NULL))