mem: fix comparison of old policy
[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
43 /*
44  * not all kernel version support fallocate on hugetlbfs, so fall back to
45  * ftruncate and disallow deallocation if fallocate is not supported.
46  */
47 static int fallocate_supported = -1; /* unknown */
48
49 /*
50  * If each page is in a separate file, we can close fd's since we need each fd
51  * only once. However, in single file segments mode, we can get away with using
52  * a single fd for entire segments, but we need to store them somewhere. Each
53  * fd is different within each process, so we'll store them in a local tailq.
54  */
55 struct msl_entry {
56         TAILQ_ENTRY(msl_entry) next;
57         unsigned int msl_idx;
58         int fd;
59 };
60
61 /** Double linked list of memseg list fd's. */
62 TAILQ_HEAD(msl_entry_list, msl_entry);
63
64 static struct msl_entry_list msl_entry_list =
65                 TAILQ_HEAD_INITIALIZER(msl_entry_list);
66 static rte_spinlock_t tailq_lock = RTE_SPINLOCK_INITIALIZER;
67
68 /** local copy of a memory map, used to synchronize memory hotplug in MP */
69 static struct rte_memseg_list local_memsegs[RTE_MAX_MEMSEG_LISTS];
70
71 static sigjmp_buf huge_jmpenv;
72
73 static void __rte_unused huge_sigbus_handler(int signo __rte_unused)
74 {
75         siglongjmp(huge_jmpenv, 1);
76 }
77
78 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
79  * non-static local variable in the stack frame calling sigsetjmp might be
80  * clobbered by a call to longjmp.
81  */
82 static int __rte_unused huge_wrap_sigsetjmp(void)
83 {
84         return sigsetjmp(huge_jmpenv, 1);
85 }
86
87 static struct sigaction huge_action_old;
88 static int huge_need_recover;
89
90 static void __rte_unused
91 huge_register_sigbus(void)
92 {
93         sigset_t mask;
94         struct sigaction action;
95
96         sigemptyset(&mask);
97         sigaddset(&mask, SIGBUS);
98         action.sa_flags = 0;
99         action.sa_mask = mask;
100         action.sa_handler = huge_sigbus_handler;
101
102         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
103 }
104
105 static void __rte_unused
106 huge_recover_sigbus(void)
107 {
108         if (huge_need_recover) {
109                 sigaction(SIGBUS, &huge_action_old, NULL);
110                 huge_need_recover = 0;
111         }
112 }
113
114 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
115 static bool
116 check_numa(void)
117 {
118         bool ret = true;
119         /* Check if kernel supports NUMA. */
120         if (numa_available() != 0) {
121                 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
122                 ret = false;
123         }
124         return ret;
125 }
126
127 static void
128 prepare_numa(int *oldpolicy, struct bitmask *oldmask, int socket_id)
129 {
130         RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
131         if (get_mempolicy(oldpolicy, oldmask->maskp,
132                           oldmask->size + 1, 0, 0) < 0) {
133                 RTE_LOG(ERR, EAL,
134                         "Failed to get current mempolicy: %s. "
135                         "Assuming MPOL_DEFAULT.\n", strerror(errno));
136                 oldpolicy = MPOL_DEFAULT;
137         }
138         RTE_LOG(DEBUG, EAL,
139                 "Setting policy MPOL_PREFERRED for socket %d\n",
140                 socket_id);
141         numa_set_preferred(socket_id);
142 }
143
144 static void
145 resotre_numa(int *oldpolicy, struct bitmask *oldmask)
146 {
147         RTE_LOG(DEBUG, EAL,
148                 "Restoring previous memory policy: %d\n", *oldpolicy);
149         if (*oldpolicy == MPOL_DEFAULT) {
150                 numa_set_localalloc();
151         } else if (set_mempolicy(*oldpolicy, oldmask->maskp,
152                                  oldmask->size + 1) < 0) {
153                 RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
154                         strerror(errno));
155                 numa_set_localalloc();
156         }
157         numa_free_cpumask(oldmask);
158 }
159 #endif
160
161 static struct msl_entry *
162 get_msl_entry_by_idx(unsigned int list_idx)
163 {
164         struct msl_entry *te;
165
166         rte_spinlock_lock(&tailq_lock);
167
168         TAILQ_FOREACH(te, &msl_entry_list, next) {
169                 if (te->msl_idx == list_idx)
170                         break;
171         }
172         if (te == NULL) {
173                 /* doesn't exist, so create it and set fd to -1 */
174
175                 te = malloc(sizeof(*te));
176                 if (te == NULL) {
177                         RTE_LOG(ERR, EAL, "%s(): cannot allocate tailq entry for memseg list\n",
178                                 __func__);
179                         goto unlock;
180                 }
181                 te->msl_idx = list_idx;
182                 te->fd = -1;
183                 TAILQ_INSERT_TAIL(&msl_entry_list, te, next);
184         }
185 unlock:
186         rte_spinlock_unlock(&tailq_lock);
187         return te;
188 }
189
190 /*
191  * uses fstat to report the size of a file on disk
192  */
193 static off_t
194 get_file_size(int fd)
195 {
196         struct stat st;
197         if (fstat(fd, &st) < 0)
198                 return 0;
199         return st.st_size;
200 }
201
202 /*
203  * uses fstat to check if file size on disk is zero (regular fstat won't show
204  * true file size due to how fallocate works)
205  */
206 static bool
207 is_zero_length(int fd)
208 {
209         struct stat st;
210         if (fstat(fd, &st) < 0)
211                 return false;
212         return st.st_blocks == 0;
213 }
214
215 /* we cannot use rte_memseg_list_walk() here because we will be holding a
216  * write lock whenever we enter every function in this file, however copying
217  * the same iteration code everywhere is not ideal as well. so, use a lockless
218  * copy of memseg list walk here.
219  */
220 static int
221 memseg_list_walk_thread_unsafe(rte_memseg_list_walk_t func, void *arg)
222 {
223         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
224         int i, ret = 0;
225
226         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
227                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
228
229                 if (msl->base_va == NULL)
230                         continue;
231
232                 ret = func(msl, arg);
233                 if (ret < 0)
234                         return -1;
235                 if (ret > 0)
236                         return 1;
237         }
238         return 0;
239 }
240
241 static int
242 get_seg_fd(char *path, int buflen, struct hugepage_info *hi,
243                 unsigned int list_idx, unsigned int seg_idx)
244 {
245         int fd;
246
247         if (internal_config.single_file_segments) {
248                 /*
249                  * try to find a tailq entry, for this memseg list, or create
250                  * one if it doesn't exist.
251                  */
252                 struct msl_entry *te = get_msl_entry_by_idx(list_idx);
253                 if (te == NULL) {
254                         RTE_LOG(ERR, EAL, "%s(): cannot allocate tailq entry for memseg list\n",
255                                 __func__);
256                         return -1;
257                 } else if (te->fd < 0) {
258                         /* create a hugepage file */
259                         eal_get_hugefile_path(path, buflen, hi->hugedir,
260                                         list_idx);
261                         fd = open(path, O_CREAT | O_RDWR, 0600);
262                         if (fd < 0) {
263                                 RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n",
264                                         __func__, strerror(errno));
265                                 return -1;
266                         }
267                         te->fd = fd;
268                 } else {
269                         fd = te->fd;
270                 }
271         } else {
272                 /* one file per page, just create it */
273                 eal_get_hugefile_path(path, buflen, hi->hugedir,
274                                 list_idx * RTE_MAX_MEMSEG_PER_LIST + seg_idx);
275                 fd = open(path, O_CREAT | O_RDWR, 0600);
276                 if (fd < 0) {
277                         RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n", __func__,
278                                         strerror(errno));
279                         return -1;
280                 }
281         }
282         return fd;
283 }
284
285 /* returns 1 on successful lock, 0 on unsuccessful lock, -1 on error */
286 static int lock(int fd, uint64_t offset, uint64_t len, int type)
287 {
288         struct flock lck;
289         int ret;
290
291         memset(&lck, 0, sizeof(lck));
292
293         lck.l_type = type;
294         lck.l_whence = SEEK_SET;
295         lck.l_start = offset;
296         lck.l_len = len;
297
298         ret = fcntl(fd, F_SETLK, &lck);
299
300         if (ret && (errno == EAGAIN || errno == EACCES)) {
301                 /* locked by another process, not an error */
302                 return 0;
303         } else if (ret) {
304                 RTE_LOG(ERR, EAL, "%s(): error calling fcntl(): %s\n",
305                         __func__, strerror(errno));
306                 /* we've encountered an unexpected error */
307                 return -1;
308         }
309         return 1;
310 }
311
312 static int
313 resize_hugefile(int fd, uint64_t fa_offset, uint64_t page_sz,
314                 bool grow)
315 {
316         bool again = false;
317         do {
318                 if (fallocate_supported == 0) {
319                         /* we cannot deallocate memory if fallocate() is not
320                          * supported, but locks are still needed to prevent
321                          * primary process' initialization from clearing out
322                          * huge pages used by this process.
323                          */
324
325                         if (!grow) {
326                                 RTE_LOG(DEBUG, EAL, "%s(): fallocate not supported, not freeing page back to the system\n",
327                                         __func__);
328                                 return -1;
329                         }
330                         uint64_t new_size = fa_offset + page_sz;
331                         uint64_t cur_size = get_file_size(fd);
332
333                         /* fallocate isn't supported, fall back to ftruncate */
334                         if (new_size > cur_size &&
335                                         ftruncate(fd, new_size) < 0) {
336                                 RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
337                                         __func__, strerror(errno));
338                                 return -1;
339                         }
340                         /* not being able to take out a read lock is an error */
341                         if (lock(fd, fa_offset, page_sz, F_RDLCK) != 1)
342                                 return -1;
343                 } else {
344                         int flags = grow ? 0 : FALLOC_FL_PUNCH_HOLE |
345                                         FALLOC_FL_KEEP_SIZE;
346                         int ret;
347
348                         /* if fallocate() is supported, we need to take out a
349                          * read lock on allocate (to prevent other processes
350                          * from deallocating this page), and take out a write
351                          * lock on deallocate (to ensure nobody else is using
352                          * this page).
353                          *
354                          * we can't use flock() for this, as we actually need to
355                          * lock part of the file, not the entire file.
356                          */
357
358                         if (!grow) {
359                                 ret = lock(fd, fa_offset, page_sz, F_WRLCK);
360
361                                 if (ret < 0)
362                                         return -1;
363                                 else if (ret == 0)
364                                         /* failed to lock, not an error */
365                                         return 0;
366                         }
367                         if (fallocate(fd, flags, fa_offset, page_sz) < 0) {
368                                 if (fallocate_supported == -1 &&
369                                                 errno == ENOTSUP) {
370                                         RTE_LOG(ERR, EAL, "%s(): fallocate() not supported, hugepage deallocation will be disabled\n",
371                                                 __func__);
372                                         again = true;
373                                         fallocate_supported = 0;
374                                 } else {
375                                         RTE_LOG(DEBUG, EAL, "%s(): fallocate() failed: %s\n",
376                                                 __func__,
377                                                 strerror(errno));
378                                         return -1;
379                                 }
380                         } else {
381                                 fallocate_supported = 1;
382
383                                 if (grow) {
384                                         /* if can't read lock, it's an error */
385                                         if (lock(fd, fa_offset, page_sz,
386                                                         F_RDLCK) != 1)
387                                                 return -1;
388                                 } else {
389                                         /* if can't unlock, it's an error */
390                                         if (lock(fd, fa_offset, page_sz,
391                                                         F_UNLCK) != 1)
392                                                 return -1;
393                                 }
394                         }
395                 }
396         } while (again);
397         return 0;
398 }
399
400 static int
401 alloc_seg(struct rte_memseg *ms, void *addr, int socket_id,
402                 struct hugepage_info *hi, unsigned int list_idx,
403                 unsigned int seg_idx)
404 {
405 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
406         int cur_socket_id = 0;
407 #endif
408         uint64_t map_offset;
409         char path[PATH_MAX];
410         int ret = 0;
411         int fd;
412         size_t alloc_sz;
413
414         fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
415         if (fd < 0)
416                 return -1;
417
418         alloc_sz = hi->hugepage_sz;
419         if (internal_config.single_file_segments) {
420                 map_offset = seg_idx * alloc_sz;
421                 ret = resize_hugefile(fd, map_offset, alloc_sz, true);
422                 if (ret < 0)
423                         goto resized;
424         } else {
425                 map_offset = 0;
426                 if (ftruncate(fd, alloc_sz) < 0) {
427                         RTE_LOG(DEBUG, EAL, "%s(): ftruncate() failed: %s\n",
428                                 __func__, strerror(errno));
429                         goto resized;
430                 }
431                 /* we've allocated a page - take out a read lock. we're using
432                  * fcntl() locks rather than flock() here because doing that
433                  * gives us one huge advantage - fcntl() locks are per-process,
434                  * not per-file descriptor, which means that we don't have to
435                  * keep the original fd's around to keep a lock on the file.
436                  *
437                  * this is useful, because when it comes to unmapping pages, we
438                  * will have to take out a write lock (to figure out if another
439                  * process still has this page mapped), and to do itwith flock()
440                  * we'll have to use original fd, as lock is associated with
441                  * that particular fd. with fcntl(), this is not necessary - we
442                  * can open a new fd and use fcntl() on that.
443                  */
444                 ret = lock(fd, map_offset, alloc_sz, F_RDLCK);
445
446                 /* this should not fail */
447                 if (ret != 1) {
448                         RTE_LOG(ERR, EAL, "%s(): error locking file: %s\n",
449                                 __func__,
450                                 strerror(errno));
451                         goto resized;
452                 }
453         }
454
455         /*
456          * map the segment, and populate page tables, the kernel fills this
457          * segment with zeros if it's a new page.
458          */
459         void *va = mmap(addr, alloc_sz, PROT_READ | PROT_WRITE,
460                         MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd, map_offset);
461
462         if (va == MAP_FAILED) {
463                 RTE_LOG(DEBUG, EAL, "%s(): mmap() failed: %s\n", __func__,
464                         strerror(errno));
465                 goto resized;
466         }
467         if (va != addr) {
468                 RTE_LOG(DEBUG, EAL, "%s(): wrong mmap() address\n", __func__);
469                 goto mapped;
470         }
471
472         rte_iova_t iova = rte_mem_virt2iova(addr);
473         if (iova == RTE_BAD_PHYS_ADDR) {
474                 RTE_LOG(DEBUG, EAL, "%s(): can't get IOVA addr\n",
475                         __func__);
476                 goto mapped;
477         }
478
479 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
480         move_pages(getpid(), 1, &addr, NULL, &cur_socket_id, 0);
481
482         if (cur_socket_id != socket_id) {
483                 RTE_LOG(DEBUG, EAL,
484                                 "%s(): allocation happened on wrong socket (wanted %d, got %d)\n",
485                         __func__, socket_id, cur_socket_id);
486                 goto mapped;
487         }
488 #endif
489
490         /* In linux, hugetlb limitations, like cgroup, are
491          * enforced at fault time instead of mmap(), even
492          * with the option of MAP_POPULATE. Kernel will send
493          * a SIGBUS signal. To avoid to be killed, save stack
494          * environment here, if SIGBUS happens, we can jump
495          * back here.
496          */
497         if (huge_wrap_sigsetjmp()) {
498                 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more hugepages of size %uMB\n",
499                         (unsigned int)(alloc_sz >> 20));
500                 goto mapped;
501         }
502         /* for non-single file segments, we can close fd here */
503         if (!internal_config.single_file_segments)
504                 close(fd);
505
506         *(int *)addr = *(int *)addr;
507
508         ms->addr = addr;
509         ms->hugepage_sz = alloc_sz;
510         ms->len = alloc_sz;
511         ms->nchannel = rte_memory_get_nchannel();
512         ms->nrank = rte_memory_get_nrank();
513         ms->iova = iova;
514         ms->socket_id = socket_id;
515
516         return 0;
517
518 mapped:
519         munmap(addr, alloc_sz);
520 resized:
521         if (internal_config.single_file_segments) {
522                 resize_hugefile(fd, map_offset, alloc_sz, false);
523                 if (is_zero_length(fd)) {
524                         struct msl_entry *te = get_msl_entry_by_idx(list_idx);
525                         /* te->fd is equivalent to fd */
526                         if (te != NULL && te->fd >= 0)
527                                 te->fd = -1;
528                         /* ignore errors, can't make it any worse */
529                         unlink(path);
530                         close(fd);
531                 }
532                 /* if we're not removing the file, fd stays in the tailq */
533         } else {
534                 close(fd);
535                 unlink(path);
536         }
537         return -1;
538 }
539
540 static int
541 free_seg(struct rte_memseg *ms, struct hugepage_info *hi,
542                 unsigned int list_idx, unsigned int seg_idx)
543 {
544         uint64_t map_offset;
545         char path[PATH_MAX];
546         int fd, ret;
547
548         /* erase page data */
549         memset(ms->addr, 0, ms->len);
550
551         if (mmap(ms->addr, ms->len, PROT_READ,
552                         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) ==
553                                 MAP_FAILED) {
554                 RTE_LOG(DEBUG, EAL, "couldn't unmap page\n");
555                 return -1;
556         }
557
558         fd = get_seg_fd(path, sizeof(path), hi, list_idx, seg_idx);
559         if (fd < 0)
560                 return -1;
561
562         if (internal_config.single_file_segments) {
563                 map_offset = seg_idx * ms->len;
564                 if (resize_hugefile(fd, map_offset, ms->len, false))
565                         return -1;
566                 /* if file is zero-length, we've already shrunk it, so it's
567                  * safe to remove.
568                  */
569                 if (is_zero_length(fd)) {
570                         struct msl_entry *te = get_msl_entry_by_idx(list_idx);
571                         /* te->fd is equivalent to fd */
572                         if (te != NULL && te->fd >= 0)
573                                 te->fd = -1;
574                         unlink(path);
575                         close(fd);
576                 }
577                 /* if we're not removing the file, fd stays in the tailq */
578                 ret = 0;
579         } else {
580                 /* if we're able to take out a write lock, we're the last one
581                  * holding onto this page.
582                  */
583
584                 ret = lock(fd, 0, ms->len, F_WRLCK);
585                 if (ret >= 0) {
586                         /* no one else is using this page */
587                         if (ret == 1)
588                                 unlink(path);
589                         ret = lock(fd, 0, ms->len, F_UNLCK);
590                         if (ret != 1)
591                                 RTE_LOG(ERR, EAL, "%s(): unable to unlock file %s\n",
592                                         __func__, path);
593                 }
594                 close(fd);
595         }
596
597         memset(ms, 0, sizeof(*ms));
598
599         return ret;
600 }
601
602 struct alloc_walk_param {
603         struct hugepage_info *hi;
604         struct rte_memseg **ms;
605         size_t page_sz;
606         unsigned int segs_allocated;
607         unsigned int n_segs;
608         int socket;
609         bool exact;
610 };
611 static int
612 alloc_seg_walk(const struct rte_memseg_list *msl, void *arg)
613 {
614         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
615         struct alloc_walk_param *wa = arg;
616         struct rte_memseg_list *cur_msl;
617         size_t page_sz;
618         int cur_idx, start_idx, j;
619         unsigned int msl_idx, need, i;
620
621         if (msl->page_sz != wa->page_sz)
622                 return 0;
623         if (msl->socket_id != wa->socket)
624                 return 0;
625
626         page_sz = (size_t)msl->page_sz;
627
628         msl_idx = msl - mcfg->memsegs;
629         cur_msl = &mcfg->memsegs[msl_idx];
630
631         need = wa->n_segs;
632
633         /* try finding space in memseg list */
634         cur_idx = rte_fbarray_find_next_n_free(&cur_msl->memseg_arr, 0, need);
635         if (cur_idx < 0)
636                 return 0;
637         start_idx = cur_idx;
638
639         for (i = 0; i < need; i++, cur_idx++) {
640                 struct rte_memseg *cur;
641                 void *map_addr;
642
643                 cur = rte_fbarray_get(&cur_msl->memseg_arr, cur_idx);
644                 map_addr = RTE_PTR_ADD(cur_msl->base_va,
645                                 cur_idx * page_sz);
646
647                 if (alloc_seg(cur, map_addr, wa->socket, wa->hi,
648                                 msl_idx, cur_idx)) {
649                         RTE_LOG(DEBUG, EAL, "attempted to allocate %i segments, but only %i were allocated\n",
650                                 need, i);
651
652                         /* if exact number wasn't requested, stop */
653                         if (!wa->exact)
654                                 goto out;
655
656                         /* clean up */
657                         for (j = start_idx; j < cur_idx; j++) {
658                                 struct rte_memseg *tmp;
659                                 struct rte_fbarray *arr =
660                                                 &cur_msl->memseg_arr;
661
662                                 tmp = rte_fbarray_get(arr, j);
663                                 if (free_seg(tmp, wa->hi, msl_idx,
664                                                 start_idx + j)) {
665                                         RTE_LOG(ERR, EAL, "Cannot free page\n");
666                                         continue;
667                                 }
668
669                                 rte_fbarray_set_free(arr, j);
670                         }
671                         /* clear the list */
672                         if (wa->ms)
673                                 memset(wa->ms, 0, sizeof(*wa->ms) * wa->n_segs);
674                         return -1;
675                 }
676                 if (wa->ms)
677                         wa->ms[i] = cur;
678
679                 rte_fbarray_set_used(&cur_msl->memseg_arr, cur_idx);
680         }
681 out:
682         wa->segs_allocated = i;
683         if (i > 0)
684                 cur_msl->version++;
685         return 1;
686 }
687
688 struct free_walk_param {
689         struct hugepage_info *hi;
690         struct rte_memseg *ms;
691 };
692 static int
693 free_seg_walk(const struct rte_memseg_list *msl, void *arg)
694 {
695         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
696         struct rte_memseg_list *found_msl;
697         struct free_walk_param *wa = arg;
698         uintptr_t start_addr, end_addr;
699         int msl_idx, seg_idx;
700
701         start_addr = (uintptr_t) msl->base_va;
702         end_addr = start_addr + msl->memseg_arr.len * (size_t)msl->page_sz;
703
704         if ((uintptr_t)wa->ms->addr < start_addr ||
705                         (uintptr_t)wa->ms->addr >= end_addr)
706                 return 0;
707
708         msl_idx = msl - mcfg->memsegs;
709         seg_idx = RTE_PTR_DIFF(wa->ms->addr, start_addr) / msl->page_sz;
710
711         /* msl is const */
712         found_msl = &mcfg->memsegs[msl_idx];
713
714         found_msl->version++;
715
716         rte_fbarray_set_free(&found_msl->memseg_arr, seg_idx);
717
718         if (free_seg(wa->ms, wa->hi, msl_idx, seg_idx))
719                 return -1;
720
721         return 1;
722 }
723
724 int
725 eal_memalloc_alloc_seg_bulk(struct rte_memseg **ms, int n_segs, size_t page_sz,
726                 int socket, bool exact)
727 {
728         int i, ret = -1;
729 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
730         bool have_numa = false;
731         int oldpolicy;
732         struct bitmask *oldmask;
733 #endif
734         struct alloc_walk_param wa;
735         struct hugepage_info *hi = NULL;
736
737         memset(&wa, 0, sizeof(wa));
738
739         /* dynamic allocation not supported in legacy mode */
740         if (internal_config.legacy_mem)
741                 return -1;
742
743         for (i = 0; i < (int) RTE_DIM(internal_config.hugepage_info); i++) {
744                 if (page_sz ==
745                                 internal_config.hugepage_info[i].hugepage_sz) {
746                         hi = &internal_config.hugepage_info[i];
747                         break;
748                 }
749         }
750         if (!hi) {
751                 RTE_LOG(ERR, EAL, "%s(): can't find relevant hugepage_info entry\n",
752                         __func__);
753                 return -1;
754         }
755
756 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
757         if (check_numa()) {
758                 oldmask = numa_allocate_nodemask();
759                 prepare_numa(&oldpolicy, oldmask, socket);
760                 have_numa = true;
761         }
762 #endif
763
764         wa.exact = exact;
765         wa.hi = hi;
766         wa.ms = ms;
767         wa.n_segs = n_segs;
768         wa.page_sz = page_sz;
769         wa.socket = socket;
770         wa.segs_allocated = 0;
771
772         ret = memseg_list_walk_thread_unsafe(alloc_seg_walk, &wa);
773         if (ret == 0) {
774                 RTE_LOG(ERR, EAL, "%s(): couldn't find suitable memseg_list\n",
775                         __func__);
776                 ret = -1;
777         } else if (ret > 0) {
778                 ret = (int)wa.segs_allocated;
779         }
780
781 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
782         if (have_numa)
783                 resotre_numa(&oldpolicy, oldmask);
784 #endif
785         return ret;
786 }
787
788 struct rte_memseg *
789 eal_memalloc_alloc_seg(size_t page_sz, int socket)
790 {
791         struct rte_memseg *ms;
792         if (eal_memalloc_alloc_seg_bulk(&ms, 1, page_sz, socket, true) < 0)
793                 return NULL;
794         /* return pointer to newly allocated memseg */
795         return ms;
796 }
797
798 int
799 eal_memalloc_free_seg_bulk(struct rte_memseg **ms, int n_segs)
800 {
801         int seg, ret = 0;
802
803         /* dynamic free not supported in legacy mode */
804         if (internal_config.legacy_mem)
805                 return -1;
806
807         for (seg = 0; seg < n_segs; seg++) {
808                 struct rte_memseg *cur = ms[seg];
809                 struct hugepage_info *hi = NULL;
810                 struct free_walk_param wa;
811                 int i, walk_res;
812
813                 /* if this page is marked as unfreeable, fail */
814                 if (cur->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
815                         RTE_LOG(DEBUG, EAL, "Page is not allowed to be freed\n");
816                         ret = -1;
817                         continue;
818                 }
819
820                 memset(&wa, 0, sizeof(wa));
821
822                 for (i = 0; i < (int)RTE_DIM(internal_config.hugepage_info);
823                                 i++) {
824                         hi = &internal_config.hugepage_info[i];
825                         if (cur->hugepage_sz == hi->hugepage_sz)
826                                 break;
827                 }
828                 if (i == (int)RTE_DIM(internal_config.hugepage_info)) {
829                         RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
830                         ret = -1;
831                         continue;
832                 }
833
834                 wa.ms = cur;
835                 wa.hi = hi;
836
837                 walk_res = memseg_list_walk_thread_unsafe(free_seg_walk, &wa);
838                 if (walk_res == 1)
839                         continue;
840                 if (walk_res == 0)
841                         RTE_LOG(ERR, EAL, "Couldn't find memseg list\n");
842                 ret = -1;
843         }
844         return ret;
845 }
846
847 int
848 eal_memalloc_free_seg(struct rte_memseg *ms)
849 {
850         /* dynamic free not supported in legacy mode */
851         if (internal_config.legacy_mem)
852                 return -1;
853
854         return eal_memalloc_free_seg_bulk(&ms, 1);
855 }
856
857 static int
858 sync_chunk(struct rte_memseg_list *primary_msl,
859                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
860                 unsigned int msl_idx, bool used, int start, int end)
861 {
862         struct rte_fbarray *l_arr, *p_arr;
863         int i, ret, chunk_len, diff_len;
864
865         l_arr = &local_msl->memseg_arr;
866         p_arr = &primary_msl->memseg_arr;
867
868         /* we need to aggregate allocations/deallocations into bigger chunks,
869          * as we don't want to spam the user with per-page callbacks.
870          *
871          * to avoid any potential issues, we also want to trigger
872          * deallocation callbacks *before* we actually deallocate
873          * memory, so that the user application could wrap up its use
874          * before it goes away.
875          */
876
877         chunk_len = end - start;
878
879         /* find how many contiguous pages we can map/unmap for this chunk */
880         diff_len = used ?
881                         rte_fbarray_find_contig_free(l_arr, start) :
882                         rte_fbarray_find_contig_used(l_arr, start);
883
884         /* has to be at least one page */
885         if (diff_len < 1)
886                 return -1;
887
888         diff_len = RTE_MIN(chunk_len, diff_len);
889
890         /* if we are freeing memory, notify the application */
891         if (!used) {
892                 struct rte_memseg *ms;
893                 void *start_va;
894                 size_t len, page_sz;
895
896                 ms = rte_fbarray_get(l_arr, start);
897                 start_va = ms->addr;
898                 page_sz = (size_t)primary_msl->page_sz;
899                 len = page_sz * diff_len;
900
901                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
902                                 start_va, len);
903         }
904
905         for (i = 0; i < diff_len; i++) {
906                 struct rte_memseg *p_ms, *l_ms;
907                 int seg_idx = start + i;
908
909                 l_ms = rte_fbarray_get(l_arr, seg_idx);
910                 p_ms = rte_fbarray_get(p_arr, seg_idx);
911
912                 if (l_ms == NULL || p_ms == NULL)
913                         return -1;
914
915                 if (used) {
916                         ret = alloc_seg(l_ms, p_ms->addr,
917                                         p_ms->socket_id, hi,
918                                         msl_idx, seg_idx);
919                         if (ret < 0)
920                                 return -1;
921                         rte_fbarray_set_used(l_arr, seg_idx);
922                 } else {
923                         ret = free_seg(l_ms, hi, msl_idx, seg_idx);
924                         rte_fbarray_set_free(l_arr, seg_idx);
925                         if (ret < 0)
926                                 return -1;
927                 }
928         }
929
930         /* if we just allocated memory, notify the application */
931         if (used) {
932                 struct rte_memseg *ms;
933                 void *start_va;
934                 size_t len, page_sz;
935
936                 ms = rte_fbarray_get(l_arr, start);
937                 start_va = ms->addr;
938                 page_sz = (size_t)primary_msl->page_sz;
939                 len = page_sz * diff_len;
940
941                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
942                                 start_va, len);
943         }
944
945         /* calculate how much we can advance until next chunk */
946         diff_len = used ?
947                         rte_fbarray_find_contig_used(l_arr, start) :
948                         rte_fbarray_find_contig_free(l_arr, start);
949         ret = RTE_MIN(chunk_len, diff_len);
950
951         return ret;
952 }
953
954 static int
955 sync_status(struct rte_memseg_list *primary_msl,
956                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
957                 unsigned int msl_idx, bool used)
958 {
959         struct rte_fbarray *l_arr, *p_arr;
960         int p_idx, l_chunk_len, p_chunk_len, ret;
961         int start, end;
962
963         /* this is a little bit tricky, but the basic idea is - walk both lists
964          * and spot any places where there are discrepancies. walking both lists
965          * and noting discrepancies in a single go is a hard problem, so we do
966          * it in two passes - first we spot any places where allocated segments
967          * mismatch (i.e. ensure that everything that's allocated in the primary
968          * is also allocated in the secondary), and then we do it by looking at
969          * free segments instead.
970          *
971          * we also need to aggregate changes into chunks, as we have to call
972          * callbacks per allocation, not per page.
973          */
974         l_arr = &local_msl->memseg_arr;
975         p_arr = &primary_msl->memseg_arr;
976
977         if (used)
978                 p_idx = rte_fbarray_find_next_used(p_arr, 0);
979         else
980                 p_idx = rte_fbarray_find_next_free(p_arr, 0);
981
982         while (p_idx >= 0) {
983                 int next_chunk_search_idx;
984
985                 if (used) {
986                         p_chunk_len = rte_fbarray_find_contig_used(p_arr,
987                                         p_idx);
988                         l_chunk_len = rte_fbarray_find_contig_used(l_arr,
989                                         p_idx);
990                 } else {
991                         p_chunk_len = rte_fbarray_find_contig_free(p_arr,
992                                         p_idx);
993                         l_chunk_len = rte_fbarray_find_contig_free(l_arr,
994                                         p_idx);
995                 }
996                 /* best case scenario - no differences (or bigger, which will be
997                  * fixed during next iteration), look for next chunk
998                  */
999                 if (l_chunk_len >= p_chunk_len) {
1000                         next_chunk_search_idx = p_idx + p_chunk_len;
1001                         goto next_chunk;
1002                 }
1003
1004                 /* if both chunks start at the same point, skip parts we know
1005                  * are identical, and sync the rest. each call to sync_chunk
1006                  * will only sync contiguous segments, so we need to call this
1007                  * until we are sure there are no more differences in this
1008                  * chunk.
1009                  */
1010                 start = p_idx + l_chunk_len;
1011                 end = p_idx + p_chunk_len;
1012                 do {
1013                         ret = sync_chunk(primary_msl, local_msl, hi, msl_idx,
1014                                         used, start, end);
1015                         start += ret;
1016                 } while (start < end && ret >= 0);
1017                 /* if ret is negative, something went wrong */
1018                 if (ret < 0)
1019                         return -1;
1020
1021                 next_chunk_search_idx = p_idx + p_chunk_len;
1022 next_chunk:
1023                 /* skip to end of this chunk */
1024                 if (used) {
1025                         p_idx = rte_fbarray_find_next_used(p_arr,
1026                                         next_chunk_search_idx);
1027                 } else {
1028                         p_idx = rte_fbarray_find_next_free(p_arr,
1029                                         next_chunk_search_idx);
1030                 }
1031         }
1032         return 0;
1033 }
1034
1035 static int
1036 sync_existing(struct rte_memseg_list *primary_msl,
1037                 struct rte_memseg_list *local_msl, struct hugepage_info *hi,
1038                 unsigned int msl_idx)
1039 {
1040         int ret;
1041
1042         /* ensure all allocated space is the same in both lists */
1043         ret = sync_status(primary_msl, local_msl, hi, msl_idx, true);
1044         if (ret < 0)
1045                 return -1;
1046
1047         /* ensure all unallocated space is the same in both lists */
1048         ret = sync_status(primary_msl, local_msl, hi, msl_idx, false);
1049         if (ret < 0)
1050                 return -1;
1051
1052         /* update version number */
1053         local_msl->version = primary_msl->version;
1054
1055         return 0;
1056 }
1057
1058 static int
1059 sync_walk(const struct rte_memseg_list *msl, void *arg __rte_unused)
1060 {
1061         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1062         struct rte_memseg_list *primary_msl, *local_msl;
1063         struct hugepage_info *hi = NULL;
1064         unsigned int i;
1065         int msl_idx;
1066         bool new_msl = false;
1067
1068         msl_idx = msl - mcfg->memsegs;
1069         primary_msl = &mcfg->memsegs[msl_idx];
1070         local_msl = &local_memsegs[msl_idx];
1071
1072         /* check if secondary has this memseg list set up */
1073         if (local_msl->base_va == NULL) {
1074                 char name[PATH_MAX];
1075                 int ret;
1076                 new_msl = true;
1077
1078                 /* create distinct fbarrays for each secondary */
1079                 snprintf(name, RTE_FBARRAY_NAME_LEN, "%s_%i",
1080                         primary_msl->memseg_arr.name, getpid());
1081
1082                 ret = rte_fbarray_init(&local_msl->memseg_arr, name,
1083                         primary_msl->memseg_arr.len,
1084                         primary_msl->memseg_arr.elt_sz);
1085                 if (ret < 0) {
1086                         RTE_LOG(ERR, EAL, "Cannot initialize local memory map\n");
1087                         return -1;
1088                 }
1089
1090                 local_msl->base_va = primary_msl->base_va;
1091         }
1092
1093         for (i = 0; i < RTE_DIM(internal_config.hugepage_info); i++) {
1094                 uint64_t cur_sz =
1095                         internal_config.hugepage_info[i].hugepage_sz;
1096                 uint64_t msl_sz = primary_msl->page_sz;
1097                 if (msl_sz == cur_sz) {
1098                         hi = &internal_config.hugepage_info[i];
1099                         break;
1100                 }
1101         }
1102         if (!hi) {
1103                 RTE_LOG(ERR, EAL, "Can't find relevant hugepage_info entry\n");
1104                 return -1;
1105         }
1106
1107         /* if versions don't match or if we have just allocated a new
1108          * memseg list, synchronize everything
1109          */
1110         if ((new_msl || local_msl->version != primary_msl->version) &&
1111                         sync_existing(primary_msl, local_msl, hi, msl_idx))
1112                 return -1;
1113         return 0;
1114 }
1115
1116
1117 int
1118 eal_memalloc_sync_with_primary(void)
1119 {
1120         /* nothing to be done in primary */
1121         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1122                 return 0;
1123
1124         if (memseg_list_walk_thread_unsafe(sync_walk, NULL))
1125                 return -1;
1126         return 0;
1127 }