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