b820989e90034495886a459abcf3d9518c4054bc
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_memalloc.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2017-2018 Intel Corporation
3  */
4
5 #define _FILE_OFFSET_BITS 64
6 #include <errno.h>
7 #include <stdarg.h>
8 #include <stdbool.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <stdint.h>
12 #include <inttypes.h>
13 #include <string.h>
14 #include <sys/mman.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/queue.h>
18 #include <sys/file.h>
19 #include <unistd.h>
20 #include <limits.h>
21 #include <fcntl.h>
22 #include <sys/ioctl.h>
23 #include <sys/time.h>
24 #include <signal.h>
25 #include <setjmp.h>
26 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
27 #include <numa.h>
28 #include <numaif.h>
29 #endif
30 #include <linux/falloc.h>
31 #include <linux/mman.h> /* for hugetlb-related mmap flags */
32
33 #include <rte_common.h>
34 #include <rte_log.h>
35 #include <rte_eal_memconfig.h>
36 #include <rte_eal.h>
37 #include <rte_memory.h>
38 #include <rte_spinlock.h>
39
40 #include "eal_filesystem.h"
41 #include "eal_internal_cfg.h"
42 #include "eal_memalloc.h"
43 #include "eal_private.h"
44
45 const int anonymous_hugepages_supported =
46 #ifdef MAP_HUGE_SHIFT
47                 1;
48 #define RTE_MAP_HUGE_SHIFT MAP_HUGE_SHIFT
49 #else
50                 0;
51 #define RTE_MAP_HUGE_SHIFT 26
52 #endif
53
54 /*
55  * not all kernel version support fallocate on hugetlbfs, so fall back to
56  * ftruncate and disallow deallocation if fallocate is not supported.
57  */
58 static int fallocate_supported = -1; /* unknown */
59
60 /*
61  * we have two modes - single file segments, and file-per-page mode.
62  *
63  * for single-file segments, we need some kind of mechanism to keep track of
64  * which hugepages can be freed back to the system, and which cannot. we cannot
65  * use flock() because they don't allow locking parts of a file, and we cannot
66  * use fcntl() due to issues with their semantics, so we will have to rely on a
67  * bunch of lockfiles for each page. so, we will use 'fds' array to keep track
68  * of per-page lockfiles. we will store the actual segment list fd in the
69  * 'memseg_list_fd' field.
70  *
71  * for file-per-page mode, each page will have its own fd, so 'memseg_list_fd'
72  * will be invalid (set to -1), and we'll use 'fds' to keep track of page fd's.
73  *
74  * we cannot know how many pages a system will have in advance, but we do know
75  * that they come in lists, and we know lengths of these lists. so, simply store
76  * a malloc'd array of fd's indexed by list and segment index.
77  *
78  * they will be initialized at startup, and filled as we allocate/deallocate
79  * segments.
80  */
81 static struct {
82         int *fds; /**< dynamically allocated array of segment lock fd's */
83         int memseg_list_fd; /**< memseg list fd */
84         int len; /**< total length of the array */
85         int count; /**< entries used in an array */
86 } fd_list[RTE_MAX_MEMSEG_LISTS];
87
88 /** local copy of a memory map, used to synchronize memory hotplug in MP */
89 static struct rte_memseg_list local_memsegs[RTE_MAX_MEMSEG_LISTS];
90
91 static sigjmp_buf huge_jmpenv;
92
93 static void __rte_unused huge_sigbus_handler(int signo __rte_unused)
94 {
95         siglongjmp(huge_jmpenv, 1);
96 }
97
98 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
99  * non-static local variable in the stack frame calling sigsetjmp might be
100  * clobbered by a call to longjmp.
101  */
102 static int __rte_unused huge_wrap_sigsetjmp(void)
103 {
104         return sigsetjmp(huge_jmpenv, 1);
105 }
106
107 static struct sigaction huge_action_old;
108 static int huge_need_recover;
109
110 static void __rte_unused
111 huge_register_sigbus(void)
112 {
113         sigset_t mask;
114         struct sigaction action;
115
116         sigemptyset(&mask);
117         sigaddset(&mask, SIGBUS);
118         action.sa_flags = 0;
119         action.sa_mask = mask;
120         action.sa_handler = huge_sigbus_handler;
121
122         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
123 }
124
125 static void __rte_unused
126 huge_recover_sigbus(void)
127 {
128         if (huge_need_recover) {
129                 sigaction(SIGBUS, &huge_action_old, NULL);
130                 huge_need_recover = 0;
131         }
132 }
133
134 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
135 static bool
136 check_numa(void)
137 {
138         bool ret = true;
139         /* Check if kernel supports NUMA. */
140         if (numa_available() != 0) {
141                 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
142                 ret = false;
143         }
144         return ret;
145 }
146
147 static void
148 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
149 {
150         RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
151         if (get_mempolicy(oldpolicy, oldmask->maskp,
152                           oldmask->size + 1, 0, 0) < 0) {
153                 RTE_LOG(ERR, EAL,
154                         "Failed to get current mempolicy: %s. "
155                         "Assuming MPOL_DEFAULT.\n", strerror(errno));
156                 oldpolicy = MPOL_DEFAULT;
157         }
158         RTE_LOG(DEBUG, EAL,
159                 "Setting policy MPOL_PREFERRED for socket %d\n",
160                 socket_id);
161         numa_set_preferred(socket_id);
162 }
163
164 static void
165 restore_numa(int *oldpolicy, struct bitmask *oldmask)
166 {
167         RTE_LOG(DEBUG, EAL,
168                 "Restoring previous memory policy: %d\n", *oldpolicy);
169         if (*oldpolicy == MPOL_DEFAULT) {
170                 numa_set_localalloc();
171         } else if (set_mempolicy(*oldpolicy, oldmask->maskp,
172                                  oldmask->size + 1) < 0) {
173                 RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
174                         strerror(errno));
175                 numa_set_localalloc();
176         }
177         numa_free_cpumask(oldmask);
178 }
179 #endif
180
181 /*
182  * uses fstat to report the size of a file on disk
183  */
184 static off_t
185 get_file_size(int fd)
186 {
187         struct stat st;
188         if (fstat(fd, &st) < 0)
189                 return 0;
190         return st.st_size;
191 }
192
193 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
194 static int lock(int fd, int type)
195 {
196         int ret;
197
198         /* flock may be interrupted */
199         do {
200                 ret = flock(fd, type | LOCK_NB);
201         } while (ret && errno == EINTR);
202
203         if (ret && errno == EWOULDBLOCK) {
204                 /* couldn't lock */
205                 return 0;
206         } else if (ret) {
207                 RTE_LOG(ERR, EAL, "%s(): error calling flock(): %s\n",
208                         __func__, strerror(errno));
209                 return -1;
210         }
211         /* lock was successful */
212         return 1;
213 }
214
215 static int get_segment_lock_fd(int list_idx, int seg_idx)
216 {
217         char path[PATH_MAX] = {0};
218         int fd;
219
220         if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
221                 return -1;
222         if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
223                 return -1;
224
225         fd = fd_list[list_idx].fds[seg_idx];
226         /* does this lock already exist? */
227         if (fd >= 0)
228                 return fd;
229
230         eal_get_hugefile_lock_path(path, sizeof(path),
231                         list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
232
233         fd = open(path, O_CREAT | O_RDWR, 0660);
234         if (fd < 0) {
235                 RTE_LOG(ERR, EAL, "%s(): error creating lockfile '%s': %s\n",
236                         __func__, path, strerror(errno));
237                 return -1;
238         }
239         /* take out a read lock */
240         if (lock(fd, LOCK_SH) != 1) {
241                 RTE_LOG(ERR, EAL, "%s(): failed to take out a readlock on '%s': %s\n",
242                         __func__, path, strerror(errno));
243                 close(fd);
244                 return -1;
245         }
246         /* store it for future reference */
247         fd_list[list_idx].fds[seg_idx] = fd;
248         fd_list[list_idx].count++;
249         return fd;
250 }
251
252 static int unlock_segment(int list_idx, int seg_idx)
253 {
254         int fd, ret;
255
256         if (list_idx < 0 || list_idx >= (int)RTE_DIM(fd_list))
257                 return -1;
258         if (seg_idx < 0 || seg_idx >= fd_list[list_idx].len)
259                 return -1;
260
261         fd = fd_list[list_idx].fds[seg_idx];
262
263         /* upgrade lock to exclusive to see if we can remove the lockfile */
264         ret = lock(fd, LOCK_EX);
265         if (ret == 1) {
266                 /* we've succeeded in taking exclusive lock, this lockfile may
267                  * be removed.
268                  */
269                 char path[PATH_MAX] = {0};
270                 eal_get_hugefile_lock_path(path, sizeof(path),
271                                 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
272                 if (unlink(path)) {
273                         RTE_LOG(ERR, EAL, "%s(): error removing lockfile '%s': %s\n",
274                                         __func__, path, strerror(errno));
275                 }
276         }
277         /* we don't want to leak the fd, so even if we fail to lock, close fd
278          * and remove it from list anyway.
279          */
280         close(fd);
281         fd_list[list_idx].fds[seg_idx] = -1;
282         fd_list[list_idx].count--;
283
284         if (ret < 0)
285                 return -1;
286         return 0;
287 }
288
289 static int
290 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
291                 unsigned int list_idx, unsigned int seg_idx)
292 {
293         int fd;
294
295         if (internal_config.single_file_segments) {
296                 /* create a hugepage file path */
297                 eal_get_hugefile_path(path, buflen, hi->hugedir, list_idx);
298
299                 fd = fd_list[list_idx].memseg_list_fd;
300
301                 if (fd < 0) {
302                         fd = open(path, O_CREAT | O_RDWR, 0600);
303                         if (fd < 0) {
304                                 RTE_LOG(ERR, EAL, "%s(): open failed: %s\n",
305                                         __func__, strerror(errno));
306                                 return -1;
307                         }
308                         /* take out a read lock and keep it indefinitely */
309                         if (lock(fd, LOCK_SH) < 0) {
310                                 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
311                                         __func__, strerror(errno));
312                                 close(fd);
313                                 return -1;
314                         }
315                         fd_list[list_idx].memseg_list_fd = fd;
316                 }
317         } else {
318                 /* create a hugepage file path */
319                 eal_get_hugefile_path(path, buflen, hi->hugedir,
320                                 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
321
322                 fd = fd_list[list_idx].fds[seg_idx];
323
324                 if (fd < 0) {
325                         fd = open(path, O_CREAT | O_RDWR, 0600);
326                         if (fd < 0) {
327                                 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
328                                         __func__, strerror(errno));
329                                 return -1;
330                         }
331                         /* take out a read lock */
332                         if (lock(fd, LOCK_SH) < 0) {
333                                 RTE_LOG(ERR, EAL, "%s(): lock failed: %s\n",
334                                         __func__, strerror(errno));
335                                 close(fd);
336                                 return -1;
337                         }
338                         fd_list[list_idx].fds[seg_idx] = fd;
339                 }
340         }
341         return fd;
342 }
343
344 static int
345 resize_hugefile(int fd, char *path, int list_idx, int seg_idx,
346                 uint64_t fa_offset, uint64_t page_sz, bool grow)
347 {
348         bool again = false;
349         do {
350                 if (fallocate_supported == 0) {
351                         /* we cannot deallocate memory if fallocate() is not
352                          * supported, and hugepage file is already locked at
353                          * creation, so no further synchronization needed.
354                          */
355
356                         if (!grow) {
357                                 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
358                                         __func__);
359                                 return -1;
360                         }
361                         uint64_t new_size = fa_offset + page_sz;
362                         uint64_t cur_size = get_file_size(fd);
363
364                         /* fallocate isn't supported, fall back to ftruncate */
365                         if (new_size > cur_size &&
366                                         ftruncate(fd, new_size) < 0) {
367                                 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
368                                         __func__, strerror(errno));
369                                 return -1;
370                         }
371                 } else {
372                         int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
373                                         FALLOC_FL_KEEP_SIZE;
374                         int ret, lock_fd;
375
376                         /* if fallocate() is supported, we need to take out a
377                          * read lock on allocate (to prevent other processes
378                          * from deallocating this page), and take out a write
379                          * lock on deallocate (to ensure nobody else is using
380                          * this page).
381                          *
382                          * read locks on page itself are already taken out at
383                          * file creation, in get_seg_fd().
384                          *
385                          * we cannot rely on simple use of flock() call, because
386                          * we need to be able to lock a section of the file,
387                          * and we cannot use fcntl() locks, because of numerous
388                          * problems with their semantics, so we will use
389                          * deterministically named lock files for each section
390                          * of the file.
391                          *
392                          * if we're shrinking the file, we want to upgrade our
393                          * lock from shared to exclusive.
394                          *
395                          * lock_fd is an fd for a lockfile, not for the segment
396                          * list.
397                          */
398                         lock_fd = get_segment_lock_fd(list_idx, seg_idx);
399
400                         if (!grow) {
401                                 /* we are using this lockfile to determine
402                                  * whether this particular page is locked, as we
403                                  * are in single file segments mode and thus
404                                  * cannot use regular flock() to get this info.
405                                  *
406                                  * we want to try and take out an exclusive lock
407                                  * on the lock file to determine if we're the
408                                  * last ones using this page, and if not, we
409                                  * won't be shrinking it, and will instead exit
410                                  * prematurely.
411                                  */
412                                 ret = lock(lock_fd, LOCK_EX);
413
414                                 /* drop the lock on the lockfile, so that even
415                                  * if we couldn't shrink the file ourselves, we
416                                  * are signalling to other processes that we're
417                                  * no longer using this page.
418                                  */
419                                 if (unlock_segment(list_idx, seg_idx))
420                                         RTE_LOG(ERR, EAL, "Could not unlock segment\n");
421
422                                 /* additionally, if this was the last lock on
423                                  * this segment list, we can safely close the
424                                  * page file fd, so that one of the processes
425                                  * could then delete the file after shrinking.
426                                  */
427                                 if (ret < 1 && fd_list[list_idx].count == 0) {
428                                         close(fd);
429                                         fd_list[list_idx].memseg_list_fd = -1;
430                                 }
431
432                                 if (ret < 0) {
433                                         RTE_LOG(ERR, EAL, "Could not lock segment\n");
434                                         return -1;
435                                 }
436                                 if (ret == 0)
437                                         /* failed to lock, not an error. */
438                                         return 0;
439                         }
440
441                         /* grow or shrink the file */
442                         ret = fallocate(fd, flags, fa_offset, page_sz);
443
444                         if (ret < 0) {
445                                 if (fallocate_supported == -1 &&
446                                                 errno == ENOTSUP) {
447                                         RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
448                                                 __func__);
449                                         again = true;
450                                         fallocate_supported = 0;
451                                 } else {
452                                         RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
453                                                 __func__,
454                                                 strerror(errno));
455                                         return -1;
456                                 }
457                         } else {
458                                 fallocate_supported = 1;
459
460                                 /* we've grew/shrunk the file, and we hold an
461                                  * exclusive lock now. check if there are no
462                                  * more segments active in this segment list,
463                                  * and remove the file if there aren't.
464                                  */
465                                 if (fd_list[list_idx].count == 0) {
466                                         if (unlink(path))
467                                                 RTE_LOG(ERR, EAL, "%s(): unlinking '%s' failed: %s\n",
468                                                         __func__, path,
469                                                         strerror(errno));
470                                         close(fd);
471                                         fd_list[list_idx].memseg_list_fd = -1;
472                                 }
473                         }
474                 }
475         } while (again);
476         return 0;
477 }
478
479 static int
480 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
481                 struct hugepage_info *hi, unsigned int list_idx,
482                 unsigned int seg_idx)
483 {
484 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
485         int cur_socket_id = 0;
486 #endif
487         uint64_t map_offset;
488         rte_iova_t iova;
489         void *va;
490         char path[PATH_MAX];
491         int ret = 0;
492         int fd;
493         size_t alloc_sz;
494         int flags;
495         void *new_addr;
496
497         alloc_sz = hi->hugepage_sz;
498         if (!internal_config.single_file_segments &&
499                         internal_config.in_memory &&
500                         anonymous_hugepages_supported) {
501                 int log2, flags;
502
503                 log2 = rte_log2_u32(alloc_sz);
504                 /* as per mmap() manpage, all page sizes are log2 of page size
505                  * shifted by MAP_HUGE_SHIFT
506                  */
507                 flags = (log2 << RTE_MAP_HUGE_SHIFT) | MAP_HUGETLB | MAP_FIXED |
508                                 MAP_PRIVATE | MAP_ANONYMOUS;
509                 fd = -1;
510                 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE, flags, -1, 0);
511
512                 /* single-file segments codepath will never be active because
513                  * in-memory mode is incompatible with it and it's stopped at
514                  * EAL initialization stage, however the compiler doesn't know
515                  * that and complains about map_offset being used uninitialized
516                  * on failure codepaths while having in-memory mode enabled. so,
517                  * assign a value here.
518                  */
519                 map_offset = 0;
520         } else {
521                 /* takes out a read lock on segment or segment list */
522                 fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
523                 if (fd < 0) {
524                         RTE_LOG(ERR, EAL, "Couldn't get fd on hugepage file\n");
525                         return -1;
526                 }
527
528                 if (internal_config.single_file_segments) {
529                         map_offset = seg_idx * alloc_sz;
530                         ret = resize_hugefile(fd, path, list_idx, seg_idx,
531                                         map_offset, alloc_sz, true);
532                         if (ret < 0)
533                                 goto resized;
534                 } else {
535                         map_offset = 0;
536                         if (ftruncate(fd, alloc_sz) < 0) {
537                                 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
538                                         __func__, strerror(errno));
539                                 goto resized;
540                         }
541                         if (internal_config.hugepage_unlink) {
542                                 if (unlink(path)) {
543                                         RTE_LOG(DEBUG, EAL, "%s(): unlink() failed: %s\n",
544                                                 __func__, strerror(errno));
545                                         goto resized;
546                                 }
547                         }
548                 }
549
550                 /*
551                  * map the segment, and populate page tables, the kernel fills
552                  * this segment with zeros if it's a new page.
553                  */
554                 va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE,
555                                 MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd,
556                                 map_offset);
557         }
558
559         if (va == MAP_FAILED) {
560                 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
561                         strerror(errno));
562                 /* mmap failed, but the previous region might have been
563                  * unmapped anyway. try to remap it
564                  */
565                 goto unmapped;
566         }
567         if (va != addr) {
568                 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
569                 munmap(va, alloc_sz);
570                 goto resized;
571         }
572
573         /* In linux, hugetlb limitations, like cgroup, are
574          * enforced at fault time instead of mmap(), even
575          * with the option of MAP_POPULATE. Kernel will send
576          * a SIGBUS signal. To avoid to be killed, save stack
577          * environment here, if SIGBUS happens, we can jump
578          * back here.
579          */
580         if (huge_wrap_sigsetjmp()) {
581                 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
582                         (unsigned int)(alloc_sz >> 20));
583                 goto mapped;
584         }
585
586         /* we need to trigger a write to the page to enforce page fault and
587          * ensure that page is accessible to us, but we can't overwrite value
588          * that is already there, so read the old value, and write itback.
589          * kernel populates the page with zeroes initially.
590          */
591         *(volatile int *)addr = *(volatile int *)addr;
592
593         iova = rte_mem_virt2iova(addr);
594         if (iova == RTE_BAD_PHYS_ADDR) {
595                 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
596                         __func__);
597                 goto mapped;
598         }
599
600 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
601         move_pages(getpid(), 1, &addr, NULL, &cur_socket_id, 0);
602
603         if (cur_socket_id != socket_id) {
604                 RTE_LOG(DEBUG, EAL,
605                                 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
606                         __func__, socket_id, cur_socket_id);
607                 goto mapped;
608         }
609 #endif
610
611         ms->addr = addr;
612         ms->hugepage_sz = alloc_sz;
613         ms->len = alloc_sz;
614         ms->nchannel = rte_memory_get_nchannel();
615         ms->nrank = rte_memory_get_nrank();
616         ms->iova = iova;
617         ms->socket_id = socket_id;
618
619         return 0;
620
621 mapped:
622         munmap(addr, alloc_sz);
623 unmapped:
624         flags = MAP_FIXED;
625 #ifdef RTE_ARCH_PPC_64
626         flags |= MAP_HUGETLB;
627 #endif
628         new_addr = eal_get_virtual_area(addr, &alloc_sz, alloc_sz, 0, flags);
629         if (new_addr != addr) {
630                 if (new_addr != NULL)
631                         munmap(new_addr, alloc_sz);
632                 /* we're leaving a hole in our virtual address space. if
633                  * somebody else maps this hole now, we could accidentally
634                  * override it in the future.
635                  */
636                 RTE_LOG(CRIT, EAL, "Can't mmap holes in our virtual address space\n");
637         }
638 resized:
639         /* some codepaths will return negative fd, so exit early */
640         if (fd < 0)
641                 return -1;
642
643         if (internal_config.single_file_segments) {
644                 resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
645                                 alloc_sz, false);
646                 /* ignore failure, can't make it any worse */
647         } else {
648                 /* only remove file if we can take out a write lock */
649                 if (internal_config.hugepage_unlink == 0 &&
650                                 internal_config.in_memory == 0 &&
651                                 lock(fd, LOCK_EX) == 1)
652                         unlink(path);
653                 close(fd);
654                 fd_list[list_idx].fds[seg_idx] = -1;
655         }
656         return -1;
657 }
658
659 static int
660 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
661                 unsigned int list_idx, unsigned int seg_idx)
662 {
663         uint64_t map_offset;
664         char path[PATH_MAX];
665         int fd, ret;
666
667         /* erase page data */
668         memset(ms->addr, 0, ms->len);
669
670         if (mmap(ms->addr, ms->len, PROT_READ,
671                         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
672                                 MAP_FAILED) {
673                 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
674                 return -1;
675         }
676
677         /* if we've already unlinked the page, nothing needs to be done */
678         if (internal_config.hugepage_unlink) {
679                 memset(ms, 0, sizeof(*ms));
680                 return 0;
681         }
682
683         /* if we are not in single file segments mode, we're going to unmap the
684          * segment and thus drop the lock on original fd, but hugepage dir is
685          * now locked so we can take out another one without races.
686          */
687         fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
688         if (fd < 0)
689                 return -1;
690
691         if (internal_config.single_file_segments) {
692                 map_offset = seg_idx * ms->len;
693                 if (resize_hugefile(fd, path, list_idx, seg_idx, map_offset,
694                                 ms->len, false))
695                         return -1;
696                 ret = 0;
697         } else {
698                 /* if we're able to take out a write lock, we're the last one
699                  * holding onto this page.
700                  */
701                 ret = lock(fd, LOCK_EX);
702                 if (ret >= 0) {
703                         /* no one else is using this page */
704                         if (ret == 1)
705                                 unlink(path);
706                 }
707                 /* closing fd will drop the lock */
708                 close(fd);
709                 fd_list[list_idx].fds[seg_idx] = -1;
710         }
711
712         memset(ms, 0, sizeof(*ms));
713
714         return ret < 0 ? -1 : 0;
715 }
716
717 struct alloc_walk_param {
718         struct hugepage_info *hi;
719         struct rte_memseg **ms;
720         size_t page_sz;
721         unsigned int segs_allocated;
722         unsigned int n_segs;
723         int socket;
724         bool exact;
725 };
726 static int
727 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
728 {
729         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
730         struct alloc_walk_param *wa = arg;
731         struct rte_memseg_list *cur_msl;
732         size_t page_sz;
733         int cur_idx, start_idx, j, dir_fd = -1;
734         unsigned int msl_idx, need, i;
735
736         if (msl->page_sz != wa->page_sz)
737                 return 0;
738         if (msl->socket_id != wa->socket)
739                 return 0;
740
741         page_sz = (size_t)msl->page_sz;
742
743         msl_idx = msl - mcfg->memsegs;
744         cur_msl = &mcfg->memsegs[msl_idx];
745
746         need = wa->n_segs;
747
748         /* try finding space in memseg list */
749         cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0, need);
750         if (cur_idx < 0)
751                 return 0;
752         start_idx = cur_idx;
753
754         /* do not allow any page allocations during the time we're allocating,
755          * because file creation and locking operations are not atomic,
756          * and we might be the first or the last ones to use a particular page,
757          * so we need to ensure atomicity of every operation.
758          *
759          * during init, we already hold a write lock, so don't try to take out
760          * another one.
761          */
762         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
763                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
764                 if (dir_fd < 0) {
765                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
766                                 __func__, wa->hi->hugedir, strerror(errno));
767                         return -1;
768                 }
769                 /* blocking writelock */
770                 if (flock(dir_fd, LOCK_EX)) {
771                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
772                                 __func__, wa->hi->hugedir, strerror(errno));
773                         close(dir_fd);
774                         return -1;
775                 }
776         }
777
778         for (i = 0; i < need; i++, cur_idx++) {
779                 struct rte_memseg *cur;
780                 void *map_addr;
781
782                 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
783                 map_addr = RTE_PTR_ADD(cur_msl->base_va,
784                                 cur_idx * page_sz);
785
786                 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
787                                 msl_idx, cur_idx)) {
788                         RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
789                                 need, i);
790
791                         /* if exact number wasn't requested, stop */
792                         if (!wa->exact)
793                                 goto out;
794
795                         /* clean up */
796                         for (j = start_idx; j < cur_idx; j++) {
797                                 struct rte_memseg *tmp;
798                                 struct rte_fbarray *arr =
799                                                 &cur_msl->memseg_arr;
800
801                                 tmp = rte_fbarray_get(arr, j);
802                                 rte_fbarray_set_free(arr, j);
803
804                                 /* free_seg may attempt to create a file, which
805                                  * may fail.
806                                  */
807                                 if (free_seg(tmp, wa->hi, msl_idx, j))
808                                         RTE_LOG(DEBUG, EAL, "Cannot free page\n");
809                         }
810                         /* clear the list */
811                         if (wa->ms)
812                                 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
813
814                         if (dir_fd >= 0)
815                                 close(dir_fd);
816                         return -1;
817                 }
818                 if (wa->ms)
819                         wa->ms[i] = cur;
820
821                 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
822         }
823 out:
824         wa->segs_allocated = i;
825         if (i > 0)
826                 cur_msl->version++;
827         if (dir_fd >= 0)
828                 close(dir_fd);
829         return 1;
830 }
831
832 struct free_walk_param {
833         struct hugepage_info *hi;
834         struct rte_memseg *ms;
835 };
836 static int
837 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
838 {
839         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
840         struct rte_memseg_list *found_msl;
841         struct free_walk_param *wa = arg;
842         uintptr_t start_addr, end_addr;
843         int msl_idx, seg_idx, ret, dir_fd = -1;
844
845         start_addr = (uintptr_t) msl->base_va;
846         end_addr = start_addr + msl->memseg_arr.len * (size_t)msl->page_sz;
847
848         if ((uintptr_t)wa->ms->addr < start_addr ||
849                         (uintptr_t)wa->ms->addr >= end_addr)
850                 return 0;
851
852         msl_idx = msl - mcfg->memsegs;
853         seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
854
855         /* msl is const */
856         found_msl = &mcfg->memsegs[msl_idx];
857
858         /* do not allow any page allocations during the time we're freeing,
859          * because file creation and locking operations are not atomic,
860          * and we might be the first or the last ones to use a particular page,
861          * so we need to ensure atomicity of every operation.
862          *
863          * during init, we already hold a write lock, so don't try to take out
864          * another one.
865          */
866         if (wa->hi->lock_descriptor == -1 && !internal_config.in_memory) {
867                 dir_fd = open(wa->hi->hugedir, O_RDONLY);
868                 if (dir_fd < 0) {
869                         RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n",
870                                 __func__, wa->hi->hugedir, strerror(errno));
871                         return -1;
872                 }
873                 /* blocking writelock */
874                 if (flock(dir_fd, LOCK_EX)) {
875                         RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n",
876                                 __func__, wa->hi->hugedir, strerror(errno));
877                         close(dir_fd);
878                         return -1;
879                 }
880         }
881
882         found_msl->version++;
883
884         rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
885
886         ret = free_seg(wa->ms, wa->hi, msl_idx, seg_idx);
887
888         if (dir_fd >= 0)
889                 close(dir_fd);
890
891         if (ret < 0)
892                 return -1;
893
894         return 1;
895 }
896
897 int
898 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
899                 int socket, bool exact)
900 {
901         int i, ret = -1;
902 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
903         bool have_numa = false;
904         int oldpolicy;
905         struct bitmask *oldmask;
906 #endif
907         struct alloc_walk_param wa;
908         struct hugepage_info *hi = NULL;
909
910         memset(&wa, 0, sizeof(wa));
911
912         /* dynamic allocation not supported in legacy mode */
913         if (internal_config.legacy_mem)
914                 return -1;
915
916         for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
917                 if (page_sz ==
918                                 internal_config.hugepage_info[i].hugepage_sz) {
919                         hi = &internal_config.hugepage_info[i];
920                         break;
921                 }
922         }
923         if (!hi) {
924                 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
925                         __func__);
926                 return -1;
927         }
928
929 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
930         if (check_numa()) {
931                 oldmask = numa_allocate_nodemask();
932                 prepare_numa(&oldpolicy, oldmask, socket);
933                 have_numa = true;
934         }
935 #endif
936
937         wa.exact = exact;
938         wa.hi = hi;
939         wa.ms = ms;
940         wa.n_segs = n_segs;
941         wa.page_sz = page_sz;
942         wa.socket = socket;
943         wa.segs_allocated = 0;
944
945         /* memalloc is locked, so it's safe to use thread-unsafe version */
946         ret = rte_memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
947         if (ret == 0) {
948                 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
949                         __func__);
950                 ret = -1;
951         } else if (ret > 0) {
952                 ret = (int)wa.segs_allocated;
953         }
954
955 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
956         if (have_numa)
957                 restore_numa(&oldpolicy, oldmask);
958 #endif
959         return ret;
960 }
961
962 struct rte_memseg *
963 eal_memalloc_alloc_seg(size_t page_sz, int socket)
964 {
965         struct rte_memseg *ms;
966         if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
967                 return NULL;
968         /* return pointer to newly allocated memseg */
969         return ms;
970 }
971
972 int
973 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
974 {
975         int seg, ret = 0;
976
977         /* dynamic free not supported in legacy mode */
978         if (internal_config.legacy_mem)
979                 return -1;
980
981         for (seg = 0; seg < n_segs; seg++) {
982                 struct rte_memseg *cur = ms[seg];
983                 struct hugepage_info *hi = NULL;
984                 struct free_walk_param wa;
985                 int i, walk_res;
986
987                 /* if this page is marked as unfreeable, fail */
988                 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
989                         RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
990                         ret = -1;
991                         continue;
992                 }
993
994                 memset(&wa, 0, sizeof(wa));
995
996                 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
997                                 i++) {
998                         hi = &internal_config.hugepage_info[i];
999                         if (cur->hugepage_sz == hi->hugepage_sz)
1000                                 break;
1001                 }
1002                 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
1003                         RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1004                         ret = -1;
1005                         continue;
1006                 }
1007
1008                 wa.ms = cur;
1009                 wa.hi = hi;
1010
1011                 /* memalloc is locked, so it's safe to use thread-unsafe version
1012                  */
1013                 walk_res = rte_memseg_list_walk_thread_unsafe(free_seg_walk,
1014                                 &wa);
1015                 if (walk_res == 1)
1016                         continue;
1017                 if (walk_res == 0)
1018                         RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
1019                 ret = -1;
1020         }
1021         return ret;
1022 }
1023
1024 int
1025 eal_memalloc_free_seg(struct rte_memseg *ms)
1026 {
1027         /* dynamic free not supported in legacy mode */
1028         if (internal_config.legacy_mem)
1029                 return -1;
1030
1031         return eal_memalloc_free_seg_bulk(&ms, 1);
1032 }
1033
1034 static int
1035 sync_chunk(struct rte_memseg_list *primary_msl,
1036                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1037                 unsigned int msl_idx, bool used, int start, int end)
1038 {
1039         struct rte_fbarray *l_arr, *p_arr;
1040         int i, ret, chunk_len, diff_len;
1041
1042         l_arr = &local_msl->memseg_arr;
1043         p_arr = &primary_msl->memseg_arr;
1044
1045         /* we need to aggregate allocations/deallocations into bigger chunks,
1046          * as we don't want to spam the user with per-page callbacks.
1047          *
1048          * to avoid any potential issues, we also want to trigger
1049          * deallocation callbacks *before* we actually deallocate
1050          * memory, so that the user application could wrap up its use
1051          * before it goes away.
1052          */
1053
1054         chunk_len = end - start;
1055
1056         /* find how many contiguous pages we can map/unmap for this chunk */
1057         diff_len = used ?
1058                         rte_fbarray_find_contig_free(l_arr, start) :
1059                         rte_fbarray_find_contig_used(l_arr, start);
1060
1061         /* has to be at least one page */
1062         if (diff_len < 1)
1063                 return -1;
1064
1065         diff_len = RTE_MIN(chunk_len, diff_len);
1066
1067         /* if we are freeing memory, notify the application */
1068         if (!used) {
1069                 struct rte_memseg *ms;
1070                 void *start_va;
1071                 size_t len, page_sz;
1072
1073                 ms = rte_fbarray_get(l_arr, start);
1074                 start_va = ms->addr;
1075                 page_sz = (size_t)primary_msl->page_sz;
1076                 len = page_sz * diff_len;
1077
1078                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
1079                                 start_va, len);
1080         }
1081
1082         for (i = 0; i < diff_len; i++) {
1083                 struct rte_memseg *p_ms, *l_ms;
1084                 int seg_idx = start + i;
1085
1086                 l_ms = rte_fbarray_get(l_arr, seg_idx);
1087                 p_ms = rte_fbarray_get(p_arr, seg_idx);
1088
1089                 if (l_ms == NULL || p_ms == NULL)
1090                         return -1;
1091
1092                 if (used) {
1093                         ret = alloc_seg(l_ms, p_ms->addr,
1094                                         p_ms->socket_id, hi,
1095                                         msl_idx, seg_idx);
1096                         if (ret < 0)
1097                                 return -1;
1098                         rte_fbarray_set_used(l_arr, seg_idx);
1099                 } else {
1100                         ret = free_seg(l_ms, hi, msl_idx, seg_idx);
1101                         rte_fbarray_set_free(l_arr, seg_idx);
1102                         if (ret < 0)
1103                                 return -1;
1104                 }
1105         }
1106
1107         /* if we just allocated memory, notify the application */
1108         if (used) {
1109                 struct rte_memseg *ms;
1110                 void *start_va;
1111                 size_t len, page_sz;
1112
1113                 ms = rte_fbarray_get(l_arr, start);
1114                 start_va = ms->addr;
1115                 page_sz = (size_t)primary_msl->page_sz;
1116                 len = page_sz * diff_len;
1117
1118                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1119                                 start_va, len);
1120         }
1121
1122         /* calculate how much we can advance until next chunk */
1123         diff_len = used ?
1124                         rte_fbarray_find_contig_used(l_arr, start) :
1125                         rte_fbarray_find_contig_free(l_arr, start);
1126         ret = RTE_MIN(chunk_len, diff_len);
1127
1128         return ret;
1129 }
1130
1131 static int
1132 sync_status(struct rte_memseg_list *primary_msl,
1133                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1134                 unsigned int msl_idx, bool used)
1135 {
1136         struct rte_fbarray *l_arr, *p_arr;
1137         int p_idx, l_chunk_len, p_chunk_len, ret;
1138         int start, end;
1139
1140         /* this is a little bit tricky, but the basic idea is - walk both lists
1141          * and spot any places where there are discrepancies. walking both lists
1142          * and noting discrepancies in a single go is a hard problem, so we do
1143          * it in two passes - first we spot any places where allocated segments
1144          * mismatch (i.e. ensure that everything that's allocated in the primary
1145          * is also allocated in the secondary), and then we do it by looking at
1146          * free segments instead.
1147          *
1148          * we also need to aggregate changes into chunks, as we have to call
1149          * callbacks per allocation, not per page.
1150          */
1151         l_arr = &local_msl->memseg_arr;
1152         p_arr = &primary_msl->memseg_arr;
1153
1154         if (used)
1155                 p_idx = rte_fbarray_find_next_used(p_arr, 0);
1156         else
1157                 p_idx = rte_fbarray_find_next_free(p_arr, 0);
1158
1159         while (p_idx >= 0) {
1160                 int next_chunk_search_idx;
1161
1162                 if (used) {
1163                         p_chunk_len = rte_fbarray_find_contig_used(p_arr,
1164                                         p_idx);
1165                         l_chunk_len = rte_fbarray_find_contig_used(l_arr,
1166                                         p_idx);
1167                 } else {
1168                         p_chunk_len = rte_fbarray_find_contig_free(p_arr,
1169                                         p_idx);
1170                         l_chunk_len = rte_fbarray_find_contig_free(l_arr,
1171                                         p_idx);
1172                 }
1173                 /* best case scenario - no differences (or bigger, which will be
1174                  * fixed during next iteration), look for next chunk
1175                  */
1176                 if (l_chunk_len >= p_chunk_len) {
1177                         next_chunk_search_idx = p_idx + p_chunk_len;
1178                         goto next_chunk;
1179                 }
1180
1181                 /* if both chunks start at the same point, skip parts we know
1182                  * are identical, and sync the rest. each call to sync_chunk
1183                  * will only sync contiguous segments, so we need to call this
1184                  * until we are sure there are no more differences in this
1185                  * chunk.
1186                  */
1187                 start = p_idx + l_chunk_len;
1188                 end = p_idx + p_chunk_len;
1189                 do {
1190                         ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1191                                         used, start, end);
1192                         start += ret;
1193                 } while (start < end && ret >= 0);
1194                 /* if ret is negative, something went wrong */
1195                 if (ret < 0)
1196                         return -1;
1197
1198                 next_chunk_search_idx = p_idx + p_chunk_len;
1199 next_chunk:
1200                 /* skip to end of this chunk */
1201                 if (used) {
1202                         p_idx = rte_fbarray_find_next_used(p_arr,
1203                                         next_chunk_search_idx);
1204                 } else {
1205                         p_idx = rte_fbarray_find_next_free(p_arr,
1206                                         next_chunk_search_idx);
1207                 }
1208         }
1209         return 0;
1210 }
1211
1212 static int
1213 sync_existing(struct rte_memseg_list *primary_msl,
1214                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1215                 unsigned int msl_idx)
1216 {
1217         int ret, dir_fd;
1218
1219         /* do not allow any page allocations during the time we're allocating,
1220          * because file creation and locking operations are not atomic,
1221          * and we might be the first or the last ones to use a particular page,
1222          * so we need to ensure atomicity of every operation.
1223          */
1224         dir_fd = open(hi->hugedir, O_RDONLY);
1225         if (dir_fd < 0) {
1226                 RTE_LOG(ERR, EAL, "%s(): Cannot open '%s': %s\n", __func__,
1227                         hi->hugedir, strerror(errno));
1228                 return -1;
1229         }
1230         /* blocking writelock */
1231         if (flock(dir_fd, LOCK_EX)) {
1232                 RTE_LOG(ERR, EAL, "%s(): Cannot lock '%s': %s\n", __func__,
1233                         hi->hugedir, strerror(errno));
1234                 close(dir_fd);
1235                 return -1;
1236         }
1237
1238         /* ensure all allocated space is the same in both lists */
1239         ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1240         if (ret < 0)
1241                 goto fail;
1242
1243         /* ensure all unallocated space is the same in both lists */
1244         ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1245         if (ret < 0)
1246                 goto fail;
1247
1248         /* update version number */
1249         local_msl->version = primary_msl->version;
1250
1251         close(dir_fd);
1252
1253         return 0;
1254 fail:
1255         close(dir_fd);
1256         return -1;
1257 }
1258
1259 static int
1260 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1261 {
1262         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1263         struct rte_memseg_list *primary_msl, *local_msl;
1264         struct hugepage_info *hi = NULL;
1265         unsigned int i;
1266         int msl_idx;
1267
1268         msl_idx = msl - mcfg->memsegs;
1269         primary_msl = &mcfg->memsegs[msl_idx];
1270         local_msl = &local_memsegs[msl_idx];
1271
1272         for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1273                 uint64_t cur_sz =
1274                         internal_config.hugepage_info[i].hugepage_sz;
1275                 uint64_t msl_sz = primary_msl->page_sz;
1276                 if (msl_sz == cur_sz) {
1277                         hi = &internal_config.hugepage_info[i];
1278                         break;
1279                 }
1280         }
1281         if (!hi) {
1282                 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1283                 return -1;
1284         }
1285
1286         /* if versions don't match, synchronize everything */
1287         if (local_msl->version != primary_msl->version &&
1288                         sync_existing(primary_msl, local_msl, hi, msl_idx))
1289                 return -1;
1290         return 0;
1291 }
1292
1293
1294 int
1295 eal_memalloc_sync_with_primary(void)
1296 {
1297         /* nothing to be done in primary */
1298         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1299                 return 0;
1300
1301         /* memalloc is locked, so it's safe to call thread-unsafe version */
1302         if (rte_memseg_list_walk_thread_unsafe(sync_walk, NULL))
1303                 return -1;
1304         return 0;
1305 }
1306
1307 static int
1308 secondary_msl_create_walk(const struct rte_memseg_list *msl,
1309                 void *arg __rte_unused)
1310 {
1311         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1312         struct rte_memseg_list *primary_msl, *local_msl;
1313         char name[PATH_MAX];
1314         int msl_idx, ret;
1315
1316         msl_idx = msl - mcfg->memsegs;
1317         primary_msl = &mcfg->memsegs[msl_idx];
1318         local_msl = &local_memsegs[msl_idx];
1319
1320         /* create distinct fbarrays for each secondary */
1321         snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1322                 primary_msl->memseg_arr.name, getpid());
1323
1324         ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1325                 primary_msl->memseg_arr.len,
1326                 primary_msl->memseg_arr.elt_sz);
1327         if (ret < 0) {
1328                 RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1329                 return -1;
1330         }
1331         local_msl->base_va = primary_msl->base_va;
1332
1333         return 0;
1334 }
1335
1336 static int
1337 alloc_list(int list_idx, int len)
1338 {
1339         int *data;
1340         int i;
1341
1342         /* ensure we have space to store fd per each possible segment */
1343         data = malloc(sizeof(int) * len);
1344         if (data == NULL) {
1345                 RTE_LOG(ERR, EAL, "Unable to allocate space for file descriptors\n");
1346                 return -1;
1347         }
1348         /* set all fd's as invalid */
1349         for (i = 0; i < len; i++)
1350                 data[i] = -1;
1351
1352         fd_list[list_idx].fds = data;
1353         fd_list[list_idx].len = len;
1354         fd_list[list_idx].count = 0;
1355         fd_list[list_idx].memseg_list_fd = -1;
1356
1357         return 0;
1358 }
1359
1360 static int
1361 fd_list_create_walk(const struct rte_memseg_list *msl,
1362                 void *arg __rte_unused)
1363 {
1364         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1365         unsigned int len;
1366         int msl_idx;
1367
1368         msl_idx = msl - mcfg->memsegs;
1369         len = msl->memseg_arr.len;
1370
1371         return alloc_list(msl_idx, len);
1372 }
1373
1374 int
1375 eal_memalloc_set_seg_fd(int list_idx, int seg_idx, int fd)
1376 {
1377         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1378
1379         /* if list is not allocated, allocate it */
1380         if (fd_list[list_idx].len == 0) {
1381                 int len = mcfg->memsegs[list_idx].memseg_arr.len;
1382
1383                 if (alloc_list(list_idx, len) < 0)
1384                         return -1;
1385         }
1386         fd_list[list_idx].fds[seg_idx] = fd;
1387
1388         return 0;
1389 }
1390
1391 int
1392 eal_memalloc_get_seg_fd(int list_idx, int seg_idx)
1393 {
1394         if (internal_config.single_file_segments)
1395                 return fd_list[list_idx].memseg_list_fd;
1396         /* list not initialized */
1397         if (fd_list[list_idx].len == 0)
1398                 return -1;
1399         return fd_list[list_idx].fds[seg_idx];
1400 }
1401
1402 int
1403 eal_memalloc_init(void)
1404 {
1405         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1406                 if (rte_memseg_list_walk(secondary_msl_create_walk, NULL) < 0)
1407                         return -1;
1408
1409         /* initialize all of the fd lists */
1410         if (rte_memseg_list_walk(fd_list_create_walk, NULL))
1411                 return -1;
1412         return 0;
1413 }