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