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