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