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