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