e0baabbebe0883220864b56ecae16d2d6e08c863
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_memory.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation.
3  * Copyright(c) 2013 6WIND S.A.
4  */
5
6 #define _FILE_OFFSET_BITS 64
7 #include <errno.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <stdint.h>
13 #include <inttypes.h>
14 #include <string.h>
15 #include <sys/mman.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/queue.h>
19 #include <sys/file.h>
20 #include <unistd.h>
21 #include <limits.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
31 #include <rte_errno.h>
32 #include <rte_log.h>
33 #include <rte_memory.h>
34 #include <rte_launch.h>
35 #include <rte_eal.h>
36 #include <rte_eal_memconfig.h>
37 #include <rte_per_lcore.h>
38 #include <rte_lcore.h>
39 #include <rte_common.h>
40 #include <rte_string_fns.h>
41
42 #include "eal_private.h"
43 #include "eal_memalloc.h"
44 #include "eal_internal_cfg.h"
45 #include "eal_filesystem.h"
46 #include "eal_hugepages.h"
47
48 #define PFN_MASK_SIZE   8
49
50 /**
51  * @file
52  * Huge page mapping under linux
53  *
54  * To reserve a big contiguous amount of memory, we use the hugepage
55  * feature of linux. For that, we need to have hugetlbfs mounted. This
56  * code will create many files in this directory (one per page) and
57  * map them in virtual memory. For each page, we will retrieve its
58  * physical address and remap it in order to have a virtual contiguous
59  * zone as well as a physical contiguous zone.
60  */
61
62 static bool phys_addrs_available = true;
63
64 #define RANDOMIZE_VA_SPACE_FILE "/proc/sys/kernel/randomize_va_space"
65
66 static void
67 test_phys_addrs_available(void)
68 {
69         uint64_t tmp;
70         phys_addr_t physaddr;
71
72         if (!rte_eal_has_hugepages()) {
73                 RTE_LOG(ERR, EAL,
74                         "Started without hugepages support, physical addresses not available\n");
75                 phys_addrs_available = false;
76                 return;
77         }
78
79         physaddr = rte_mem_virt2phy(&tmp);
80         if (physaddr == RTE_BAD_PHYS_ADDR) {
81                 if (rte_eal_iova_mode() == RTE_IOVA_PA)
82                         RTE_LOG(ERR, EAL,
83                                 "Cannot obtain physical addresses: %s. "
84                                 "Only vfio will function.\n",
85                                 strerror(errno));
86                 phys_addrs_available = false;
87         }
88 }
89
90 /*
91  * Get physical address of any mapped virtual address in the current process.
92  */
93 phys_addr_t
94 rte_mem_virt2phy(const void *virtaddr)
95 {
96         int fd, retval;
97         uint64_t page, physaddr;
98         unsigned long virt_pfn;
99         int page_size;
100         off_t offset;
101
102         /* Cannot parse /proc/self/pagemap, no need to log errors everywhere */
103         if (!phys_addrs_available)
104                 return RTE_BAD_IOVA;
105
106         /* standard page size */
107         page_size = getpagesize();
108
109         fd = open("/proc/self/pagemap", O_RDONLY);
110         if (fd < 0) {
111                 RTE_LOG(ERR, EAL, "%s(): cannot open /proc/self/pagemap: %s\n",
112                         __func__, strerror(errno));
113                 return RTE_BAD_IOVA;
114         }
115
116         virt_pfn = (unsigned long)virtaddr / page_size;
117         offset = sizeof(uint64_t) * virt_pfn;
118         if (lseek(fd, offset, SEEK_SET) == (off_t) -1) {
119                 RTE_LOG(ERR, EAL, "%s(): seek error in /proc/self/pagemap: %s\n",
120                                 __func__, strerror(errno));
121                 close(fd);
122                 return RTE_BAD_IOVA;
123         }
124
125         retval = read(fd, &page, PFN_MASK_SIZE);
126         close(fd);
127         if (retval < 0) {
128                 RTE_LOG(ERR, EAL, "%s(): cannot read /proc/self/pagemap: %s\n",
129                                 __func__, strerror(errno));
130                 return RTE_BAD_IOVA;
131         } else if (retval != PFN_MASK_SIZE) {
132                 RTE_LOG(ERR, EAL, "%s(): read %d bytes from /proc/self/pagemap "
133                                 "but expected %d:\n",
134                                 __func__, retval, PFN_MASK_SIZE);
135                 return RTE_BAD_IOVA;
136         }
137
138         /*
139          * the pfn (page frame number) are bits 0-54 (see
140          * pagemap.txt in linux Documentation)
141          */
142         if ((page & 0x7fffffffffffffULL) == 0)
143                 return RTE_BAD_IOVA;
144
145         physaddr = ((page & 0x7fffffffffffffULL) * page_size)
146                 + ((unsigned long)virtaddr % page_size);
147
148         return physaddr;
149 }
150
151 rte_iova_t
152 rte_mem_virt2iova(const void *virtaddr)
153 {
154         if (rte_eal_iova_mode() == RTE_IOVA_VA)
155                 return (uintptr_t)virtaddr;
156         return rte_mem_virt2phy(virtaddr);
157 }
158
159 /*
160  * For each hugepage in hugepg_tbl, fill the physaddr value. We find
161  * it by browsing the /proc/self/pagemap special file.
162  */
163 static int
164 find_physaddrs(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
165 {
166         unsigned int i;
167         phys_addr_t addr;
168
169         for (i = 0; i < hpi->num_pages[0]; i++) {
170                 addr = rte_mem_virt2phy(hugepg_tbl[i].orig_va);
171                 if (addr == RTE_BAD_PHYS_ADDR)
172                         return -1;
173                 hugepg_tbl[i].physaddr = addr;
174         }
175         return 0;
176 }
177
178 /*
179  * For each hugepage in hugepg_tbl, fill the physaddr value sequentially.
180  */
181 static int
182 set_physaddrs(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
183 {
184         unsigned int i;
185         static phys_addr_t addr;
186
187         for (i = 0; i < hpi->num_pages[0]; i++) {
188                 hugepg_tbl[i].physaddr = addr;
189                 addr += hugepg_tbl[i].size;
190         }
191         return 0;
192 }
193
194 /*
195  * Check whether address-space layout randomization is enabled in
196  * the kernel. This is important for multi-process as it can prevent
197  * two processes mapping data to the same virtual address
198  * Returns:
199  *    0 - address space randomization disabled
200  *    1/2 - address space randomization enabled
201  *    negative error code on error
202  */
203 static int
204 aslr_enabled(void)
205 {
206         char c;
207         int retval, fd = open(RANDOMIZE_VA_SPACE_FILE, O_RDONLY);
208         if (fd < 0)
209                 return -errno;
210         retval = read(fd, &c, 1);
211         close(fd);
212         if (retval < 0)
213                 return -errno;
214         if (retval == 0)
215                 return -EIO;
216         switch (c) {
217                 case '0' : return 0;
218                 case '1' : return 1;
219                 case '2' : return 2;
220                 default: return -EINVAL;
221         }
222 }
223
224 static sigjmp_buf huge_jmpenv;
225
226 static void huge_sigbus_handler(int signo __rte_unused)
227 {
228         siglongjmp(huge_jmpenv, 1);
229 }
230
231 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
232  * non-static local variable in the stack frame calling sigsetjmp might be
233  * clobbered by a call to longjmp.
234  */
235 static int huge_wrap_sigsetjmp(void)
236 {
237         return sigsetjmp(huge_jmpenv, 1);
238 }
239
240 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
241 /* Callback for numa library. */
242 void numa_error(char *where)
243 {
244         RTE_LOG(ERR, EAL, "%s failed: %s\n", where, strerror(errno));
245 }
246 #endif
247
248 /*
249  * Mmap all hugepages of hugepage table: it first open a file in
250  * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
251  * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
252  * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
253  * map contiguous physical blocks in contiguous virtual blocks.
254  */
255 static unsigned
256 map_all_hugepages(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi,
257                   uint64_t *essential_memory __rte_unused)
258 {
259         int fd;
260         unsigned i;
261         void *virtaddr;
262 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
263         int node_id = -1;
264         int essential_prev = 0;
265         int oldpolicy;
266         struct bitmask *oldmask = numa_allocate_nodemask();
267         bool have_numa = true;
268         unsigned long maxnode = 0;
269
270         /* Check if kernel supports NUMA. */
271         if (numa_available() != 0) {
272                 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
273                 have_numa = false;
274         }
275
276         if (have_numa) {
277                 RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
278                 if (get_mempolicy(&oldpolicy, oldmask->maskp,
279                                   oldmask->size + 1, 0, 0) < 0) {
280                         RTE_LOG(ERR, EAL,
281                                 "Failed to get current mempolicy: %s. "
282                                 "Assuming MPOL_DEFAULT.\n", strerror(errno));
283                         oldpolicy = MPOL_DEFAULT;
284                 }
285                 for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
286                         if (internal_config.socket_mem[i])
287                                 maxnode = i + 1;
288         }
289 #endif
290
291         for (i = 0; i < hpi->num_pages[0]; i++) {
292                 struct hugepage_file *hf = &hugepg_tbl[i];
293                 uint64_t hugepage_sz = hpi->hugepage_sz;
294
295 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
296                 if (maxnode) {
297                         unsigned int j;
298
299                         for (j = 0; j < maxnode; j++)
300                                 if (essential_memory[j])
301                                         break;
302
303                         if (j == maxnode) {
304                                 node_id = (node_id + 1) % maxnode;
305                                 while (!internal_config.socket_mem[node_id]) {
306                                         node_id++;
307                                         node_id %= maxnode;
308                                 }
309                                 essential_prev = 0;
310                         } else {
311                                 node_id = j;
312                                 essential_prev = essential_memory[j];
313
314                                 if (essential_memory[j] < hugepage_sz)
315                                         essential_memory[j] = 0;
316                                 else
317                                         essential_memory[j] -= hugepage_sz;
318                         }
319
320                         RTE_LOG(DEBUG, EAL,
321                                 "Setting policy MPOL_PREFERRED for socket %d\n",
322                                 node_id);
323                         numa_set_preferred(node_id);
324                 }
325 #endif
326
327                 hf->file_id = i;
328                 hf->size = hugepage_sz;
329                 eal_get_hugefile_path(hf->filepath, sizeof(hf->filepath),
330                                 hpi->hugedir, hf->file_id);
331                 hf->filepath[sizeof(hf->filepath) - 1] = '\0';
332
333                 /* try to create hugepage file */
334                 fd = open(hf->filepath, O_CREAT | O_RDWR, 0600);
335                 if (fd < 0) {
336                         RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n", __func__,
337                                         strerror(errno));
338                         goto out;
339                 }
340
341                 /* map the segment, and populate page tables,
342                  * the kernel fills this segment with zeros. we don't care where
343                  * this gets mapped - we already have contiguous memory areas
344                  * ready for us to map into.
345                  */
346                 virtaddr = mmap(NULL, hugepage_sz, PROT_READ | PROT_WRITE,
347                                 MAP_SHARED | MAP_POPULATE, fd, 0);
348                 if (virtaddr == MAP_FAILED) {
349                         RTE_LOG(DEBUG, EAL, "%s(): mmap failed: %s\n", __func__,
350                                         strerror(errno));
351                         close(fd);
352                         goto out;
353                 }
354
355                 hf->orig_va = virtaddr;
356
357                 /* In linux, hugetlb limitations, like cgroup, are
358                  * enforced at fault time instead of mmap(), even
359                  * with the option of MAP_POPULATE. Kernel will send
360                  * a SIGBUS signal. To avoid to be killed, save stack
361                  * environment here, if SIGBUS happens, we can jump
362                  * back here.
363                  */
364                 if (huge_wrap_sigsetjmp()) {
365                         RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more "
366                                 "hugepages of size %u MB\n",
367                                 (unsigned int)(hugepage_sz / 0x100000));
368                         munmap(virtaddr, hugepage_sz);
369                         close(fd);
370                         unlink(hugepg_tbl[i].filepath);
371 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
372                         if (maxnode)
373                                 essential_memory[node_id] =
374                                         essential_prev;
375 #endif
376                         goto out;
377                 }
378                 *(int *)virtaddr = 0;
379
380                 /* set shared lock on the file. */
381                 if (flock(fd, LOCK_SH) < 0) {
382                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed:%s \n",
383                                 __func__, strerror(errno));
384                         close(fd);
385                         goto out;
386                 }
387
388                 close(fd);
389         }
390
391 out:
392 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
393         if (maxnode) {
394                 RTE_LOG(DEBUG, EAL,
395                         "Restoring previous memory policy: %d\n", oldpolicy);
396                 if (oldpolicy == MPOL_DEFAULT) {
397                         numa_set_localalloc();
398                 } else if (set_mempolicy(oldpolicy, oldmask->maskp,
399                                          oldmask->size + 1) < 0) {
400                         RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
401                                 strerror(errno));
402                         numa_set_localalloc();
403                 }
404         }
405         numa_free_cpumask(oldmask);
406 #endif
407         return i;
408 }
409
410 /*
411  * Parse /proc/self/numa_maps to get the NUMA socket ID for each huge
412  * page.
413  */
414 static int
415 find_numasocket(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
416 {
417         int socket_id;
418         char *end, *nodestr;
419         unsigned i, hp_count = 0;
420         uint64_t virt_addr;
421         char buf[BUFSIZ];
422         char hugedir_str[PATH_MAX];
423         FILE *f;
424
425         f = fopen("/proc/self/numa_maps", "r");
426         if (f == NULL) {
427                 RTE_LOG(NOTICE, EAL, "NUMA support not available"
428                         " consider that all memory is in socket_id 0\n");
429                 return 0;
430         }
431
432         snprintf(hugedir_str, sizeof(hugedir_str),
433                         "%s/%s", hpi->hugedir, internal_config.hugefile_prefix);
434
435         /* parse numa map */
436         while (fgets(buf, sizeof(buf), f) != NULL) {
437
438                 /* ignore non huge page */
439                 if (strstr(buf, " huge ") == NULL &&
440                                 strstr(buf, hugedir_str) == NULL)
441                         continue;
442
443                 /* get zone addr */
444                 virt_addr = strtoull(buf, &end, 16);
445                 if (virt_addr == 0 || end == buf) {
446                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
447                         goto error;
448                 }
449
450                 /* get node id (socket id) */
451                 nodestr = strstr(buf, " N");
452                 if (nodestr == NULL) {
453                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
454                         goto error;
455                 }
456                 nodestr += 2;
457                 end = strstr(nodestr, "=");
458                 if (end == NULL) {
459                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
460                         goto error;
461                 }
462                 end[0] = '\0';
463                 end = NULL;
464
465                 socket_id = strtoul(nodestr, &end, 0);
466                 if ((nodestr[0] == '\0') || (end == NULL) || (*end != '\0')) {
467                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
468                         goto error;
469                 }
470
471                 /* if we find this page in our mappings, set socket_id */
472                 for (i = 0; i < hpi->num_pages[0]; i++) {
473                         void *va = (void *)(unsigned long)virt_addr;
474                         if (hugepg_tbl[i].orig_va == va) {
475                                 hugepg_tbl[i].socket_id = socket_id;
476                                 hp_count++;
477 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
478                                 RTE_LOG(DEBUG, EAL,
479                                         "Hugepage %s is on socket %d\n",
480                                         hugepg_tbl[i].filepath, socket_id);
481 #endif
482                         }
483                 }
484         }
485
486         if (hp_count < hpi->num_pages[0])
487                 goto error;
488
489         fclose(f);
490         return 0;
491
492 error:
493         fclose(f);
494         return -1;
495 }
496
497 static int
498 cmp_physaddr(const void *a, const void *b)
499 {
500 #ifndef RTE_ARCH_PPC_64
501         const struct hugepage_file *p1 = a;
502         const struct hugepage_file *p2 = b;
503 #else
504         /* PowerPC needs memory sorted in reverse order from x86 */
505         const struct hugepage_file *p1 = b;
506         const struct hugepage_file *p2 = a;
507 #endif
508         if (p1->physaddr < p2->physaddr)
509                 return -1;
510         else if (p1->physaddr > p2->physaddr)
511                 return 1;
512         else
513                 return 0;
514 }
515
516 /*
517  * Uses mmap to create a shared memory area for storage of data
518  * Used in this file to store the hugepage file map on disk
519  */
520 static void *
521 create_shared_memory(const char *filename, const size_t mem_size)
522 {
523         void *retval;
524         int fd = open(filename, O_CREAT | O_RDWR, 0666);
525         if (fd < 0)
526                 return NULL;
527         if (ftruncate(fd, mem_size) < 0) {
528                 close(fd);
529                 return NULL;
530         }
531         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
532         close(fd);
533         if (retval == MAP_FAILED)
534                 return NULL;
535         return retval;
536 }
537
538 /*
539  * this copies *active* hugepages from one hugepage table to another.
540  * destination is typically the shared memory.
541  */
542 static int
543 copy_hugepages_to_shared_mem(struct hugepage_file * dst, int dest_size,
544                 const struct hugepage_file * src, int src_size)
545 {
546         int src_pos, dst_pos = 0;
547
548         for (src_pos = 0; src_pos < src_size; src_pos++) {
549                 if (src[src_pos].orig_va != NULL) {
550                         /* error on overflow attempt */
551                         if (dst_pos == dest_size)
552                                 return -1;
553                         memcpy(&dst[dst_pos], &src[src_pos], sizeof(struct hugepage_file));
554                         dst_pos++;
555                 }
556         }
557         return 0;
558 }
559
560 static int
561 unlink_hugepage_files(struct hugepage_file *hugepg_tbl,
562                 unsigned num_hp_info)
563 {
564         unsigned socket, size;
565         int page, nrpages = 0;
566
567         /* get total number of hugepages */
568         for (size = 0; size < num_hp_info; size++)
569                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
570                         nrpages +=
571                         internal_config.hugepage_info[size].num_pages[socket];
572
573         for (page = 0; page < nrpages; page++) {
574                 struct hugepage_file *hp = &hugepg_tbl[page];
575
576                 if (hp->final_va != NULL && unlink(hp->filepath)) {
577                         RTE_LOG(WARNING, EAL, "%s(): Removing %s failed: %s\n",
578                                 __func__, hp->filepath, strerror(errno));
579                 }
580         }
581         return 0;
582 }
583
584 /*
585  * unmaps hugepages that are not going to be used. since we originally allocate
586  * ALL hugepages (not just those we need), additional unmapping needs to be done.
587  */
588 static int
589 unmap_unneeded_hugepages(struct hugepage_file *hugepg_tbl,
590                 struct hugepage_info *hpi,
591                 unsigned num_hp_info)
592 {
593         unsigned socket, size;
594         int page, nrpages = 0;
595
596         /* get total number of hugepages */
597         for (size = 0; size < num_hp_info; size++)
598                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
599                         nrpages += internal_config.hugepage_info[size].num_pages[socket];
600
601         for (size = 0; size < num_hp_info; size++) {
602                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++) {
603                         unsigned pages_found = 0;
604
605                         /* traverse until we have unmapped all the unused pages */
606                         for (page = 0; page < nrpages; page++) {
607                                 struct hugepage_file *hp = &hugepg_tbl[page];
608
609                                 /* find a page that matches the criteria */
610                                 if ((hp->size == hpi[size].hugepage_sz) &&
611                                                 (hp->socket_id == (int) socket)) {
612
613                                         /* if we skipped enough pages, unmap the rest */
614                                         if (pages_found == hpi[size].num_pages[socket]) {
615                                                 uint64_t unmap_len;
616
617                                                 unmap_len = hp->size;
618
619                                                 /* get start addr and len of the remaining segment */
620                                                 munmap(hp->orig_va,
621                                                         (size_t)unmap_len);
622
623                                                 hp->orig_va = NULL;
624                                                 if (unlink(hp->filepath) == -1) {
625                                                         RTE_LOG(ERR, EAL, "%s(): Removing %s failed: %s\n",
626                                                                         __func__, hp->filepath, strerror(errno));
627                                                         return -1;
628                                                 }
629                                         } else {
630                                                 /* lock the page and skip */
631                                                 pages_found++;
632                                         }
633
634                                 } /* match page */
635                         } /* foreach page */
636                 } /* foreach socket */
637         } /* foreach pagesize */
638
639         return 0;
640 }
641
642 static int
643 remap_segment(struct hugepage_file *hugepages, int seg_start, int seg_end)
644 {
645         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
646         struct rte_memseg_list *msl;
647         struct rte_fbarray *arr;
648         int cur_page, seg_len;
649         unsigned int msl_idx;
650         int ms_idx;
651         uint64_t page_sz;
652         size_t memseg_len;
653         int socket_id;
654
655         page_sz = hugepages[seg_start].size;
656         socket_id = hugepages[seg_start].socket_id;
657         seg_len = seg_end - seg_start;
658
659         RTE_LOG(DEBUG, EAL, "Attempting to map %" PRIu64 "M on socket %i\n",
660                         (seg_len * page_sz) >> 20ULL, socket_id);
661
662         /* find free space in memseg lists */
663         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS; msl_idx++) {
664                 bool empty;
665                 msl = &mcfg->memsegs[msl_idx];
666                 arr = &msl->memseg_arr;
667
668                 if (msl->page_sz != page_sz)
669                         continue;
670                 if (msl->socket_id != socket_id)
671                         continue;
672
673                 /* leave space for a hole if array is not empty */
674                 empty = arr->count == 0;
675                 ms_idx = rte_fbarray_find_next_n_free(arr, 0,
676                                 seg_len + (empty ? 0 : 1));
677
678                 /* memseg list is full? */
679                 if (ms_idx < 0)
680                         continue;
681
682                 /* leave some space between memsegs, they are not IOVA
683                  * contiguous, so they shouldn't be VA contiguous either.
684                  */
685                 if (!empty)
686                         ms_idx++;
687                 break;
688         }
689         if (msl_idx == RTE_MAX_MEMSEG_LISTS) {
690                 RTE_LOG(ERR, EAL, "Could not find space for memseg. Please increase %s and/or %s in configuration.\n",
691                                 RTE_STR(CONFIG_RTE_MAX_MEMSEG_PER_TYPE),
692                                 RTE_STR(CONFIG_RTE_MAX_MEM_PER_TYPE));
693                 return -1;
694         }
695
696 #ifdef RTE_ARCH_PPC64
697         /* for PPC64 we go through the list backwards */
698         for (cur_page = seg_end - 1; cur_page >= seg_start;
699                         cur_page--, ms_idx++) {
700 #else
701         for (cur_page = seg_start; cur_page < seg_end; cur_page++, ms_idx++) {
702 #endif
703                 struct hugepage_file *hfile = &hugepages[cur_page];
704                 struct rte_memseg *ms = rte_fbarray_get(arr, ms_idx);
705                 void *addr;
706                 int fd;
707
708                 fd = open(hfile->filepath, O_RDWR);
709                 if (fd < 0) {
710                         RTE_LOG(ERR, EAL, "Could not open '%s': %s\n",
711                                         hfile->filepath, strerror(errno));
712                         return -1;
713                 }
714                 /* set shared lock on the file. */
715                 if (flock(fd, LOCK_SH) < 0) {
716                         RTE_LOG(DEBUG, EAL, "Could not lock '%s': %s\n",
717                                         hfile->filepath, strerror(errno));
718                         close(fd);
719                         return -1;
720                 }
721                 memseg_len = (size_t)page_sz;
722                 addr = RTE_PTR_ADD(msl->base_va, ms_idx * memseg_len);
723
724                 /* we know this address is already mmapped by memseg list, so
725                  * using MAP_FIXED here is safe
726                  */
727                 addr = mmap(addr, page_sz, PROT_READ | PROT_WRITE,
728                                 MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd, 0);
729                 if (addr == MAP_FAILED) {
730                         RTE_LOG(ERR, EAL, "Couldn't remap '%s': %s\n",
731                                         hfile->filepath, strerror(errno));
732                         close(fd);
733                         return -1;
734                 }
735
736                 /* we have a new address, so unmap previous one */
737 #ifndef RTE_ARCH_64
738                 /* in 32-bit legacy mode, we have already unmapped the page */
739                 if (!internal_config.legacy_mem)
740                         munmap(hfile->orig_va, page_sz);
741 #else
742                 munmap(hfile->orig_va, page_sz);
743 #endif
744
745                 hfile->orig_va = NULL;
746                 hfile->final_va = addr;
747
748                 /* rewrite physical addresses in IOVA as VA mode */
749                 if (rte_eal_iova_mode() == RTE_IOVA_VA)
750                         hfile->physaddr = (uintptr_t)addr;
751
752                 /* set up memseg data */
753                 ms->addr = addr;
754                 ms->hugepage_sz = page_sz;
755                 ms->len = memseg_len;
756                 ms->iova = hfile->physaddr;
757                 ms->socket_id = hfile->socket_id;
758                 ms->nchannel = rte_memory_get_nchannel();
759                 ms->nrank = rte_memory_get_nrank();
760
761                 rte_fbarray_set_used(arr, ms_idx);
762
763                 close(fd);
764         }
765         RTE_LOG(DEBUG, EAL, "Allocated %" PRIu64 "M on socket %i\n",
766                         (seg_len * page_sz) >> 20, socket_id);
767         return 0;
768 }
769
770 #define MEMSEG_LIST_FMT "memseg-%" PRIu64 "k-%i-%i"
771 static int
772 alloc_memseg_list(struct rte_memseg_list *msl, uint64_t page_sz,
773                 int n_segs, int socket_id, int type_msl_idx)
774 {
775         char name[RTE_FBARRAY_NAME_LEN];
776
777         snprintf(name, sizeof(name), MEMSEG_LIST_FMT, page_sz >> 10, socket_id,
778                  type_msl_idx);
779         if (rte_fbarray_init(&msl->memseg_arr, name, n_segs,
780                         sizeof(struct rte_memseg))) {
781                 RTE_LOG(ERR, EAL, "Cannot allocate memseg list: %s\n",
782                         rte_strerror(rte_errno));
783                 return -1;
784         }
785
786         msl->page_sz = page_sz;
787         msl->socket_id = socket_id;
788         msl->base_va = NULL;
789
790         RTE_LOG(DEBUG, EAL, "Memseg list allocated: 0x%zxkB at socket %i\n",
791                         (size_t)page_sz >> 10, socket_id);
792
793         return 0;
794 }
795
796 static int
797 alloc_va_space(struct rte_memseg_list *msl)
798 {
799         uint64_t page_sz;
800         size_t mem_sz;
801         void *addr;
802         int flags = 0;
803
804 #ifdef RTE_ARCH_PPC_64
805         flags |= MAP_HUGETLB;
806 #endif
807
808         page_sz = msl->page_sz;
809         mem_sz = page_sz * msl->memseg_arr.len;
810
811         addr = eal_get_virtual_area(msl->base_va, &mem_sz, page_sz, 0, flags);
812         if (addr == NULL) {
813                 if (rte_errno == EADDRNOTAVAIL)
814                         RTE_LOG(ERR, EAL, "Could not mmap %llu bytes at [%p] - please use '--base-virtaddr' option\n",
815                                 (unsigned long long)mem_sz, msl->base_va);
816                 else
817                         RTE_LOG(ERR, EAL, "Cannot reserve memory\n");
818                 return -1;
819         }
820         msl->base_va = addr;
821
822         return 0;
823 }
824
825 /*
826  * Our VA space is not preallocated yet, so preallocate it here. We need to know
827  * how many segments there are in order to map all pages into one address space,
828  * and leave appropriate holes between segments so that rte_malloc does not
829  * concatenate them into one big segment.
830  *
831  * we also need to unmap original pages to free up address space.
832  */
833 static int __rte_unused
834 prealloc_segments(struct hugepage_file *hugepages, int n_pages)
835 {
836         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
837         int cur_page, seg_start_page, end_seg, new_memseg;
838         unsigned int hpi_idx, socket, i;
839         int n_contig_segs, n_segs;
840         int msl_idx;
841
842         /* before we preallocate segments, we need to free up our VA space.
843          * we're not removing files, and we already have information about
844          * PA-contiguousness, so it is safe to unmap everything.
845          */
846         for (cur_page = 0; cur_page < n_pages; cur_page++) {
847                 struct hugepage_file *hpi = &hugepages[cur_page];
848                 munmap(hpi->orig_va, hpi->size);
849                 hpi->orig_va = NULL;
850         }
851
852         /* we cannot know how many page sizes and sockets we have discovered, so
853          * loop over all of them
854          */
855         for (hpi_idx = 0; hpi_idx < internal_config.num_hugepage_sizes;
856                         hpi_idx++) {
857                 uint64_t page_sz =
858                         internal_config.hugepage_info[hpi_idx].hugepage_sz;
859
860                 for (i = 0; i < rte_socket_count(); i++) {
861                         struct rte_memseg_list *msl;
862
863                         socket = rte_socket_id_by_idx(i);
864                         n_contig_segs = 0;
865                         n_segs = 0;
866                         seg_start_page = -1;
867
868                         for (cur_page = 0; cur_page < n_pages; cur_page++) {
869                                 struct hugepage_file *prev, *cur;
870                                 int prev_seg_start_page = -1;
871
872                                 cur = &hugepages[cur_page];
873                                 prev = cur_page == 0 ? NULL :
874                                                 &hugepages[cur_page - 1];
875
876                                 new_memseg = 0;
877                                 end_seg = 0;
878
879                                 if (cur->size == 0)
880                                         end_seg = 1;
881                                 else if (cur->socket_id != (int) socket)
882                                         end_seg = 1;
883                                 else if (cur->size != page_sz)
884                                         end_seg = 1;
885                                 else if (cur_page == 0)
886                                         new_memseg = 1;
887 #ifdef RTE_ARCH_PPC_64
888                                 /* On PPC64 architecture, the mmap always start
889                                  * from higher address to lower address. Here,
890                                  * physical addresses are in descending order.
891                                  */
892                                 else if ((prev->physaddr - cur->physaddr) !=
893                                                 cur->size)
894                                         new_memseg = 1;
895 #else
896                                 else if ((cur->physaddr - prev->physaddr) !=
897                                                 cur->size)
898                                         new_memseg = 1;
899 #endif
900                                 if (new_memseg) {
901                                         /* if we're already inside a segment,
902                                          * new segment means end of current one
903                                          */
904                                         if (seg_start_page != -1) {
905                                                 end_seg = 1;
906                                                 prev_seg_start_page =
907                                                                 seg_start_page;
908                                         }
909                                         seg_start_page = cur_page;
910                                 }
911
912                                 if (end_seg) {
913                                         if (prev_seg_start_page != -1) {
914                                                 /* we've found a new segment */
915                                                 n_contig_segs++;
916                                                 n_segs += cur_page -
917                                                         prev_seg_start_page;
918                                         } else if (seg_start_page != -1) {
919                                                 /* we didn't find new segment,
920                                                  * but did end current one
921                                                  */
922                                                 n_contig_segs++;
923                                                 n_segs += cur_page -
924                                                                 seg_start_page;
925                                                 seg_start_page = -1;
926                                                 continue;
927                                         } else {
928                                                 /* we're skipping this page */
929                                                 continue;
930                                         }
931                                 }
932                                 /* segment continues */
933                         }
934                         /* check if we missed last segment */
935                         if (seg_start_page != -1) {
936                                 n_contig_segs++;
937                                 n_segs += cur_page - seg_start_page;
938                         }
939
940                         /* if no segments were found, do not preallocate */
941                         if (n_segs == 0)
942                                 continue;
943
944                         /* we now have total number of pages that we will
945                          * allocate for this segment list. add separator pages
946                          * to the total count, and preallocate VA space.
947                          */
948                         n_segs += n_contig_segs - 1;
949
950                         /* now, preallocate VA space for these segments */
951
952                         /* first, find suitable memseg list for this */
953                         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS;
954                                         msl_idx++) {
955                                 msl = &mcfg->memsegs[msl_idx];
956
957                                 if (msl->base_va != NULL)
958                                         continue;
959                                 break;
960                         }
961                         if (msl_idx == RTE_MAX_MEMSEG_LISTS) {
962                                 RTE_LOG(ERR, EAL, "Not enough space in memseg lists, please increase %s\n",
963                                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
964                                 return -1;
965                         }
966
967                         /* now, allocate fbarray itself */
968                         if (alloc_memseg_list(msl, page_sz, n_segs, socket,
969                                                 msl_idx) < 0)
970                                 return -1;
971
972                         /* finally, allocate VA space */
973                         if (alloc_va_space(msl) < 0)
974                                 return -1;
975                 }
976         }
977         return 0;
978 }
979
980 /*
981  * We cannot reallocate memseg lists on the fly because PPC64 stores pages
982  * backwards, therefore we have to process the entire memseg first before
983  * remapping it into memseg list VA space.
984  */
985 static int
986 remap_needed_hugepages(struct hugepage_file *hugepages, int n_pages)
987 {
988         int cur_page, seg_start_page, new_memseg, ret;
989
990         seg_start_page = 0;
991         for (cur_page = 0; cur_page < n_pages; cur_page++) {
992                 struct hugepage_file *prev, *cur;
993
994                 new_memseg = 0;
995
996                 cur = &hugepages[cur_page];
997                 prev = cur_page == 0 ? NULL : &hugepages[cur_page - 1];
998
999                 /* if size is zero, no more pages left */
1000                 if (cur->size == 0)
1001                         break;
1002
1003                 if (cur_page == 0)
1004                         new_memseg = 1;
1005                 else if (cur->socket_id != prev->socket_id)
1006                         new_memseg = 1;
1007                 else if (cur->size != prev->size)
1008                         new_memseg = 1;
1009 #ifdef RTE_ARCH_PPC_64
1010                 /* On PPC64 architecture, the mmap always start from higher
1011                  * address to lower address. Here, physical addresses are in
1012                  * descending order.
1013                  */
1014                 else if ((prev->physaddr - cur->physaddr) != cur->size)
1015                         new_memseg = 1;
1016 #else
1017                 else if ((cur->physaddr - prev->physaddr) != cur->size)
1018                         new_memseg = 1;
1019 #endif
1020
1021                 if (new_memseg) {
1022                         /* if this isn't the first time, remap segment */
1023                         if (cur_page != 0) {
1024                                 ret = remap_segment(hugepages, seg_start_page,
1025                                                 cur_page);
1026                                 if (ret != 0)
1027                                         return -1;
1028                         }
1029                         /* remember where we started */
1030                         seg_start_page = cur_page;
1031                 }
1032                 /* continuation of previous memseg */
1033         }
1034         /* we were stopped, but we didn't remap the last segment, do it now */
1035         if (cur_page != 0) {
1036                 ret = remap_segment(hugepages, seg_start_page,
1037                                 cur_page);
1038                 if (ret != 0)
1039                         return -1;
1040         }
1041         return 0;
1042 }
1043
1044 static inline uint64_t
1045 get_socket_mem_size(int socket)
1046 {
1047         uint64_t size = 0;
1048         unsigned i;
1049
1050         for (i = 0; i < internal_config.num_hugepage_sizes; i++){
1051                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1052                 if (strnlen(hpi->hugedir, sizeof(hpi->hugedir)) != 0)
1053                         size += hpi->hugepage_sz * hpi->num_pages[socket];
1054         }
1055
1056         return size;
1057 }
1058
1059 /*
1060  * This function is a NUMA-aware equivalent of calc_num_pages.
1061  * It takes in the list of hugepage sizes and the
1062  * number of pages thereof, and calculates the best number of
1063  * pages of each size to fulfill the request for <memory> ram
1064  */
1065 static int
1066 calc_num_pages_per_socket(uint64_t * memory,
1067                 struct hugepage_info *hp_info,
1068                 struct hugepage_info *hp_used,
1069                 unsigned num_hp_info)
1070 {
1071         unsigned socket, j, i = 0;
1072         unsigned requested, available;
1073         int total_num_pages = 0;
1074         uint64_t remaining_mem, cur_mem;
1075         uint64_t total_mem = internal_config.memory;
1076
1077         if (num_hp_info == 0)
1078                 return -1;
1079
1080         /* if specific memory amounts per socket weren't requested */
1081         if (internal_config.force_sockets == 0) {
1082                 size_t total_size;
1083 #ifdef RTE_ARCH_64
1084                 int cpu_per_socket[RTE_MAX_NUMA_NODES];
1085                 size_t default_size;
1086                 unsigned lcore_id;
1087
1088                 /* Compute number of cores per socket */
1089                 memset(cpu_per_socket, 0, sizeof(cpu_per_socket));
1090                 RTE_LCORE_FOREACH(lcore_id) {
1091                         cpu_per_socket[rte_lcore_to_socket_id(lcore_id)]++;
1092                 }
1093
1094                 /*
1095                  * Automatically spread requested memory amongst detected sockets according
1096                  * to number of cores from cpu mask present on each socket
1097                  */
1098                 total_size = internal_config.memory;
1099                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1100
1101                         /* Set memory amount per socket */
1102                         default_size = (internal_config.memory * cpu_per_socket[socket])
1103                                         / rte_lcore_count();
1104
1105                         /* Limit to maximum available memory on socket */
1106                         default_size = RTE_MIN(default_size, get_socket_mem_size(socket));
1107
1108                         /* Update sizes */
1109                         memory[socket] = default_size;
1110                         total_size -= default_size;
1111                 }
1112
1113                 /*
1114                  * If some memory is remaining, try to allocate it by getting all
1115                  * available memory from sockets, one after the other
1116                  */
1117                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1118                         /* take whatever is available */
1119                         default_size = RTE_MIN(get_socket_mem_size(socket) - memory[socket],
1120                                                total_size);
1121
1122                         /* Update sizes */
1123                         memory[socket] += default_size;
1124                         total_size -= default_size;
1125                 }
1126 #else
1127                 /* in 32-bit mode, allocate all of the memory only on master
1128                  * lcore socket
1129                  */
1130                 total_size = internal_config.memory;
1131                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0;
1132                                 socket++) {
1133                         struct rte_config *cfg = rte_eal_get_configuration();
1134                         unsigned int master_lcore_socket;
1135
1136                         master_lcore_socket =
1137                                 rte_lcore_to_socket_id(cfg->master_lcore);
1138
1139                         if (master_lcore_socket != socket)
1140                                 continue;
1141
1142                         /* Update sizes */
1143                         memory[socket] = total_size;
1144                         break;
1145                 }
1146 #endif
1147         }
1148
1149         for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_mem != 0; socket++) {
1150                 /* skips if the memory on specific socket wasn't requested */
1151                 for (i = 0; i < num_hp_info && memory[socket] != 0; i++){
1152                         strlcpy(hp_used[i].hugedir, hp_info[i].hugedir,
1153                                 sizeof(hp_used[i].hugedir));
1154                         hp_used[i].num_pages[socket] = RTE_MIN(
1155                                         memory[socket] / hp_info[i].hugepage_sz,
1156                                         hp_info[i].num_pages[socket]);
1157
1158                         cur_mem = hp_used[i].num_pages[socket] *
1159                                         hp_used[i].hugepage_sz;
1160
1161                         memory[socket] -= cur_mem;
1162                         total_mem -= cur_mem;
1163
1164                         total_num_pages += hp_used[i].num_pages[socket];
1165
1166                         /* check if we have met all memory requests */
1167                         if (memory[socket] == 0)
1168                                 break;
1169
1170                         /* check if we have any more pages left at this size, if so
1171                          * move on to next size */
1172                         if (hp_used[i].num_pages[socket] == hp_info[i].num_pages[socket])
1173                                 continue;
1174                         /* At this point we know that there are more pages available that are
1175                          * bigger than the memory we want, so lets see if we can get enough
1176                          * from other page sizes.
1177                          */
1178                         remaining_mem = 0;
1179                         for (j = i+1; j < num_hp_info; j++)
1180                                 remaining_mem += hp_info[j].hugepage_sz *
1181                                 hp_info[j].num_pages[socket];
1182
1183                         /* is there enough other memory, if not allocate another page and quit */
1184                         if (remaining_mem < memory[socket]){
1185                                 cur_mem = RTE_MIN(memory[socket],
1186                                                 hp_info[i].hugepage_sz);
1187                                 memory[socket] -= cur_mem;
1188                                 total_mem -= cur_mem;
1189                                 hp_used[i].num_pages[socket]++;
1190                                 total_num_pages++;
1191                                 break; /* we are done with this socket*/
1192                         }
1193                 }
1194                 /* if we didn't satisfy all memory requirements per socket */
1195                 if (memory[socket] > 0 &&
1196                                 internal_config.socket_mem[socket] != 0) {
1197                         /* to prevent icc errors */
1198                         requested = (unsigned) (internal_config.socket_mem[socket] /
1199                                         0x100000);
1200                         available = requested -
1201                                         ((unsigned) (memory[socket] / 0x100000));
1202                         RTE_LOG(ERR, EAL, "Not enough memory available on socket %u! "
1203                                         "Requested: %uMB, available: %uMB\n", socket,
1204                                         requested, available);
1205                         return -1;
1206                 }
1207         }
1208
1209         /* if we didn't satisfy total memory requirements */
1210         if (total_mem > 0) {
1211                 requested = (unsigned) (internal_config.memory / 0x100000);
1212                 available = requested - (unsigned) (total_mem / 0x100000);
1213                 RTE_LOG(ERR, EAL, "Not enough memory available! Requested: %uMB,"
1214                                 " available: %uMB\n", requested, available);
1215                 return -1;
1216         }
1217         return total_num_pages;
1218 }
1219
1220 static inline size_t
1221 eal_get_hugepage_mem_size(void)
1222 {
1223         uint64_t size = 0;
1224         unsigned i, j;
1225
1226         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1227                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1228                 if (strnlen(hpi->hugedir, sizeof(hpi->hugedir)) != 0) {
1229                         for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1230                                 size += hpi->hugepage_sz * hpi->num_pages[j];
1231                         }
1232                 }
1233         }
1234
1235         return (size < SIZE_MAX) ? (size_t)(size) : SIZE_MAX;
1236 }
1237
1238 static struct sigaction huge_action_old;
1239 static int huge_need_recover;
1240
1241 static void
1242 huge_register_sigbus(void)
1243 {
1244         sigset_t mask;
1245         struct sigaction action;
1246
1247         sigemptyset(&mask);
1248         sigaddset(&mask, SIGBUS);
1249         action.sa_flags = 0;
1250         action.sa_mask = mask;
1251         action.sa_handler = huge_sigbus_handler;
1252
1253         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
1254 }
1255
1256 static void
1257 huge_recover_sigbus(void)
1258 {
1259         if (huge_need_recover) {
1260                 sigaction(SIGBUS, &huge_action_old, NULL);
1261                 huge_need_recover = 0;
1262         }
1263 }
1264
1265 /*
1266  * Prepare physical memory mapping: fill configuration structure with
1267  * these infos, return 0 on success.
1268  *  1. map N huge pages in separate files in hugetlbfs
1269  *  2. find associated physical addr
1270  *  3. find associated NUMA socket ID
1271  *  4. sort all huge pages by physical address
1272  *  5. remap these N huge pages in the correct order
1273  *  6. unmap the first mapping
1274  *  7. fill memsegs in configuration with contiguous zones
1275  */
1276 static int
1277 eal_legacy_hugepage_init(void)
1278 {
1279         struct rte_mem_config *mcfg;
1280         struct hugepage_file *hugepage = NULL, *tmp_hp = NULL;
1281         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1282         struct rte_fbarray *arr;
1283         struct rte_memseg *ms;
1284
1285         uint64_t memory[RTE_MAX_NUMA_NODES];
1286
1287         unsigned hp_offset;
1288         int i, j;
1289         int nr_hugefiles, nr_hugepages = 0;
1290         void *addr;
1291
1292         test_phys_addrs_available();
1293
1294         memset(used_hp, 0, sizeof(used_hp));
1295
1296         /* get pointer to global configuration */
1297         mcfg = rte_eal_get_configuration()->mem_config;
1298
1299         /* hugetlbfs can be disabled */
1300         if (internal_config.no_hugetlbfs) {
1301                 struct rte_memseg_list *msl;
1302                 uint64_t page_sz;
1303                 int n_segs, cur_seg;
1304
1305                 /* nohuge mode is legacy mode */
1306                 internal_config.legacy_mem = 1;
1307
1308                 /* create a memseg list */
1309                 msl = &mcfg->memsegs[0];
1310
1311                 page_sz = RTE_PGSIZE_4K;
1312                 n_segs = internal_config.memory / page_sz;
1313
1314                 if (rte_fbarray_init(&msl->memseg_arr, "nohugemem", n_segs,
1315                                         sizeof(struct rte_memseg))) {
1316                         RTE_LOG(ERR, EAL, "Cannot allocate memseg list\n");
1317                         return -1;
1318                 }
1319
1320                 addr = mmap(NULL, internal_config.memory, PROT_READ | PROT_WRITE,
1321                                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1322                 if (addr == MAP_FAILED) {
1323                         RTE_LOG(ERR, EAL, "%s: mmap() failed: %s\n", __func__,
1324                                         strerror(errno));
1325                         return -1;
1326                 }
1327                 msl->base_va = addr;
1328                 msl->page_sz = page_sz;
1329                 msl->socket_id = 0;
1330
1331                 /* populate memsegs. each memseg is one page long */
1332                 for (cur_seg = 0; cur_seg < n_segs; cur_seg++) {
1333                         arr = &msl->memseg_arr;
1334
1335                         ms = rte_fbarray_get(arr, cur_seg);
1336                         if (rte_eal_iova_mode() == RTE_IOVA_VA)
1337                                 ms->iova = (uintptr_t)addr;
1338                         else
1339                                 ms->iova = RTE_BAD_IOVA;
1340                         ms->addr = addr;
1341                         ms->hugepage_sz = page_sz;
1342                         ms->socket_id = 0;
1343                         ms->len = page_sz;
1344
1345                         rte_fbarray_set_used(arr, cur_seg);
1346
1347                         addr = RTE_PTR_ADD(addr, (size_t)page_sz);
1348                 }
1349                 return 0;
1350         }
1351
1352         /* calculate total number of hugepages available. at this point we haven't
1353          * yet started sorting them so they all are on socket 0 */
1354         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1355                 /* meanwhile, also initialize used_hp hugepage sizes in used_hp */
1356                 used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;
1357
1358                 nr_hugepages += internal_config.hugepage_info[i].num_pages[0];
1359         }
1360
1361         /*
1362          * allocate a memory area for hugepage table.
1363          * this isn't shared memory yet. due to the fact that we need some
1364          * processing done on these pages, shared memory will be created
1365          * at a later stage.
1366          */
1367         tmp_hp = malloc(nr_hugepages * sizeof(struct hugepage_file));
1368         if (tmp_hp == NULL)
1369                 goto fail;
1370
1371         memset(tmp_hp, 0, nr_hugepages * sizeof(struct hugepage_file));
1372
1373         hp_offset = 0; /* where we start the current page size entries */
1374
1375         huge_register_sigbus();
1376
1377         /* make a copy of socket_mem, needed for balanced allocation. */
1378         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1379                 memory[i] = internal_config.socket_mem[i];
1380
1381         /* map all hugepages and sort them */
1382         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
1383                 unsigned pages_old, pages_new;
1384                 struct hugepage_info *hpi;
1385
1386                 /*
1387                  * we don't yet mark hugepages as used at this stage, so
1388                  * we just map all hugepages available to the system
1389                  * all hugepages are still located on socket 0
1390                  */
1391                 hpi = &internal_config.hugepage_info[i];
1392
1393                 if (hpi->num_pages[0] == 0)
1394                         continue;
1395
1396                 /* map all hugepages available */
1397                 pages_old = hpi->num_pages[0];
1398                 pages_new = map_all_hugepages(&tmp_hp[hp_offset], hpi, memory);
1399                 if (pages_new < pages_old) {
1400                         RTE_LOG(DEBUG, EAL,
1401                                 "%d not %d hugepages of size %u MB allocated\n",
1402                                 pages_new, pages_old,
1403                                 (unsigned)(hpi->hugepage_sz / 0x100000));
1404
1405                         int pages = pages_old - pages_new;
1406
1407                         nr_hugepages -= pages;
1408                         hpi->num_pages[0] = pages_new;
1409                         if (pages_new == 0)
1410                                 continue;
1411                 }
1412
1413                 if (phys_addrs_available &&
1414                                 rte_eal_iova_mode() != RTE_IOVA_VA) {
1415                         /* find physical addresses for each hugepage */
1416                         if (find_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1417                                 RTE_LOG(DEBUG, EAL, "Failed to find phys addr "
1418                                         "for %u MB pages\n",
1419                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1420                                 goto fail;
1421                         }
1422                 } else {
1423                         /* set physical addresses for each hugepage */
1424                         if (set_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1425                                 RTE_LOG(DEBUG, EAL, "Failed to set phys addr "
1426                                         "for %u MB pages\n",
1427                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1428                                 goto fail;
1429                         }
1430                 }
1431
1432                 if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
1433                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
1434                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1435                         goto fail;
1436                 }
1437
1438                 qsort(&tmp_hp[hp_offset], hpi->num_pages[0],
1439                       sizeof(struct hugepage_file), cmp_physaddr);
1440
1441                 /* we have processed a num of hugepages of this size, so inc offset */
1442                 hp_offset += hpi->num_pages[0];
1443         }
1444
1445         huge_recover_sigbus();
1446
1447         if (internal_config.memory == 0 && internal_config.force_sockets == 0)
1448                 internal_config.memory = eal_get_hugepage_mem_size();
1449
1450         nr_hugefiles = nr_hugepages;
1451
1452
1453         /* clean out the numbers of pages */
1454         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
1455                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
1456                         internal_config.hugepage_info[i].num_pages[j] = 0;
1457
1458         /* get hugepages for each socket */
1459         for (i = 0; i < nr_hugefiles; i++) {
1460                 int socket = tmp_hp[i].socket_id;
1461
1462                 /* find a hugepage info with right size and increment num_pages */
1463                 const int nb_hpsizes = RTE_MIN(MAX_HUGEPAGE_SIZES,
1464                                 (int)internal_config.num_hugepage_sizes);
1465                 for (j = 0; j < nb_hpsizes; j++) {
1466                         if (tmp_hp[i].size ==
1467                                         internal_config.hugepage_info[j].hugepage_sz) {
1468                                 internal_config.hugepage_info[j].num_pages[socket]++;
1469                         }
1470                 }
1471         }
1472
1473         /* make a copy of socket_mem, needed for number of pages calculation */
1474         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1475                 memory[i] = internal_config.socket_mem[i];
1476
1477         /* calculate final number of pages */
1478         nr_hugepages = calc_num_pages_per_socket(memory,
1479                         internal_config.hugepage_info, used_hp,
1480                         internal_config.num_hugepage_sizes);
1481
1482         /* error if not enough memory available */
1483         if (nr_hugepages < 0)
1484                 goto fail;
1485
1486         /* reporting in! */
1487         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1488                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1489                         if (used_hp[i].num_pages[j] > 0) {
1490                                 RTE_LOG(DEBUG, EAL,
1491                                         "Requesting %u pages of size %uMB"
1492                                         " from socket %i\n",
1493                                         used_hp[i].num_pages[j],
1494                                         (unsigned)
1495                                         (used_hp[i].hugepage_sz / 0x100000),
1496                                         j);
1497                         }
1498                 }
1499         }
1500
1501         /* create shared memory */
1502         hugepage = create_shared_memory(eal_hugepage_file_path(),
1503                         nr_hugefiles * sizeof(struct hugepage_file));
1504
1505         if (hugepage == NULL) {
1506                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
1507                 goto fail;
1508         }
1509         memset(hugepage, 0, nr_hugefiles * sizeof(struct hugepage_file));
1510
1511         /*
1512          * unmap pages that we won't need (looks at used_hp).
1513          * also, sets final_va to NULL on pages that were unmapped.
1514          */
1515         if (unmap_unneeded_hugepages(tmp_hp, used_hp,
1516                         internal_config.num_hugepage_sizes) < 0) {
1517                 RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
1518                 goto fail;
1519         }
1520
1521         /*
1522          * copy stuff from malloc'd hugepage* to the actual shared memory.
1523          * this procedure only copies those hugepages that have orig_va
1524          * not NULL. has overflow protection.
1525          */
1526         if (copy_hugepages_to_shared_mem(hugepage, nr_hugefiles,
1527                         tmp_hp, nr_hugefiles) < 0) {
1528                 RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
1529                 goto fail;
1530         }
1531
1532 #ifndef RTE_ARCH_64
1533         /* for legacy 32-bit mode, we did not preallocate VA space, so do it */
1534         if (internal_config.legacy_mem &&
1535                         prealloc_segments(hugepage, nr_hugefiles)) {
1536                 RTE_LOG(ERR, EAL, "Could not preallocate VA space for hugepages\n");
1537                 goto fail;
1538         }
1539 #endif
1540
1541         /* remap all pages we do need into memseg list VA space, so that those
1542          * pages become first-class citizens in DPDK memory subsystem
1543          */
1544         if (remap_needed_hugepages(hugepage, nr_hugefiles)) {
1545                 RTE_LOG(ERR, EAL, "Couldn't remap hugepage files into memseg lists\n");
1546                 goto fail;
1547         }
1548
1549         /* free the hugepage backing files */
1550         if (internal_config.hugepage_unlink &&
1551                 unlink_hugepage_files(tmp_hp, internal_config.num_hugepage_sizes) < 0) {
1552                 RTE_LOG(ERR, EAL, "Unlinking hugepage files failed!\n");
1553                 goto fail;
1554         }
1555
1556         /* free the temporary hugepage table */
1557         free(tmp_hp);
1558         tmp_hp = NULL;
1559
1560         munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1561
1562         /* we're not going to allocate more pages, so release VA space for
1563          * unused memseg lists
1564          */
1565         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
1566                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
1567                 size_t mem_sz;
1568
1569                 /* skip inactive lists */
1570                 if (msl->base_va == NULL)
1571                         continue;
1572                 /* skip lists where there is at least one page allocated */
1573                 if (msl->memseg_arr.count > 0)
1574                         continue;
1575                 /* this is an unused list, deallocate it */
1576                 mem_sz = (size_t)msl->page_sz * msl->memseg_arr.len;
1577                 munmap(msl->base_va, mem_sz);
1578                 msl->base_va = NULL;
1579
1580                 /* destroy backing fbarray */
1581                 rte_fbarray_destroy(&msl->memseg_arr);
1582         }
1583
1584         return 0;
1585
1586 fail:
1587         huge_recover_sigbus();
1588         free(tmp_hp);
1589         if (hugepage != NULL)
1590                 munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1591
1592         return -1;
1593 }
1594
1595 static int __rte_unused
1596 hugepage_count_walk(const struct rte_memseg_list *msl, void *arg)
1597 {
1598         struct hugepage_info *hpi = arg;
1599
1600         if (msl->page_sz != hpi->hugepage_sz)
1601                 return 0;
1602
1603         hpi->num_pages[msl->socket_id] += msl->memseg_arr.len;
1604         return 0;
1605 }
1606
1607 static int
1608 eal_hugepage_init(void)
1609 {
1610         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1611         uint64_t memory[RTE_MAX_NUMA_NODES];
1612         int hp_sz_idx, socket_id;
1613
1614         test_phys_addrs_available();
1615
1616         memset(used_hp, 0, sizeof(used_hp));
1617
1618         for (hp_sz_idx = 0;
1619                         hp_sz_idx < (int) internal_config.num_hugepage_sizes;
1620                         hp_sz_idx++) {
1621 #ifndef RTE_ARCH_64
1622                 struct hugepage_info dummy;
1623                 unsigned int i;
1624 #endif
1625                 /* also initialize used_hp hugepage sizes in used_hp */
1626                 struct hugepage_info *hpi;
1627                 hpi = &internal_config.hugepage_info[hp_sz_idx];
1628                 used_hp[hp_sz_idx].hugepage_sz = hpi->hugepage_sz;
1629
1630 #ifndef RTE_ARCH_64
1631                 /* for 32-bit, limit number of pages on socket to whatever we've
1632                  * preallocated, as we cannot allocate more.
1633                  */
1634                 memset(&dummy, 0, sizeof(dummy));
1635                 dummy.hugepage_sz = hpi->hugepage_sz;
1636                 if (rte_memseg_list_walk(hugepage_count_walk, &dummy) < 0)
1637                         return -1;
1638
1639                 for (i = 0; i < RTE_DIM(dummy.num_pages); i++) {
1640                         hpi->num_pages[i] = RTE_MIN(hpi->num_pages[i],
1641                                         dummy.num_pages[i]);
1642                 }
1643 #endif
1644         }
1645
1646         /* make a copy of socket_mem, needed for balanced allocation. */
1647         for (hp_sz_idx = 0; hp_sz_idx < RTE_MAX_NUMA_NODES; hp_sz_idx++)
1648                 memory[hp_sz_idx] = internal_config.socket_mem[hp_sz_idx];
1649
1650         /* calculate final number of pages */
1651         if (calc_num_pages_per_socket(memory,
1652                         internal_config.hugepage_info, used_hp,
1653                         internal_config.num_hugepage_sizes) < 0)
1654                 return -1;
1655
1656         for (hp_sz_idx = 0;
1657                         hp_sz_idx < (int)internal_config.num_hugepage_sizes;
1658                         hp_sz_idx++) {
1659                 for (socket_id = 0; socket_id < RTE_MAX_NUMA_NODES;
1660                                 socket_id++) {
1661                         struct rte_memseg **pages;
1662                         struct hugepage_info *hpi = &used_hp[hp_sz_idx];
1663                         unsigned int num_pages = hpi->num_pages[socket_id];
1664                         int num_pages_alloc, i;
1665
1666                         if (num_pages == 0)
1667                                 continue;
1668
1669                         pages = malloc(sizeof(*pages) * num_pages);
1670
1671                         RTE_LOG(DEBUG, EAL, "Allocating %u pages of size %" PRIu64 "M on socket %i\n",
1672                                 num_pages, hpi->hugepage_sz >> 20, socket_id);
1673
1674                         num_pages_alloc = eal_memalloc_alloc_seg_bulk(pages,
1675                                         num_pages, hpi->hugepage_sz,
1676                                         socket_id, true);
1677                         if (num_pages_alloc < 0) {
1678                                 free(pages);
1679                                 return -1;
1680                         }
1681
1682                         /* mark preallocated pages as unfreeable */
1683                         for (i = 0; i < num_pages_alloc; i++) {
1684                                 struct rte_memseg *ms = pages[i];
1685                                 ms->flags |= RTE_MEMSEG_FLAG_DO_NOT_FREE;
1686                         }
1687                         free(pages);
1688                 }
1689         }
1690         return 0;
1691 }
1692
1693 /*
1694  * uses fstat to report the size of a file on disk
1695  */
1696 static off_t
1697 getFileSize(int fd)
1698 {
1699         struct stat st;
1700         if (fstat(fd, &st) < 0)
1701                 return 0;
1702         return st.st_size;
1703 }
1704
1705 /*
1706  * This creates the memory mappings in the secondary process to match that of
1707  * the server process. It goes through each memory segment in the DPDK runtime
1708  * configuration and finds the hugepages which form that segment, mapping them
1709  * in order to form a contiguous block in the virtual memory space
1710  */
1711 static int
1712 eal_legacy_hugepage_attach(void)
1713 {
1714         struct hugepage_file *hp = NULL;
1715         unsigned int num_hp = 0;
1716         unsigned int i = 0;
1717         unsigned int cur_seg;
1718         off_t size = 0;
1719         int fd, fd_hugepage = -1;
1720
1721         if (aslr_enabled() > 0) {
1722                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
1723                                 "(ASLR) is enabled in the kernel.\n");
1724                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
1725                                 "into secondary processes\n");
1726         }
1727
1728         test_phys_addrs_available();
1729
1730         fd_hugepage = open(eal_hugepage_file_path(), O_RDONLY);
1731         if (fd_hugepage < 0) {
1732                 RTE_LOG(ERR, EAL, "Could not open %s\n", eal_hugepage_file_path());
1733                 goto error;
1734         }
1735
1736         size = getFileSize(fd_hugepage);
1737         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
1738         if (hp == MAP_FAILED) {
1739                 RTE_LOG(ERR, EAL, "Could not mmap %s\n", eal_hugepage_file_path());
1740                 goto error;
1741         }
1742
1743         num_hp = size / sizeof(struct hugepage_file);
1744         RTE_LOG(DEBUG, EAL, "Analysing %u files\n", num_hp);
1745
1746         /* map all segments into memory to make sure we get the addrs. the
1747          * segments themselves are already in memseg list (which is shared and
1748          * has its VA space already preallocated), so we just need to map
1749          * everything into correct addresses.
1750          */
1751         for (i = 0; i < num_hp; i++) {
1752                 struct hugepage_file *hf = &hp[i];
1753                 size_t map_sz = hf->size;
1754                 void *map_addr = hf->final_va;
1755
1756                 /* if size is zero, no more pages left */
1757                 if (map_sz == 0)
1758                         break;
1759
1760                 fd = open(hf->filepath, O_RDWR);
1761                 if (fd < 0) {
1762                         RTE_LOG(ERR, EAL, "Could not open %s: %s\n",
1763                                 hf->filepath, strerror(errno));
1764                         goto error;
1765                 }
1766
1767                 map_addr = mmap(map_addr, map_sz, PROT_READ | PROT_WRITE,
1768                                 MAP_SHARED | MAP_FIXED, fd, 0);
1769                 if (map_addr == MAP_FAILED) {
1770                         RTE_LOG(ERR, EAL, "Could not map %s: %s\n",
1771                                 hf->filepath, strerror(errno));
1772                         close(fd);
1773                         goto error;
1774                 }
1775
1776                 /* set shared lock on the file. */
1777                 if (flock(fd, LOCK_SH) < 0) {
1778                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed: %s\n",
1779                                 __func__, strerror(errno));
1780                         close(fd);
1781                         goto error;
1782                 }
1783
1784                 close(fd);
1785         }
1786         /* unmap the hugepage config file, since we are done using it */
1787         munmap(hp, size);
1788         close(fd_hugepage);
1789         return 0;
1790
1791 error:
1792         /* map all segments into memory to make sure we get the addrs */
1793         cur_seg = 0;
1794         for (cur_seg = 0; cur_seg < i; cur_seg++) {
1795                 struct hugepage_file *hf = &hp[i];
1796                 size_t map_sz = hf->size;
1797                 void *map_addr = hf->final_va;
1798
1799                 munmap(map_addr, map_sz);
1800         }
1801         if (hp != NULL && hp != MAP_FAILED)
1802                 munmap(hp, size);
1803         if (fd_hugepage >= 0)
1804                 close(fd_hugepage);
1805         return -1;
1806 }
1807
1808 static int
1809 eal_hugepage_attach(void)
1810 {
1811         if (eal_memalloc_sync_with_primary()) {
1812                 RTE_LOG(ERR, EAL, "Could not map memory from primary process\n");
1813                 if (aslr_enabled() > 0)
1814                         RTE_LOG(ERR, EAL, "It is recommended to disable ASLR in the kernel and retry running both primary and secondary processes\n");
1815                 return -1;
1816         }
1817         return 0;
1818 }
1819
1820 int
1821 rte_eal_hugepage_init(void)
1822 {
1823         return internal_config.legacy_mem ?
1824                         eal_legacy_hugepage_init() :
1825                         eal_hugepage_init();
1826 }
1827
1828 int
1829 rte_eal_hugepage_attach(void)
1830 {
1831         return internal_config.legacy_mem ?
1832                         eal_legacy_hugepage_attach() :
1833                         eal_hugepage_attach();
1834 }
1835
1836 int
1837 rte_eal_using_phys_addrs(void)
1838 {
1839         return phys_addrs_available;
1840 }