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