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)
216 static inline uint32_t
219 return (uint32_t)__builtin_ctzll(v);
222 static inline uint32_t
227 v = rte_align64pow2(v);
232 pagesz_flags(uint64_t page_sz)
234 /* as per mmap() manpage, all page sizes are log2 of page size
235 * shifted by MAP_HUGE_SHIFT
237 int log2 = log2_u64(page_sz);
238 return log2 << RTE_MAP_HUGE_SHIFT;
241 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
242 static int lock(int fd, int type)
246 /* flock may be interrupted */
248 ret = flock(fd, type | LOCK_NB);
249 } while (ret && errno == EINTR);
251 if (ret && errno == EWOULDBLOCK) {
255 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
256 __func__, strerror(errno));
259 /* lock was successful */
263 static int get_segment_lock_fd(int list_idx, int seg_idx)
265 char path[PATH_MAX] = {0};
268 if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
270 if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
273 fd = fd_list[list_idx].fds[seg_idx];
274 /* does this lock already exist? */
278 eal_get_hugefile_lock_path(path, sizeof(path),
279 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
281 fd = open(path, O_CREAT | O_RDWR, 0660);
283 RTE_LOG(ERR, EAL, "%s(): error creating lockfile '%s': %s\n",
284 __func__, path, strerror(errno));
287 /* take out a read lock */
288 if (lock(fd, LOCK_SH) != 1) {
289 RTE_LOG(ERR, EAL, "%s(): failed to take out a readlock on '%s': %s\n",
290 __func__, path, strerror(errno));
294 /* store it for future reference */
295 fd_list[list_idx].fds[seg_idx] = fd;
296 fd_list[list_idx].count++;
300 static int unlock_segment(int list_idx, int seg_idx)
304 if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
306 if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
309 fd = fd_list[list_idx].fds[seg_idx];
311 /* upgrade lock to exclusive to see if we can remove the lockfile */
312 ret = lock(fd, LOCK_EX);
314 /* we've succeeded in taking exclusive lock, this lockfile may
317 char path[PATH_MAX] = {0};
318 eal_get_hugefile_lock_path(path, sizeof(path),
319 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
321 RTE_LOG(ERR, EAL, "%s(): error removing lockfile '%s': %s\n",
322 __func__, path, strerror(errno));
325 /* we don't want to leak the fd, so even if we fail to lock, close fd
326 * and remove it from list anyway.
329 fd_list[list_idx].fds[seg_idx] = -1;
330 fd_list[list_idx].count--;
338 get_seg_memfd(struct hugepage_info *hi __rte_unused,
339 unsigned int list_idx __rte_unused,
340 unsigned int seg_idx __rte_unused)
342 #ifdef MEMFD_SUPPORTED
344 char segname[250]; /* as per manpage, limit is 249 bytes plus null */
346 int flags = RTE_MFD_HUGETLB | pagesz_flags(hi->hugepage_sz);
348 if (internal_config.single_file_segments) {
349 fd = fd_list[list_idx].memseg_list_fd;
352 snprintf(segname, sizeof(segname), "seg_%i", list_idx);
353 fd = memfd_create(segname, flags);
355 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
356 __func__, strerror(errno));
359 fd_list[list_idx].memseg_list_fd = fd;
362 fd = fd_list[list_idx].fds[seg_idx];
365 snprintf(segname, sizeof(segname), "seg_%i-%i",
367 fd = memfd_create(segname, flags);
369 RTE_LOG(DEBUG, EAL, "%s(): memfd create failed: %s\n",
370 __func__, strerror(errno));
373 fd_list[list_idx].fds[seg_idx] = fd;
382 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
383 unsigned int list_idx, unsigned int seg_idx)
387 /* for in-memory mode, we only make it here when we're sure we support
388 * memfd, and this is a special case.
390 if (internal_config.in_memory)
391 return get_seg_memfd(hi, list_idx, seg_idx);
393 if (internal_config.single_file_segments) {
394 /* create a hugepage file path */
395 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
397 fd = fd_list[list_idx].memseg_list_fd;
400 fd = open(path, O_CREAT | O_RDWR, 0600);
402 RTE_LOG(ERR, EAL, "%s(): open failed: %s\n",
403 __func__, strerror(errno));
406 /* take out a read lock and keep it indefinitely */
407 if (lock(fd, LOCK_SH) < 0) {
408 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
409 __func__, strerror(errno));
413 fd_list[list_idx].memseg_list_fd = fd;
416 /* create a hugepage file path */
417 eal_get_hugefile_path(path, buflen, hi->hugedir,
418 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
420 fd = fd_list[list_idx].fds[seg_idx];
423 fd = open(path, O_CREAT | O_RDWR, 0600);
425 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
426 __func__, strerror(errno));
429 /* take out a read lock */
430 if (lock(fd, LOCK_SH) < 0) {
431 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
432 __func__, strerror(errno));
436 fd_list[list_idx].fds[seg_idx] = fd;
443 resize_hugefile(int fd, char *path, int list_idx, int seg_idx,
444 uint64_t fa_offset, uint64_t page_sz, bool grow)
448 /* in-memory mode is a special case, because we don't need to perform
449 * any locking, and we can be sure that fallocate() is supported.
451 if (internal_config.in_memory) {
452 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
456 /* grow or shrink the file */
457 ret = fallocate(fd, flags, fa_offset, page_sz);
460 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
465 /* increase/decrease total segment count */
466 fd_list[list_idx].count += (grow ? 1 : -1);
467 if (!grow && fd_list[list_idx].count == 0) {
468 close(fd_list[list_idx].memseg_list_fd);
469 fd_list[list_idx].memseg_list_fd = -1;
475 if (fallocate_supported == 0) {
476 /* we cannot deallocate memory if fallocate() is not
477 * supported, and hugepage file is already locked at
478 * creation, so no further synchronization needed.
482 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
486 uint64_t new_size = fa_offset + page_sz;
487 uint64_t cur_size = get_file_size(fd);
489 /* fallocate isn't supported, fall back to ftruncate */
490 if (new_size > cur_size &&
491 ftruncate(fd, new_size) < 0) {
492 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
493 __func__, strerror(errno));
497 int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
501 /* if fallocate() is supported, we need to take out a
502 * read lock on allocate (to prevent other processes
503 * from deallocating this page), and take out a write
504 * lock on deallocate (to ensure nobody else is using
507 * read locks on page itself are already taken out at
508 * file creation, in get_seg_fd().
510 * we cannot rely on simple use of flock() call, because
511 * we need to be able to lock a section of the file,
512 * and we cannot use fcntl() locks, because of numerous
513 * problems with their semantics, so we will use
514 * deterministically named lock files for each section
517 * if we're shrinking the file, we want to upgrade our
518 * lock from shared to exclusive.
520 * lock_fd is an fd for a lockfile, not for the segment
523 lock_fd = get_segment_lock_fd(list_idx, seg_idx);
526 /* we are using this lockfile to determine
527 * whether this particular page is locked, as we
528 * are in single file segments mode and thus
529 * cannot use regular flock() to get this info.
531 * we want to try and take out an exclusive lock
532 * on the lock file to determine if we're the
533 * last ones using this page, and if not, we
534 * won't be shrinking it, and will instead exit
537 ret = lock(lock_fd, LOCK_EX);
539 /* drop the lock on the lockfile, so that even
540 * if we couldn't shrink the file ourselves, we
541 * are signalling to other processes that we're
542 * no longer using this page.
544 if (unlock_segment(list_idx, seg_idx))
545 RTE_LOG(ERR, EAL, "Could not unlock segment\n");
547 /* additionally, if this was the last lock on
548 * this segment list, we can safely close the
549 * page file fd, so that one of the processes
550 * could then delete the file after shrinking.
552 if (ret < 1 && fd_list[list_idx].count == 0) {
554 fd_list[list_idx].memseg_list_fd = -1;
558 RTE_LOG(ERR, EAL, "Could not lock segment\n");
562 /* failed to lock, not an error. */
566 /* grow or shrink the file */
567 ret = fallocate(fd, flags, fa_offset, page_sz);
570 if (fallocate_supported == -1 &&
572 RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
575 fallocate_supported = 0;
577 RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
583 fallocate_supported = 1;
585 /* we've grew/shrunk the file, and we hold an
586 * exclusive lock now. check if there are no
587 * more segments active in this segment list,
588 * and remove the file if there aren't.
590 if (fd_list[list_idx].count == 0) {
592 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
596 fd_list[list_idx].memseg_list_fd = -1;
605 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
606 struct hugepage_info *hi, unsigned int list_idx,
607 unsigned int seg_idx)
609 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
610 int cur_socket_id = 0;
622 alloc_sz = hi->hugepage_sz;
624 /* these are checked at init, but code analyzers don't know that */
625 if (internal_config.in_memory && !anonymous_hugepages_supported) {
626 RTE_LOG(ERR, EAL, "Anonymous hugepages not supported, in-memory mode cannot allocate memory\n");
629 if (internal_config.in_memory && !memfd_create_supported &&
630 internal_config.single_file_segments) {
631 RTE_LOG(ERR, EAL, "Single-file segments are not supported without memfd support\n");
635 /* in-memory without memfd is a special case */
638 if (internal_config.in_memory && !memfd_create_supported) {
639 int pagesz_flag, flags;
641 pagesz_flag = pagesz_flags(alloc_sz);
642 flags = pagesz_flag | MAP_HUGETLB | MAP_FIXED |
643 MAP_PRIVATE | MAP_ANONYMOUS;
647 /* single-file segments codepath will never be active
648 * here because in-memory mode is incompatible with the
649 * fallback path, and it's stopped at EAL initialization
654 /* takes out a read lock on segment or segment list */
655 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
657 RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
661 if (internal_config.single_file_segments) {
662 map_offset = seg_idx * alloc_sz;
663 ret = resize_hugefile(fd, path, list_idx, seg_idx,
664 map_offset, alloc_sz, true);
669 if (ftruncate(fd, alloc_sz) < 0) {
670 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
671 __func__, strerror(errno));
674 if (internal_config.hugepage_unlink &&
675 !internal_config.in_memory) {
677 RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
678 __func__, strerror(errno));
683 mmap_flags = MAP_SHARED | MAP_POPULATE | MAP_FIXED;
687 * map the segment, and populate page tables, the kernel fills
688 * this segment with zeros if it's a new page.
690 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, mmap_flags, fd,
693 if (va == MAP_FAILED) {
694 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
696 /* mmap failed, but the previous region might have been
697 * unmapped anyway. try to remap it
702 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
703 munmap(va, alloc_sz);
707 /* In linux, hugetlb limitations, like cgroup, are
708 * enforced at fault time instead of mmap(), even
709 * with the option of MAP_POPULATE. Kernel will send
710 * a SIGBUS signal. To avoid to be killed, save stack
711 * environment here, if SIGBUS happens, we can jump
714 if (huge_wrap_sigsetjmp()) {
715 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
716 (unsigned int)(alloc_sz >> 20));
720 /* we need to trigger a write to the page to enforce page fault and
721 * ensure that page is accessible to us, but we can't overwrite value
722 * that is already there, so read the old value, and write itback.
723 * kernel populates the page with zeroes initially.
725 *(volatile int *)addr = *(volatile int *)addr;
727 iova = rte_mem_virt2iova(addr);
728 if (iova == RTE_BAD_PHYS_ADDR) {
729 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
734 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
735 move_pages(getpid(), 1, &addr, NULL, &cur_socket_id, 0);
737 if (cur_socket_id != socket_id) {
739 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
740 __func__, socket_id, cur_socket_id);
746 ms->hugepage_sz = alloc_sz;
748 ms->nchannel = rte_memory_get_nchannel();
749 ms->nrank = rte_memory_get_nrank();
751 ms->socket_id = socket_id;
756 munmap(addr, alloc_sz);
759 new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
760 if (new_addr != addr) {
761 if (new_addr != NULL)
762 munmap(new_addr, alloc_sz);
763 /* we're leaving a hole in our virtual address space. if
764 * somebody else maps this hole now, we could accidentally
765 * override it in the future.
767 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
770 /* some codepaths will return negative fd, so exit early */
774 if (internal_config.single_file_segments) {
775 resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
777 /* ignore failure, can't make it any worse */
779 /* only remove file if we can take out a write lock */
780 if (internal_config.hugepage_unlink == 0 &&
781 internal_config.in_memory == 0 &&
782 lock(fd, LOCK_EX) == 1)
785 fd_list[list_idx].fds[seg_idx] = -1;
791 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
792 unsigned int list_idx, unsigned int seg_idx)
799 /* erase page data */
800 memset(ms->addr, 0, ms->len);
802 if (mmap(ms->addr, ms->len, PROT_READ,
803 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
805 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
811 /* if we're using anonymous hugepages, nothing to be done */
812 if (internal_config.in_memory && !memfd_create_supported)
815 /* if we've already unlinked the page, nothing needs to be done */
816 if (!internal_config.in_memory && internal_config.hugepage_unlink)
820 memset(ms, 0, sizeof(*ms));
824 /* if we are not in single file segments mode, we're going to unmap the
825 * segment and thus drop the lock on original fd, but hugepage dir is
826 * now locked so we can take out another one without races.
828 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
832 if (internal_config.single_file_segments) {
833 map_offset = seg_idx * ms->len;
834 if (resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
839 /* if we're able to take out a write lock, we're the last one
840 * holding onto this page.
842 if (!internal_config.in_memory) {
843 ret = lock(fd, LOCK_EX);
845 /* no one else is using this page */
850 /* closing fd will drop the lock */
852 fd_list[list_idx].fds[seg_idx] = -1;
855 memset(ms, 0, sizeof(*ms));
857 return ret < 0 ? -1 : 0;
860 struct alloc_walk_param {
861 struct hugepage_info *hi;
862 struct rte_memseg **ms;
864 unsigned int segs_allocated;
870 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
872 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
873 struct alloc_walk_param *wa = arg;
874 struct rte_memseg_list *cur_msl;
876 int cur_idx, start_idx, j, dir_fd = -1;
877 unsigned int msl_idx, need, i;
879 if (msl->page_sz != wa->page_sz)
881 if (msl->socket_id != wa->socket)
884 page_sz = (size_t)msl->page_sz;
886 msl_idx = msl - mcfg->memsegs;
887 cur_msl = &mcfg->memsegs[msl_idx];
891 /* try finding space in memseg list */
892 cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0, need);
897 /* do not allow any page allocations during the time we're allocating,
898 * because file creation and locking operations are not atomic,
899 * and we might be the first or the last ones to use a particular page,
900 * so we need to ensure atomicity of every operation.
902 * during init, we already hold a write lock, so don't try to take out
905 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
906 dir_fd = open(wa->hi->hugedir, O_RDONLY);
908 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
909 __func__, wa->hi->hugedir, strerror(errno));
912 /* blocking writelock */
913 if (flock(dir_fd, LOCK_EX)) {
914 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
915 __func__, wa->hi->hugedir, strerror(errno));
921 for (i = 0; i < need; i++, cur_idx++) {
922 struct rte_memseg *cur;
925 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
926 map_addr = RTE_PTR_ADD(cur_msl->base_va,
929 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
931 RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
934 /* if exact number wasn't requested, stop */
939 for (j = start_idx; j < cur_idx; j++) {
940 struct rte_memseg *tmp;
941 struct rte_fbarray *arr =
942 &cur_msl->memseg_arr;
944 tmp = rte_fbarray_get(arr, j);
945 rte_fbarray_set_free(arr, j);
947 /* free_seg may attempt to create a file, which
950 if (free_seg(tmp, wa->hi, msl_idx, j))
951 RTE_LOG(DEBUG, EAL, "Cannot free page\n");
955 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
964 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
967 wa->segs_allocated = i;
975 struct free_walk_param {
976 struct hugepage_info *hi;
977 struct rte_memseg *ms;
980 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
982 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
983 struct rte_memseg_list *found_msl;
984 struct free_walk_param *wa = arg;
985 uintptr_t start_addr, end_addr;
986 int msl_idx, seg_idx, ret, dir_fd = -1;
988 start_addr = (uintptr_t) msl->base_va;
989 end_addr = start_addr + msl->len;
991 if ((uintptr_t)wa->ms->addr < start_addr ||
992 (uintptr_t)wa->ms->addr >= end_addr)
995 msl_idx = msl - mcfg->memsegs;
996 seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
999 found_msl = &mcfg->memsegs[msl_idx];
1001 /* do not allow any page allocations during the time we're freeing,
1002 * because file creation and locking operations are not atomic,
1003 * and we might be the first or the last ones to use a particular page,
1004 * so we need to ensure atomicity of every operation.
1006 * during init, we already hold a write lock, so don't try to take out
1009 if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
1010 dir_fd = open(wa->hi->hugedir, O_RDONLY);
1012 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
1013 __func__, wa->hi->hugedir, strerror(errno));
1016 /* blocking writelock */
1017 if (flock(dir_fd, LOCK_EX)) {
1018 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
1019 __func__, wa->hi->hugedir, strerror(errno));
1025 found_msl->version++;
1027 rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
1029 ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
1041 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
1042 int socket, bool exact)
1045 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1046 bool have_numa = false;
1048 struct bitmask *oldmask;
1050 struct alloc_walk_param wa;
1051 struct hugepage_info *hi = NULL;
1053 memset(&wa, 0, sizeof(wa));
1055 /* dynamic allocation not supported in legacy mode */
1056 if (internal_config.legacy_mem)
1059 for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
1061 internal_config.hugepage_info[i].hugepage_sz) {
1062 hi = &internal_config.hugepage_info[i];
1067 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
1072 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1074 oldmask = numa_allocate_nodemask();
1075 prepare_numa(&oldpolicy, oldmask, socket);
1084 wa.page_sz = page_sz;
1086 wa.segs_allocated = 0;
1088 /* memalloc is locked, so it's safe to use thread-unsafe version */
1089 ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
1091 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
1094 } else if (ret > 0) {
1095 ret = (int)wa.segs_allocated;
1098 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
1100 restore_numa(&oldpolicy, oldmask);
1106 eal_memalloc_alloc_seg(size_t page_sz, int socket)
1108 struct rte_memseg *ms;
1109 if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
1111 /* return pointer to newly allocated memseg */
1116 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
1120 /* dynamic free not supported in legacy mode */
1121 if (internal_config.legacy_mem)
1124 for (seg = 0; seg < n_segs; seg++) {
1125 struct rte_memseg *cur = ms[seg];
1126 struct hugepage_info *hi = NULL;
1127 struct free_walk_param wa;
1130 /* if this page is marked as unfreeable, fail */
1131 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
1132 RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
1137 memset(&wa, 0, sizeof(wa));
1139 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
1141 hi = &internal_config.hugepage_info[i];
1142 if (cur->hugepage_sz == hi->hugepage_sz)
1145 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1146 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1154 /* memalloc is locked, so it's safe to use thread-unsafe version
1156 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1161 RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1168 eal_memalloc_free_seg(struct rte_memseg *ms)
1170 /* dynamic free not supported in legacy mode */
1171 if (internal_config.legacy_mem)
1174 return eal_memalloc_free_seg_bulk(&ms, 1);
1178 sync_chunk(struct rte_memseg_list *primary_msl,
1179 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1180 unsigned int msl_idx, bool used, int start, int end)
1182 struct rte_fbarray *l_arr, *p_arr;
1183 int i, ret, chunk_len, diff_len;
1185 l_arr = &local_msl->memseg_arr;
1186 p_arr = &primary_msl->memseg_arr;
1188 /* we need to aggregate allocations/deallocations into bigger chunks,
1189 * as we don't want to spam the user with per-page callbacks.
1191 * to avoid any potential issues, we also want to trigger
1192 * deallocation callbacks *before* we actually deallocate
1193 * memory, so that the user application could wrap up its use
1194 * before it goes away.
1197 chunk_len = end - start;
1199 /* find how many contiguous pages we can map/unmap for this chunk */
1201 rte_fbarray_find_contig_free(l_arr, start) :
1202 rte_fbarray_find_contig_used(l_arr, start);
1204 /* has to be at least one page */
1208 diff_len = RTE_MIN(chunk_len, diff_len);
1210 /* if we are freeing memory, notify the application */
1212 struct rte_memseg *ms;
1214 size_t len, page_sz;
1216 ms = rte_fbarray_get(l_arr, start);
1217 start_va = ms->addr;
1218 page_sz = (size_t)primary_msl->page_sz;
1219 len = page_sz * diff_len;
1221 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1225 for (i = 0; i < diff_len; i++) {
1226 struct rte_memseg *p_ms, *l_ms;
1227 int seg_idx = start + i;
1229 l_ms = rte_fbarray_get(l_arr, seg_idx);
1230 p_ms = rte_fbarray_get(p_arr, seg_idx);
1232 if (l_ms == NULL || p_ms == NULL)
1236 ret = alloc_seg(l_ms, p_ms->addr,
1237 p_ms->socket_id, hi,
1241 rte_fbarray_set_used(l_arr, seg_idx);
1243 ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1244 rte_fbarray_set_free(l_arr, seg_idx);
1250 /* if we just allocated memory, notify the application */
1252 struct rte_memseg *ms;
1254 size_t len, page_sz;
1256 ms = rte_fbarray_get(l_arr, start);
1257 start_va = ms->addr;
1258 page_sz = (size_t)primary_msl->page_sz;
1259 len = page_sz * diff_len;
1261 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1265 /* calculate how much we can advance until next chunk */
1267 rte_fbarray_find_contig_used(l_arr, start) :
1268 rte_fbarray_find_contig_free(l_arr, start);
1269 ret = RTE_MIN(chunk_len, diff_len);
1275 sync_status(struct rte_memseg_list *primary_msl,
1276 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1277 unsigned int msl_idx, bool used)
1279 struct rte_fbarray *l_arr, *p_arr;
1280 int p_idx, l_chunk_len, p_chunk_len, ret;
1283 /* this is a little bit tricky, but the basic idea is - walk both lists
1284 * and spot any places where there are discrepancies. walking both lists
1285 * and noting discrepancies in a single go is a hard problem, so we do
1286 * it in two passes - first we spot any places where allocated segments
1287 * mismatch (i.e. ensure that everything that's allocated in the primary
1288 * is also allocated in the secondary), and then we do it by looking at
1289 * free segments instead.
1291 * we also need to aggregate changes into chunks, as we have to call
1292 * callbacks per allocation, not per page.
1294 l_arr = &local_msl->memseg_arr;
1295 p_arr = &primary_msl->memseg_arr;
1298 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1300 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1302 while (p_idx >= 0) {
1303 int next_chunk_search_idx;
1306 p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1308 l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1311 p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1313 l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1316 /* best case scenario - no differences (or bigger, which will be
1317 * fixed during next iteration), look for next chunk
1319 if (l_chunk_len >= p_chunk_len) {
1320 next_chunk_search_idx = p_idx + p_chunk_len;
1324 /* if both chunks start at the same point, skip parts we know
1325 * are identical, and sync the rest. each call to sync_chunk
1326 * will only sync contiguous segments, so we need to call this
1327 * until we are sure there are no more differences in this
1330 start = p_idx + l_chunk_len;
1331 end = p_idx + p_chunk_len;
1333 ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1336 } while (start < end && ret >= 0);
1337 /* if ret is negative, something went wrong */
1341 next_chunk_search_idx = p_idx + p_chunk_len;
1343 /* skip to end of this chunk */
1345 p_idx = rte_fbarray_find_next_used(p_arr,
1346 next_chunk_search_idx);
1348 p_idx = rte_fbarray_find_next_free(p_arr,
1349 next_chunk_search_idx);
1356 sync_existing(struct rte_memseg_list *primary_msl,
1357 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1358 unsigned int msl_idx)
1362 /* do not allow any page allocations during the time we're allocating,
1363 * because file creation and locking operations are not atomic,
1364 * and we might be the first or the last ones to use a particular page,
1365 * so we need to ensure atomicity of every operation.
1367 dir_fd = open(hi->hugedir, O_RDONLY);
1369 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1370 hi->hugedir, strerror(errno));
1373 /* blocking writelock */
1374 if (flock(dir_fd, LOCK_EX)) {
1375 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1376 hi->hugedir, strerror(errno));
1381 /* ensure all allocated space is the same in both lists */
1382 ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1386 /* ensure all unallocated space is the same in both lists */
1387 ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1391 /* update version number */
1392 local_msl->version = primary_msl->version;
1403 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1405 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1406 struct rte_memseg_list *primary_msl, *local_msl;
1407 struct hugepage_info *hi = NULL;
1414 msl_idx = msl - mcfg->memsegs;
1415 primary_msl = &mcfg->memsegs[msl_idx];
1416 local_msl = &local_memsegs[msl_idx];
1418 for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1420 internal_config.hugepage_info[i].hugepage_sz;
1421 uint64_t msl_sz = primary_msl->page_sz;
1422 if (msl_sz == cur_sz) {
1423 hi = &internal_config.hugepage_info[i];
1428 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1432 /* if versions don't match, synchronize everything */
1433 if (local_msl->version != primary_msl->version &&
1434 sync_existing(primary_msl, local_msl, hi, msl_idx))
1441 eal_memalloc_sync_with_primary(void)
1443 /* nothing to be done in primary */
1444 if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1447 /* memalloc is locked, so it's safe to call thread-unsafe version */
1448 if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1454 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1455 void *arg __rte_unused)
1457 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1458 struct rte_memseg_list *primary_msl, *local_msl;
1459 char name[PATH_MAX];
1465 msl_idx = msl - mcfg->memsegs;
1466 primary_msl = &mcfg->memsegs[msl_idx];
1467 local_msl = &local_memsegs[msl_idx];
1469 /* create distinct fbarrays for each secondary */
1470 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1471 primary_msl->memseg_arr.name, getpid());
1473 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1474 primary_msl->memseg_arr.len,
1475 primary_msl->memseg_arr.elt_sz);
1477 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1480 local_msl->base_va = primary_msl->base_va;
1481 local_msl->len = primary_msl->len;
1487 alloc_list(int list_idx, int len)
1492 /* ensure we have space to store fd per each possible segment */
1493 data = malloc(sizeof(int) * len);
1495 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1498 /* set all fd's as invalid */
1499 for (i = 0; i < len; i++)
1502 fd_list[list_idx].fds = data;
1503 fd_list[list_idx].len = len;
1504 fd_list[list_idx].count = 0;
1505 fd_list[list_idx].memseg_list_fd = -1;
1511 fd_list_create_walk(const struct rte_memseg_list *msl,
1512 void *arg __rte_unused)
1514 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1521 msl_idx = msl - mcfg->memsegs;
1522 len = msl->memseg_arr.len;
1524 return alloc_list(msl_idx, len);
1528 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1530 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1532 /* if list is not allocated, allocate it */
1533 if (fd_list[list_idx].len == 0) {
1534 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1536 if (alloc_list(list_idx, len) < 0)
1539 fd_list[list_idx].fds[seg_idx] = fd;
1545 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1549 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1550 #ifndef MEMFD_SUPPORTED
1551 /* in in-memory or no-huge mode, we rely on memfd support */
1554 /* memfd supported, but hugetlbfs memfd may not be */
1555 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1559 if (internal_config.single_file_segments) {
1560 fd = fd_list[list_idx].memseg_list_fd;
1561 } else if (fd_list[list_idx].len == 0) {
1562 /* list not initialized */
1565 fd = fd_list[list_idx].fds[seg_idx];
1573 test_memfd_create(void)
1575 #ifdef MEMFD_SUPPORTED
1577 for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1578 uint64_t pagesz = internal_config.hugepage_info[i].hugepage_sz;
1579 int pagesz_flag = pagesz_flags(pagesz);
1582 flags = pagesz_flag | RTE_MFD_HUGETLB;
1583 int fd = memfd_create("test", flags);
1585 /* we failed - let memalloc know this isn't working */
1586 if (errno == EINVAL) {
1587 memfd_create_supported = 0;
1588 return 0; /* not supported */
1591 /* we got other error - something's wrong */
1592 return -1; /* error */
1595 return 1; /* supported */
1598 return 0; /* not supported */
1602 eal_memalloc_get_seg_fd_offset(int list_idx, int seg_idx, size_t *offset)
1604 struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1606 if (internal_config.in_memory || internal_config.no_hugetlbfs) {
1607 #ifndef MEMFD_SUPPORTED
1608 /* in in-memory or no-huge mode, we rely on memfd support */
1611 /* memfd supported, but hugetlbfs memfd may not be */
1612 if (!internal_config.no_hugetlbfs && !memfd_create_supported)
1616 /* fd_list not initialized? */
1617 if (fd_list[list_idx].len == 0)
1619 if (internal_config.single_file_segments) {
1620 size_t pgsz = mcfg->memsegs[list_idx].page_sz;
1622 /* segment not active? */
1623 if (fd_list[list_idx].memseg_list_fd < 0)
1625 *offset = pgsz * seg_idx;
1627 /* segment not active? */
1628 if (fd_list[list_idx].fds[seg_idx] < 0)
1636 eal_memalloc_init(void)
1638 if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1639 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1641 if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
1642 internal_config.in_memory) {
1643 int mfd_res = test_memfd_create();
1646 RTE_LOG(ERR, EAL, "Unable to check if memfd is supported\n");
1650 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1652 RTE_LOG(INFO, EAL, "Using memfd is not supported, falling back to anonymous hugepages\n");
1654 /* we only support single-file segments mode with in-memory mode
1655 * if we support hugetlbfs with memfd_create. this code will
1658 if (internal_config.single_file_segments &&
1660 RTE_LOG(ERR, EAL, "Single-file segments mode cannot be used without memfd support\n");
1663 /* this cannot ever happen but better safe than sorry */
1664 if (!anonymous_hugepages_supported) {
1665 RTE_LOG(ERR, EAL, "Using anonymous memory is not supported\n");
1670 /* initialize all of the fd lists */
1671 if (rte_memseg_list_walk(fd_list_create_walk, NULL))