mem: make base address hint OS specific
[dpdk.git] / lib / librte_eal / linux / 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 #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 free_memseg_list(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 #define MEMSEG_LIST_FMT "memseg-%" PRIu64 "k-%i-%i"
816 static int
817 alloc_memseg_list(struct rte_memseg_list *msl, uint64_t page_sz,
818                 int n_segs, int socket_id, int type_msl_idx)
819 {
820         char name[RTE_FBARRAY_NAME_LEN];
821
822         snprintf(name, sizeof(name), MEMSEG_LIST_FMT, page_sz >> 10, socket_id,
823                  type_msl_idx);
824         if (rte_fbarray_init(&msl->memseg_arr, name, n_segs,
825                         sizeof(struct rte_memseg))) {
826                 RTE_LOG(ERR, EAL, "Cannot allocate memseg list: %s\n",
827                         rte_strerror(rte_errno));
828                 return -1;
829         }
830
831         msl->page_sz = page_sz;
832         msl->socket_id = socket_id;
833         msl->base_va = NULL;
834
835         RTE_LOG(DEBUG, EAL, "Memseg list allocated: 0x%zxkB at socket %i\n",
836                         (size_t)page_sz >> 10, socket_id);
837
838         return 0;
839 }
840
841 static int
842 alloc_va_space(struct rte_memseg_list *msl)
843 {
844         uint64_t page_sz;
845         size_t mem_sz;
846         void *addr;
847         int flags = 0;
848
849         page_sz = msl->page_sz;
850         mem_sz = page_sz * msl->memseg_arr.len;
851
852         addr = eal_get_virtual_area(msl->base_va, &mem_sz, page_sz, 0, flags);
853         if (addr == NULL) {
854                 if (rte_errno == EADDRNOTAVAIL)
855                         RTE_LOG(ERR, EAL, "Could not mmap %llu bytes at [%p] - "
856                                 "please use '--" OPT_BASE_VIRTADDR "' option\n",
857                                 (unsigned long long)mem_sz, msl->base_va);
858                 else
859                         RTE_LOG(ERR, EAL, "Cannot reserve memory\n");
860                 return -1;
861         }
862         msl->base_va = addr;
863         msl->len = mem_sz;
864
865         return 0;
866 }
867
868 /*
869  * Our VA space is not preallocated yet, so preallocate it here. We need to know
870  * how many segments there are in order to map all pages into one address space,
871  * and leave appropriate holes between segments so that rte_malloc does not
872  * concatenate them into one big segment.
873  *
874  * we also need to unmap original pages to free up address space.
875  */
876 static int __rte_unused
877 prealloc_segments(struct hugepage_file *hugepages, int n_pages)
878 {
879         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
880         int cur_page, seg_start_page, end_seg, new_memseg;
881         unsigned int hpi_idx, socket, i;
882         int n_contig_segs, n_segs;
883         int msl_idx;
884
885         /* before we preallocate segments, we need to free up our VA space.
886          * we're not removing files, and we already have information about
887          * PA-contiguousness, so it is safe to unmap everything.
888          */
889         for (cur_page = 0; cur_page < n_pages; cur_page++) {
890                 struct hugepage_file *hpi = &hugepages[cur_page];
891                 munmap(hpi->orig_va, hpi->size);
892                 hpi->orig_va = NULL;
893         }
894
895         /* we cannot know how many page sizes and sockets we have discovered, so
896          * loop over all of them
897          */
898         for (hpi_idx = 0; hpi_idx < internal_config.num_hugepage_sizes;
899                         hpi_idx++) {
900                 uint64_t page_sz =
901                         internal_config.hugepage_info[hpi_idx].hugepage_sz;
902
903                 for (i = 0; i < rte_socket_count(); i++) {
904                         struct rte_memseg_list *msl;
905
906                         socket = rte_socket_id_by_idx(i);
907                         n_contig_segs = 0;
908                         n_segs = 0;
909                         seg_start_page = -1;
910
911                         for (cur_page = 0; cur_page < n_pages; cur_page++) {
912                                 struct hugepage_file *prev, *cur;
913                                 int prev_seg_start_page = -1;
914
915                                 cur = &hugepages[cur_page];
916                                 prev = cur_page == 0 ? NULL :
917                                                 &hugepages[cur_page - 1];
918
919                                 new_memseg = 0;
920                                 end_seg = 0;
921
922                                 if (cur->size == 0)
923                                         end_seg = 1;
924                                 else if (cur->socket_id != (int) socket)
925                                         end_seg = 1;
926                                 else if (cur->size != page_sz)
927                                         end_seg = 1;
928                                 else if (cur_page == 0)
929                                         new_memseg = 1;
930 #ifdef RTE_ARCH_PPC_64
931                                 /* On PPC64 architecture, the mmap always start
932                                  * from higher address to lower address. Here,
933                                  * physical addresses are in descending order.
934                                  */
935                                 else if ((prev->physaddr - cur->physaddr) !=
936                                                 cur->size)
937                                         new_memseg = 1;
938 #else
939                                 else if ((cur->physaddr - prev->physaddr) !=
940                                                 cur->size)
941                                         new_memseg = 1;
942 #endif
943                                 if (new_memseg) {
944                                         /* if we're already inside a segment,
945                                          * new segment means end of current one
946                                          */
947                                         if (seg_start_page != -1) {
948                                                 end_seg = 1;
949                                                 prev_seg_start_page =
950                                                                 seg_start_page;
951                                         }
952                                         seg_start_page = cur_page;
953                                 }
954
955                                 if (end_seg) {
956                                         if (prev_seg_start_page != -1) {
957                                                 /* we've found a new segment */
958                                                 n_contig_segs++;
959                                                 n_segs += cur_page -
960                                                         prev_seg_start_page;
961                                         } else if (seg_start_page != -1) {
962                                                 /* we didn't find new segment,
963                                                  * but did end current one
964                                                  */
965                                                 n_contig_segs++;
966                                                 n_segs += cur_page -
967                                                                 seg_start_page;
968                                                 seg_start_page = -1;
969                                                 continue;
970                                         } else {
971                                                 /* we're skipping this page */
972                                                 continue;
973                                         }
974                                 }
975                                 /* segment continues */
976                         }
977                         /* check if we missed last segment */
978                         if (seg_start_page != -1) {
979                                 n_contig_segs++;
980                                 n_segs += cur_page - seg_start_page;
981                         }
982
983                         /* if no segments were found, do not preallocate */
984                         if (n_segs == 0)
985                                 continue;
986
987                         /* we now have total number of pages that we will
988                          * allocate for this segment list. add separator pages
989                          * to the total count, and preallocate VA space.
990                          */
991                         n_segs += n_contig_segs - 1;
992
993                         /* now, preallocate VA space for these segments */
994
995                         /* first, find suitable memseg list for this */
996                         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS;
997                                         msl_idx++) {
998                                 msl = &mcfg->memsegs[msl_idx];
999
1000                                 if (msl->base_va != NULL)
1001                                         continue;
1002                                 break;
1003                         }
1004                         if (msl_idx == RTE_MAX_MEMSEG_LISTS) {
1005                                 RTE_LOG(ERR, EAL, "Not enough space in memseg lists, please increase %s\n",
1006                                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
1007                                 return -1;
1008                         }
1009
1010                         /* now, allocate fbarray itself */
1011                         if (alloc_memseg_list(msl, page_sz, n_segs, socket,
1012                                                 msl_idx) < 0)
1013                                 return -1;
1014
1015                         /* finally, allocate VA space */
1016                         if (alloc_va_space(msl) < 0)
1017                                 return -1;
1018                 }
1019         }
1020         return 0;
1021 }
1022
1023 /*
1024  * We cannot reallocate memseg lists on the fly because PPC64 stores pages
1025  * backwards, therefore we have to process the entire memseg first before
1026  * remapping it into memseg list VA space.
1027  */
1028 static int
1029 remap_needed_hugepages(struct hugepage_file *hugepages, int n_pages)
1030 {
1031         int cur_page, seg_start_page, new_memseg, ret;
1032
1033         seg_start_page = 0;
1034         for (cur_page = 0; cur_page < n_pages; cur_page++) {
1035                 struct hugepage_file *prev, *cur;
1036
1037                 new_memseg = 0;
1038
1039                 cur = &hugepages[cur_page];
1040                 prev = cur_page == 0 ? NULL : &hugepages[cur_page - 1];
1041
1042                 /* if size is zero, no more pages left */
1043                 if (cur->size == 0)
1044                         break;
1045
1046                 if (cur_page == 0)
1047                         new_memseg = 1;
1048                 else if (cur->socket_id != prev->socket_id)
1049                         new_memseg = 1;
1050                 else if (cur->size != prev->size)
1051                         new_memseg = 1;
1052 #ifdef RTE_ARCH_PPC_64
1053                 /* On PPC64 architecture, the mmap always start from higher
1054                  * address to lower address. Here, physical addresses are in
1055                  * descending order.
1056                  */
1057                 else if ((prev->physaddr - cur->physaddr) != cur->size)
1058                         new_memseg = 1;
1059 #else
1060                 else if ((cur->physaddr - prev->physaddr) != cur->size)
1061                         new_memseg = 1;
1062 #endif
1063
1064                 if (new_memseg) {
1065                         /* if this isn't the first time, remap segment */
1066                         if (cur_page != 0) {
1067                                 ret = remap_segment(hugepages, seg_start_page,
1068                                                 cur_page);
1069                                 if (ret != 0)
1070                                         return -1;
1071                         }
1072                         /* remember where we started */
1073                         seg_start_page = cur_page;
1074                 }
1075                 /* continuation of previous memseg */
1076         }
1077         /* we were stopped, but we didn't remap the last segment, do it now */
1078         if (cur_page != 0) {
1079                 ret = remap_segment(hugepages, seg_start_page,
1080                                 cur_page);
1081                 if (ret != 0)
1082                         return -1;
1083         }
1084         return 0;
1085 }
1086
1087 __rte_unused /* function is unused on 32-bit builds */
1088 static inline uint64_t
1089 get_socket_mem_size(int socket)
1090 {
1091         uint64_t size = 0;
1092         unsigned i;
1093
1094         for (i = 0; i < internal_config.num_hugepage_sizes; i++){
1095                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1096                 size += hpi->hugepage_sz * hpi->num_pages[socket];
1097         }
1098
1099         return size;
1100 }
1101
1102 /*
1103  * This function is a NUMA-aware equivalent of calc_num_pages.
1104  * It takes in the list of hugepage sizes and the
1105  * number of pages thereof, and calculates the best number of
1106  * pages of each size to fulfill the request for <memory> ram
1107  */
1108 static int
1109 calc_num_pages_per_socket(uint64_t * memory,
1110                 struct hugepage_info *hp_info,
1111                 struct hugepage_info *hp_used,
1112                 unsigned num_hp_info)
1113 {
1114         unsigned socket, j, i = 0;
1115         unsigned requested, available;
1116         int total_num_pages = 0;
1117         uint64_t remaining_mem, cur_mem;
1118         uint64_t total_mem = internal_config.memory;
1119
1120         if (num_hp_info == 0)
1121                 return -1;
1122
1123         /* if specific memory amounts per socket weren't requested */
1124         if (internal_config.force_sockets == 0) {
1125                 size_t total_size;
1126 #ifdef RTE_ARCH_64
1127                 int cpu_per_socket[RTE_MAX_NUMA_NODES];
1128                 size_t default_size;
1129                 unsigned lcore_id;
1130
1131                 /* Compute number of cores per socket */
1132                 memset(cpu_per_socket, 0, sizeof(cpu_per_socket));
1133                 RTE_LCORE_FOREACH(lcore_id) {
1134                         cpu_per_socket[rte_lcore_to_socket_id(lcore_id)]++;
1135                 }
1136
1137                 /*
1138                  * Automatically spread requested memory amongst detected sockets according
1139                  * to number of cores from cpu mask present on each socket
1140                  */
1141                 total_size = internal_config.memory;
1142                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1143
1144                         /* Set memory amount per socket */
1145                         default_size = (internal_config.memory * cpu_per_socket[socket])
1146                                         / rte_lcore_count();
1147
1148                         /* Limit to maximum available memory on socket */
1149                         default_size = RTE_MIN(default_size, get_socket_mem_size(socket));
1150
1151                         /* Update sizes */
1152                         memory[socket] = default_size;
1153                         total_size -= default_size;
1154                 }
1155
1156                 /*
1157                  * If some memory is remaining, try to allocate it by getting all
1158                  * available memory from sockets, one after the other
1159                  */
1160                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1161                         /* take whatever is available */
1162                         default_size = RTE_MIN(get_socket_mem_size(socket) - memory[socket],
1163                                                total_size);
1164
1165                         /* Update sizes */
1166                         memory[socket] += default_size;
1167                         total_size -= default_size;
1168                 }
1169 #else
1170                 /* in 32-bit mode, allocate all of the memory only on master
1171                  * lcore socket
1172                  */
1173                 total_size = internal_config.memory;
1174                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0;
1175                                 socket++) {
1176                         struct rte_config *cfg = rte_eal_get_configuration();
1177                         unsigned int master_lcore_socket;
1178
1179                         master_lcore_socket =
1180                                 rte_lcore_to_socket_id(cfg->master_lcore);
1181
1182                         if (master_lcore_socket != socket)
1183                                 continue;
1184
1185                         /* Update sizes */
1186                         memory[socket] = total_size;
1187                         break;
1188                 }
1189 #endif
1190         }
1191
1192         for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_mem != 0; socket++) {
1193                 /* skips if the memory on specific socket wasn't requested */
1194                 for (i = 0; i < num_hp_info && memory[socket] != 0; i++){
1195                         strlcpy(hp_used[i].hugedir, hp_info[i].hugedir,
1196                                 sizeof(hp_used[i].hugedir));
1197                         hp_used[i].num_pages[socket] = RTE_MIN(
1198                                         memory[socket] / hp_info[i].hugepage_sz,
1199                                         hp_info[i].num_pages[socket]);
1200
1201                         cur_mem = hp_used[i].num_pages[socket] *
1202                                         hp_used[i].hugepage_sz;
1203
1204                         memory[socket] -= cur_mem;
1205                         total_mem -= cur_mem;
1206
1207                         total_num_pages += hp_used[i].num_pages[socket];
1208
1209                         /* check if we have met all memory requests */
1210                         if (memory[socket] == 0)
1211                                 break;
1212
1213                         /* check if we have any more pages left at this size, if so
1214                          * move on to next size */
1215                         if (hp_used[i].num_pages[socket] == hp_info[i].num_pages[socket])
1216                                 continue;
1217                         /* At this point we know that there are more pages available that are
1218                          * bigger than the memory we want, so lets see if we can get enough
1219                          * from other page sizes.
1220                          */
1221                         remaining_mem = 0;
1222                         for (j = i+1; j < num_hp_info; j++)
1223                                 remaining_mem += hp_info[j].hugepage_sz *
1224                                 hp_info[j].num_pages[socket];
1225
1226                         /* is there enough other memory, if not allocate another page and quit */
1227                         if (remaining_mem < memory[socket]){
1228                                 cur_mem = RTE_MIN(memory[socket],
1229                                                 hp_info[i].hugepage_sz);
1230                                 memory[socket] -= cur_mem;
1231                                 total_mem -= cur_mem;
1232                                 hp_used[i].num_pages[socket]++;
1233                                 total_num_pages++;
1234                                 break; /* we are done with this socket*/
1235                         }
1236                 }
1237                 /* if we didn't satisfy all memory requirements per socket */
1238                 if (memory[socket] > 0 &&
1239                                 internal_config.socket_mem[socket] != 0) {
1240                         /* to prevent icc errors */
1241                         requested = (unsigned) (internal_config.socket_mem[socket] /
1242                                         0x100000);
1243                         available = requested -
1244                                         ((unsigned) (memory[socket] / 0x100000));
1245                         RTE_LOG(ERR, EAL, "Not enough memory available on socket %u! "
1246                                         "Requested: %uMB, available: %uMB\n", socket,
1247                                         requested, available);
1248                         return -1;
1249                 }
1250         }
1251
1252         /* if we didn't satisfy total memory requirements */
1253         if (total_mem > 0) {
1254                 requested = (unsigned) (internal_config.memory / 0x100000);
1255                 available = requested - (unsigned) (total_mem / 0x100000);
1256                 RTE_LOG(ERR, EAL, "Not enough memory available! Requested: %uMB,"
1257                                 " available: %uMB\n", requested, available);
1258                 return -1;
1259         }
1260         return total_num_pages;
1261 }
1262
1263 static inline size_t
1264 eal_get_hugepage_mem_size(void)
1265 {
1266         uint64_t size = 0;
1267         unsigned i, j;
1268
1269         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1270                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1271                 if (strnlen(hpi->hugedir, sizeof(hpi->hugedir)) != 0) {
1272                         for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1273                                 size += hpi->hugepage_sz * hpi->num_pages[j];
1274                         }
1275                 }
1276         }
1277
1278         return (size < SIZE_MAX) ? (size_t)(size) : SIZE_MAX;
1279 }
1280
1281 static struct sigaction huge_action_old;
1282 static int huge_need_recover;
1283
1284 static void
1285 huge_register_sigbus(void)
1286 {
1287         sigset_t mask;
1288         struct sigaction action;
1289
1290         sigemptyset(&mask);
1291         sigaddset(&mask, SIGBUS);
1292         action.sa_flags = 0;
1293         action.sa_mask = mask;
1294         action.sa_handler = huge_sigbus_handler;
1295
1296         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
1297 }
1298
1299 static void
1300 huge_recover_sigbus(void)
1301 {
1302         if (huge_need_recover) {
1303                 sigaction(SIGBUS, &huge_action_old, NULL);
1304                 huge_need_recover = 0;
1305         }
1306 }
1307
1308 /*
1309  * Prepare physical memory mapping: fill configuration structure with
1310  * these infos, return 0 on success.
1311  *  1. map N huge pages in separate files in hugetlbfs
1312  *  2. find associated physical addr
1313  *  3. find associated NUMA socket ID
1314  *  4. sort all huge pages by physical address
1315  *  5. remap these N huge pages in the correct order
1316  *  6. unmap the first mapping
1317  *  7. fill memsegs in configuration with contiguous zones
1318  */
1319 static int
1320 eal_legacy_hugepage_init(void)
1321 {
1322         struct rte_mem_config *mcfg;
1323         struct hugepage_file *hugepage = NULL, *tmp_hp = NULL;
1324         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1325         struct rte_fbarray *arr;
1326         struct rte_memseg *ms;
1327
1328         uint64_t memory[RTE_MAX_NUMA_NODES];
1329
1330         unsigned hp_offset;
1331         int i, j;
1332         int nr_hugefiles, nr_hugepages = 0;
1333         void *addr;
1334
1335         memset(used_hp, 0, sizeof(used_hp));
1336
1337         /* get pointer to global configuration */
1338         mcfg = rte_eal_get_configuration()->mem_config;
1339
1340         /* hugetlbfs can be disabled */
1341         if (internal_config.no_hugetlbfs) {
1342                 struct rte_memseg_list *msl;
1343                 int n_segs, cur_seg, fd, flags;
1344 #ifdef MEMFD_SUPPORTED
1345                 int memfd;
1346 #endif
1347                 uint64_t page_sz;
1348
1349                 /* nohuge mode is legacy mode */
1350                 internal_config.legacy_mem = 1;
1351
1352                 /* nohuge mode is single-file segments mode */
1353                 internal_config.single_file_segments = 1;
1354
1355                 /* create a memseg list */
1356                 msl = &mcfg->memsegs[0];
1357
1358                 page_sz = RTE_PGSIZE_4K;
1359                 n_segs = internal_config.memory / page_sz;
1360
1361                 if (rte_fbarray_init(&msl->memseg_arr, "nohugemem", n_segs,
1362                                         sizeof(struct rte_memseg))) {
1363                         RTE_LOG(ERR, EAL, "Cannot allocate memseg list\n");
1364                         return -1;
1365                 }
1366
1367                 /* set up parameters for anonymous mmap */
1368                 fd = -1;
1369                 flags = MAP_PRIVATE | MAP_ANONYMOUS;
1370
1371 #ifdef MEMFD_SUPPORTED
1372                 /* create a memfd and store it in the segment fd table */
1373                 memfd = memfd_create("nohuge", 0);
1374                 if (memfd < 0) {
1375                         RTE_LOG(DEBUG, EAL, "Cannot create memfd: %s\n",
1376                                         strerror(errno));
1377                         RTE_LOG(DEBUG, EAL, "Falling back to anonymous map\n");
1378                 } else {
1379                         /* we got an fd - now resize it */
1380                         if (ftruncate(memfd, internal_config.memory) < 0) {
1381                                 RTE_LOG(ERR, EAL, "Cannot resize memfd: %s\n",
1382                                                 strerror(errno));
1383                                 RTE_LOG(ERR, EAL, "Falling back to anonymous map\n");
1384                                 close(memfd);
1385                         } else {
1386                                 /* creating memfd-backed file was successful.
1387                                  * we want changes to memfd to be visible to
1388                                  * other processes (such as vhost backend), so
1389                                  * map it as shared memory.
1390                                  */
1391                                 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1392                                 fd = memfd;
1393                                 flags = MAP_SHARED;
1394                         }
1395                 }
1396 #endif
1397                 addr = mmap(NULL, internal_config.memory, PROT_READ | PROT_WRITE,
1398                                 flags, fd, 0);
1399                 if (addr == MAP_FAILED) {
1400                         RTE_LOG(ERR, EAL, "%s: mmap() failed: %s\n", __func__,
1401                                         strerror(errno));
1402                         return -1;
1403                 }
1404                 msl->base_va = addr;
1405                 msl->page_sz = page_sz;
1406                 msl->socket_id = 0;
1407                 msl->len = internal_config.memory;
1408
1409                 /* we're in single-file segments mode, so only the segment list
1410                  * fd needs to be set up.
1411                  */
1412                 if (fd != -1) {
1413                         if (eal_memalloc_set_seg_list_fd(0, fd) < 0) {
1414                                 RTE_LOG(ERR, EAL, "Cannot set up segment list fd\n");
1415                                 /* not a serious error, proceed */
1416                         }
1417                 }
1418
1419                 /* populate memsegs. each memseg is one page long */
1420                 for (cur_seg = 0; cur_seg < n_segs; cur_seg++) {
1421                         arr = &msl->memseg_arr;
1422
1423                         ms = rte_fbarray_get(arr, cur_seg);
1424                         if (rte_eal_iova_mode() == RTE_IOVA_VA)
1425                                 ms->iova = (uintptr_t)addr;
1426                         else
1427                                 ms->iova = RTE_BAD_IOVA;
1428                         ms->addr = addr;
1429                         ms->hugepage_sz = page_sz;
1430                         ms->socket_id = 0;
1431                         ms->len = page_sz;
1432
1433                         rte_fbarray_set_used(arr, cur_seg);
1434
1435                         addr = RTE_PTR_ADD(addr, (size_t)page_sz);
1436                 }
1437                 if (mcfg->dma_maskbits &&
1438                     rte_mem_check_dma_mask_thread_unsafe(mcfg->dma_maskbits)) {
1439                         RTE_LOG(ERR, EAL,
1440                                 "%s(): couldn't allocate memory due to IOVA exceeding limits of current DMA mask.\n",
1441                                 __func__);
1442                         if (rte_eal_iova_mode() == RTE_IOVA_VA &&
1443                             rte_eal_using_phys_addrs())
1444                                 RTE_LOG(ERR, EAL,
1445                                         "%s(): Please try initializing EAL with --iova-mode=pa parameter.\n",
1446                                         __func__);
1447                         goto fail;
1448                 }
1449                 return 0;
1450         }
1451
1452         /* calculate total number of hugepages available. at this point we haven't
1453          * yet started sorting them so they all are on socket 0 */
1454         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1455                 /* meanwhile, also initialize used_hp hugepage sizes in used_hp */
1456                 used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;
1457
1458                 nr_hugepages += internal_config.hugepage_info[i].num_pages[0];
1459         }
1460
1461         /*
1462          * allocate a memory area for hugepage table.
1463          * this isn't shared memory yet. due to the fact that we need some
1464          * processing done on these pages, shared memory will be created
1465          * at a later stage.
1466          */
1467         tmp_hp = malloc(nr_hugepages * sizeof(struct hugepage_file));
1468         if (tmp_hp == NULL)
1469                 goto fail;
1470
1471         memset(tmp_hp, 0, nr_hugepages * sizeof(struct hugepage_file));
1472
1473         hp_offset = 0; /* where we start the current page size entries */
1474
1475         huge_register_sigbus();
1476
1477         /* make a copy of socket_mem, needed for balanced allocation. */
1478         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1479                 memory[i] = internal_config.socket_mem[i];
1480
1481         /* map all hugepages and sort them */
1482         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
1483                 unsigned pages_old, pages_new;
1484                 struct hugepage_info *hpi;
1485
1486                 /*
1487                  * we don't yet mark hugepages as used at this stage, so
1488                  * we just map all hugepages available to the system
1489                  * all hugepages are still located on socket 0
1490                  */
1491                 hpi = &internal_config.hugepage_info[i];
1492
1493                 if (hpi->num_pages[0] == 0)
1494                         continue;
1495
1496                 /* map all hugepages available */
1497                 pages_old = hpi->num_pages[0];
1498                 pages_new = map_all_hugepages(&tmp_hp[hp_offset], hpi, memory);
1499                 if (pages_new < pages_old) {
1500                         RTE_LOG(DEBUG, EAL,
1501                                 "%d not %d hugepages of size %u MB allocated\n",
1502                                 pages_new, pages_old,
1503                                 (unsigned)(hpi->hugepage_sz / 0x100000));
1504
1505                         int pages = pages_old - pages_new;
1506
1507                         nr_hugepages -= pages;
1508                         hpi->num_pages[0] = pages_new;
1509                         if (pages_new == 0)
1510                                 continue;
1511                 }
1512
1513                 if (rte_eal_using_phys_addrs() &&
1514                                 rte_eal_iova_mode() != RTE_IOVA_VA) {
1515                         /* find physical addresses for each hugepage */
1516                         if (find_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1517                                 RTE_LOG(DEBUG, EAL, "Failed to find phys addr "
1518                                         "for %u MB pages\n",
1519                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1520                                 goto fail;
1521                         }
1522                 } else {
1523                         /* set physical addresses for each hugepage */
1524                         if (set_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1525                                 RTE_LOG(DEBUG, EAL, "Failed to set phys addr "
1526                                         "for %u MB pages\n",
1527                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1528                                 goto fail;
1529                         }
1530                 }
1531
1532                 if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
1533                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
1534                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1535                         goto fail;
1536                 }
1537
1538                 qsort(&tmp_hp[hp_offset], hpi->num_pages[0],
1539                       sizeof(struct hugepage_file), cmp_physaddr);
1540
1541                 /* we have processed a num of hugepages of this size, so inc offset */
1542                 hp_offset += hpi->num_pages[0];
1543         }
1544
1545         huge_recover_sigbus();
1546
1547         if (internal_config.memory == 0 && internal_config.force_sockets == 0)
1548                 internal_config.memory = eal_get_hugepage_mem_size();
1549
1550         nr_hugefiles = nr_hugepages;
1551
1552
1553         /* clean out the numbers of pages */
1554         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
1555                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
1556                         internal_config.hugepage_info[i].num_pages[j] = 0;
1557
1558         /* get hugepages for each socket */
1559         for (i = 0; i < nr_hugefiles; i++) {
1560                 int socket = tmp_hp[i].socket_id;
1561
1562                 /* find a hugepage info with right size and increment num_pages */
1563                 const int nb_hpsizes = RTE_MIN(MAX_HUGEPAGE_SIZES,
1564                                 (int)internal_config.num_hugepage_sizes);
1565                 for (j = 0; j < nb_hpsizes; j++) {
1566                         if (tmp_hp[i].size ==
1567                                         internal_config.hugepage_info[j].hugepage_sz) {
1568                                 internal_config.hugepage_info[j].num_pages[socket]++;
1569                         }
1570                 }
1571         }
1572
1573         /* make a copy of socket_mem, needed for number of pages calculation */
1574         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1575                 memory[i] = internal_config.socket_mem[i];
1576
1577         /* calculate final number of pages */
1578         nr_hugepages = calc_num_pages_per_socket(memory,
1579                         internal_config.hugepage_info, used_hp,
1580                         internal_config.num_hugepage_sizes);
1581
1582         /* error if not enough memory available */
1583         if (nr_hugepages < 0)
1584                 goto fail;
1585
1586         /* reporting in! */
1587         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1588                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1589                         if (used_hp[i].num_pages[j] > 0) {
1590                                 RTE_LOG(DEBUG, EAL,
1591                                         "Requesting %u pages of size %uMB"
1592                                         " from socket %i\n",
1593                                         used_hp[i].num_pages[j],
1594                                         (unsigned)
1595                                         (used_hp[i].hugepage_sz / 0x100000),
1596                                         j);
1597                         }
1598                 }
1599         }
1600
1601         /* create shared memory */
1602         hugepage = create_shared_memory(eal_hugepage_data_path(),
1603                         nr_hugefiles * sizeof(struct hugepage_file));
1604
1605         if (hugepage == NULL) {
1606                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
1607                 goto fail;
1608         }
1609         memset(hugepage, 0, nr_hugefiles * sizeof(struct hugepage_file));
1610
1611         /*
1612          * unmap pages that we won't need (looks at used_hp).
1613          * also, sets final_va to NULL on pages that were unmapped.
1614          */
1615         if (unmap_unneeded_hugepages(tmp_hp, used_hp,
1616                         internal_config.num_hugepage_sizes) < 0) {
1617                 RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
1618                 goto fail;
1619         }
1620
1621         /*
1622          * copy stuff from malloc'd hugepage* to the actual shared memory.
1623          * this procedure only copies those hugepages that have orig_va
1624          * not NULL. has overflow protection.
1625          */
1626         if (copy_hugepages_to_shared_mem(hugepage, nr_hugefiles,
1627                         tmp_hp, nr_hugefiles) < 0) {
1628                 RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
1629                 goto fail;
1630         }
1631
1632 #ifndef RTE_ARCH_64
1633         /* for legacy 32-bit mode, we did not preallocate VA space, so do it */
1634         if (internal_config.legacy_mem &&
1635                         prealloc_segments(hugepage, nr_hugefiles)) {
1636                 RTE_LOG(ERR, EAL, "Could not preallocate VA space for hugepages\n");
1637                 goto fail;
1638         }
1639 #endif
1640
1641         /* remap all pages we do need into memseg list VA space, so that those
1642          * pages become first-class citizens in DPDK memory subsystem
1643          */
1644         if (remap_needed_hugepages(hugepage, nr_hugefiles)) {
1645                 RTE_LOG(ERR, EAL, "Couldn't remap hugepage files into memseg lists\n");
1646                 goto fail;
1647         }
1648
1649         /* free the hugepage backing files */
1650         if (internal_config.hugepage_unlink &&
1651                 unlink_hugepage_files(tmp_hp, internal_config.num_hugepage_sizes) < 0) {
1652                 RTE_LOG(ERR, EAL, "Unlinking hugepage files failed!\n");
1653                 goto fail;
1654         }
1655
1656         /* free the temporary hugepage table */
1657         free(tmp_hp);
1658         tmp_hp = NULL;
1659
1660         munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1661         hugepage = NULL;
1662
1663         /* we're not going to allocate more pages, so release VA space for
1664          * unused memseg lists
1665          */
1666         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
1667                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
1668                 size_t mem_sz;
1669
1670                 /* skip inactive lists */
1671                 if (msl->base_va == NULL)
1672                         continue;
1673                 /* skip lists where there is at least one page allocated */
1674                 if (msl->memseg_arr.count > 0)
1675                         continue;
1676                 /* this is an unused list, deallocate it */
1677                 mem_sz = msl->len;
1678                 munmap(msl->base_va, mem_sz);
1679                 msl->base_va = NULL;
1680
1681                 /* destroy backing fbarray */
1682                 rte_fbarray_destroy(&msl->memseg_arr);
1683         }
1684
1685         if (mcfg->dma_maskbits &&
1686             rte_mem_check_dma_mask_thread_unsafe(mcfg->dma_maskbits)) {
1687                 RTE_LOG(ERR, EAL,
1688                         "%s(): couldn't allocate memory due to IOVA exceeding limits of current DMA mask.\n",
1689                         __func__);
1690                 goto fail;
1691         }
1692
1693         return 0;
1694
1695 fail:
1696         huge_recover_sigbus();
1697         free(tmp_hp);
1698         if (hugepage != NULL)
1699                 munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1700
1701         return -1;
1702 }
1703
1704 static int __rte_unused
1705 hugepage_count_walk(const struct rte_memseg_list *msl, void *arg)
1706 {
1707         struct hugepage_info *hpi = arg;
1708
1709         if (msl->page_sz != hpi->hugepage_sz)
1710                 return 0;
1711
1712         hpi->num_pages[msl->socket_id] += msl->memseg_arr.len;
1713         return 0;
1714 }
1715
1716 static int
1717 limits_callback(int socket_id, size_t cur_limit, size_t new_len)
1718 {
1719         RTE_SET_USED(socket_id);
1720         RTE_SET_USED(cur_limit);
1721         RTE_SET_USED(new_len);
1722         return -1;
1723 }
1724
1725 static int
1726 eal_hugepage_init(void)
1727 {
1728         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1729         uint64_t memory[RTE_MAX_NUMA_NODES];
1730         int hp_sz_idx, socket_id;
1731
1732         memset(used_hp, 0, sizeof(used_hp));
1733
1734         for (hp_sz_idx = 0;
1735                         hp_sz_idx < (int) internal_config.num_hugepage_sizes;
1736                         hp_sz_idx++) {
1737 #ifndef RTE_ARCH_64
1738                 struct hugepage_info dummy;
1739                 unsigned int i;
1740 #endif
1741                 /* also initialize used_hp hugepage sizes in used_hp */
1742                 struct hugepage_info *hpi;
1743                 hpi = &internal_config.hugepage_info[hp_sz_idx];
1744                 used_hp[hp_sz_idx].hugepage_sz = hpi->hugepage_sz;
1745
1746 #ifndef RTE_ARCH_64
1747                 /* for 32-bit, limit number of pages on socket to whatever we've
1748                  * preallocated, as we cannot allocate more.
1749                  */
1750                 memset(&dummy, 0, sizeof(dummy));
1751                 dummy.hugepage_sz = hpi->hugepage_sz;
1752                 if (rte_memseg_list_walk(hugepage_count_walk, &dummy) < 0)
1753                         return -1;
1754
1755                 for (i = 0; i < RTE_DIM(dummy.num_pages); i++) {
1756                         hpi->num_pages[i] = RTE_MIN(hpi->num_pages[i],
1757                                         dummy.num_pages[i]);
1758                 }
1759 #endif
1760         }
1761
1762         /* make a copy of socket_mem, needed for balanced allocation. */
1763         for (hp_sz_idx = 0; hp_sz_idx < RTE_MAX_NUMA_NODES; hp_sz_idx++)
1764                 memory[hp_sz_idx] = internal_config.socket_mem[hp_sz_idx];
1765
1766         /* calculate final number of pages */
1767         if (calc_num_pages_per_socket(memory,
1768                         internal_config.hugepage_info, used_hp,
1769                         internal_config.num_hugepage_sizes) < 0)
1770                 return -1;
1771
1772         for (hp_sz_idx = 0;
1773                         hp_sz_idx < (int)internal_config.num_hugepage_sizes;
1774                         hp_sz_idx++) {
1775                 for (socket_id = 0; socket_id < RTE_MAX_NUMA_NODES;
1776                                 socket_id++) {
1777                         struct rte_memseg **pages;
1778                         struct hugepage_info *hpi = &used_hp[hp_sz_idx];
1779                         unsigned int num_pages = hpi->num_pages[socket_id];
1780                         unsigned int num_pages_alloc;
1781
1782                         if (num_pages == 0)
1783                                 continue;
1784
1785                         RTE_LOG(DEBUG, EAL, "Allocating %u pages of size %" PRIu64 "M on socket %i\n",
1786                                 num_pages, hpi->hugepage_sz >> 20, socket_id);
1787
1788                         /* we may not be able to allocate all pages in one go,
1789                          * because we break up our memory map into multiple
1790                          * memseg lists. therefore, try allocating multiple
1791                          * times and see if we can get the desired number of
1792                          * pages from multiple allocations.
1793                          */
1794
1795                         num_pages_alloc = 0;
1796                         do {
1797                                 int i, cur_pages, needed;
1798
1799                                 needed = num_pages - num_pages_alloc;
1800
1801                                 pages = malloc(sizeof(*pages) * needed);
1802
1803                                 /* do not request exact number of pages */
1804                                 cur_pages = eal_memalloc_alloc_seg_bulk(pages,
1805                                                 needed, hpi->hugepage_sz,
1806                                                 socket_id, false);
1807                                 if (cur_pages <= 0) {
1808                                         free(pages);
1809                                         return -1;
1810                                 }
1811
1812                                 /* mark preallocated pages as unfreeable */
1813                                 for (i = 0; i < cur_pages; i++) {
1814                                         struct rte_memseg *ms = pages[i];
1815                                         ms->flags |= RTE_MEMSEG_FLAG_DO_NOT_FREE;
1816                                 }
1817                                 free(pages);
1818
1819                                 num_pages_alloc += cur_pages;
1820                         } while (num_pages_alloc != num_pages);
1821                 }
1822         }
1823         /* if socket limits were specified, set them */
1824         if (internal_config.force_socket_limits) {
1825                 unsigned int i;
1826                 for (i = 0; i < RTE_MAX_NUMA_NODES; i++) {
1827                         uint64_t limit = internal_config.socket_limit[i];
1828                         if (limit == 0)
1829                                 continue;
1830                         if (rte_mem_alloc_validator_register("socket-limit",
1831                                         limits_callback, i, limit))
1832                                 RTE_LOG(ERR, EAL, "Failed to register socket limits validator callback\n");
1833                 }
1834         }
1835         return 0;
1836 }
1837
1838 /*
1839  * uses fstat to report the size of a file on disk
1840  */
1841 static off_t
1842 getFileSize(int fd)
1843 {
1844         struct stat st;
1845         if (fstat(fd, &st) < 0)
1846                 return 0;
1847         return st.st_size;
1848 }
1849
1850 /*
1851  * This creates the memory mappings in the secondary process to match that of
1852  * the server process. It goes through each memory segment in the DPDK runtime
1853  * configuration and finds the hugepages which form that segment, mapping them
1854  * in order to form a contiguous block in the virtual memory space
1855  */
1856 static int
1857 eal_legacy_hugepage_attach(void)
1858 {
1859         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1860         struct hugepage_file *hp = NULL;
1861         unsigned int num_hp = 0;
1862         unsigned int i = 0;
1863         unsigned int cur_seg;
1864         off_t size = 0;
1865         int fd, fd_hugepage = -1;
1866
1867         if (aslr_enabled() > 0) {
1868                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
1869                                 "(ASLR) is enabled in the kernel.\n");
1870                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
1871                                 "into secondary processes\n");
1872         }
1873
1874         fd_hugepage = open(eal_hugepage_data_path(), O_RDONLY);
1875         if (fd_hugepage < 0) {
1876                 RTE_LOG(ERR, EAL, "Could not open %s\n",
1877                                 eal_hugepage_data_path());
1878                 goto error;
1879         }
1880
1881         size = getFileSize(fd_hugepage);
1882         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
1883         if (hp == MAP_FAILED) {
1884                 RTE_LOG(ERR, EAL, "Could not mmap %s\n",
1885                                 eal_hugepage_data_path());
1886                 goto error;
1887         }
1888
1889         num_hp = size / sizeof(struct hugepage_file);
1890         RTE_LOG(DEBUG, EAL, "Analysing %u files\n", num_hp);
1891
1892         /* map all segments into memory to make sure we get the addrs. the
1893          * segments themselves are already in memseg list (which is shared and
1894          * has its VA space already preallocated), so we just need to map
1895          * everything into correct addresses.
1896          */
1897         for (i = 0; i < num_hp; i++) {
1898                 struct hugepage_file *hf = &hp[i];
1899                 size_t map_sz = hf->size;
1900                 void *map_addr = hf->final_va;
1901                 int msl_idx, ms_idx;
1902                 struct rte_memseg_list *msl;
1903                 struct rte_memseg *ms;
1904
1905                 /* if size is zero, no more pages left */
1906                 if (map_sz == 0)
1907                         break;
1908
1909                 fd = open(hf->filepath, O_RDWR);
1910                 if (fd < 0) {
1911                         RTE_LOG(ERR, EAL, "Could not open %s: %s\n",
1912                                 hf->filepath, strerror(errno));
1913                         goto error;
1914                 }
1915
1916                 map_addr = mmap(map_addr, map_sz, PROT_READ | PROT_WRITE,
1917                                 MAP_SHARED | MAP_FIXED, fd, 0);
1918                 if (map_addr == MAP_FAILED) {
1919                         RTE_LOG(ERR, EAL, "Could not map %s: %s\n",
1920                                 hf->filepath, strerror(errno));
1921                         goto fd_error;
1922                 }
1923
1924                 /* set shared lock on the file. */
1925                 if (flock(fd, LOCK_SH) < 0) {
1926                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed: %s\n",
1927                                 __func__, strerror(errno));
1928                         goto fd_error;
1929                 }
1930
1931                 /* find segment data */
1932                 msl = rte_mem_virt2memseg_list(map_addr);
1933                 if (msl == NULL) {
1934                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg list\n",
1935                                 __func__);
1936                         goto fd_error;
1937                 }
1938                 ms = rte_mem_virt2memseg(map_addr, msl);
1939                 if (ms == NULL) {
1940                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg\n",
1941                                 __func__);
1942                         goto fd_error;
1943                 }
1944
1945                 msl_idx = msl - mcfg->memsegs;
1946                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
1947                 if (ms_idx < 0) {
1948                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg idx\n",
1949                                 __func__);
1950                         goto fd_error;
1951                 }
1952
1953                 /* store segment fd internally */
1954                 if (eal_memalloc_set_seg_fd(msl_idx, ms_idx, fd) < 0)
1955                         RTE_LOG(ERR, EAL, "Could not store segment fd: %s\n",
1956                                 rte_strerror(rte_errno));
1957         }
1958         /* unmap the hugepage config file, since we are done using it */
1959         munmap(hp, size);
1960         close(fd_hugepage);
1961         return 0;
1962
1963 fd_error:
1964         close(fd);
1965 error:
1966         /* map all segments into memory to make sure we get the addrs */
1967         cur_seg = 0;
1968         for (cur_seg = 0; cur_seg < i; cur_seg++) {
1969                 struct hugepage_file *hf = &hp[i];
1970                 size_t map_sz = hf->size;
1971                 void *map_addr = hf->final_va;
1972
1973                 munmap(map_addr, map_sz);
1974         }
1975         if (hp != NULL && hp != MAP_FAILED)
1976                 munmap(hp, size);
1977         if (fd_hugepage >= 0)
1978                 close(fd_hugepage);
1979         return -1;
1980 }
1981
1982 static int
1983 eal_hugepage_attach(void)
1984 {
1985         if (eal_memalloc_sync_with_primary()) {
1986                 RTE_LOG(ERR, EAL, "Could not map memory from primary process\n");
1987                 if (aslr_enabled() > 0)
1988                         RTE_LOG(ERR, EAL, "It is recommended to disable ASLR in the kernel and retry running both primary and secondary processes\n");
1989                 return -1;
1990         }
1991         return 0;
1992 }
1993
1994 int
1995 rte_eal_hugepage_init(void)
1996 {
1997         return internal_config.legacy_mem ?
1998                         eal_legacy_hugepage_init() :
1999                         eal_hugepage_init();
2000 }
2001
2002 int
2003 rte_eal_hugepage_attach(void)
2004 {
2005         return internal_config.legacy_mem ?
2006                         eal_legacy_hugepage_attach() :
2007                         eal_hugepage_attach();
2008 }
2009
2010 int
2011 rte_eal_using_phys_addrs(void)
2012 {
2013         if (phys_addrs_available == -1) {
2014                 uint64_t tmp = 0;
2015
2016                 if (rte_eal_has_hugepages() != 0 &&
2017                     rte_mem_virt2phy(&tmp) != RTE_BAD_PHYS_ADDR)
2018                         phys_addrs_available = 1;
2019                 else
2020                         phys_addrs_available = 0;
2021         }
2022         return phys_addrs_available;
2023 }
2024
2025 static int __rte_unused
2026 memseg_primary_init_32(void)
2027 {
2028         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2029         int active_sockets, hpi_idx, msl_idx = 0;
2030         unsigned int socket_id, i;
2031         struct rte_memseg_list *msl;
2032         uint64_t extra_mem_per_socket, total_extra_mem, total_requested_mem;
2033         uint64_t max_mem;
2034
2035         /* no-huge does not need this at all */
2036         if (internal_config.no_hugetlbfs)
2037                 return 0;
2038
2039         /* this is a giant hack, but desperate times call for desperate
2040          * measures. in legacy 32-bit mode, we cannot preallocate VA space,
2041          * because having upwards of 2 gigabytes of VA space already mapped will
2042          * interfere with our ability to map and sort hugepages.
2043          *
2044          * therefore, in legacy 32-bit mode, we will be initializing memseg
2045          * lists much later - in eal_memory.c, right after we unmap all the
2046          * unneeded pages. this will not affect secondary processes, as those
2047          * should be able to mmap the space without (too many) problems.
2048          */
2049         if (internal_config.legacy_mem)
2050                 return 0;
2051
2052         /* 32-bit mode is a very special case. we cannot know in advance where
2053          * the user will want to allocate their memory, so we have to do some
2054          * heuristics.
2055          */
2056         active_sockets = 0;
2057         total_requested_mem = 0;
2058         if (internal_config.force_sockets)
2059                 for (i = 0; i < rte_socket_count(); i++) {
2060                         uint64_t mem;
2061
2062                         socket_id = rte_socket_id_by_idx(i);
2063                         mem = internal_config.socket_mem[socket_id];
2064
2065                         if (mem == 0)
2066                                 continue;
2067
2068                         active_sockets++;
2069                         total_requested_mem += mem;
2070                 }
2071         else
2072                 total_requested_mem = internal_config.memory;
2073
2074         max_mem = (uint64_t)RTE_MAX_MEM_MB << 20;
2075         if (total_requested_mem > max_mem) {
2076                 RTE_LOG(ERR, EAL, "Invalid parameters: 32-bit process can at most use %uM of memory\n",
2077                                 (unsigned int)(max_mem >> 20));
2078                 return -1;
2079         }
2080         total_extra_mem = max_mem - total_requested_mem;
2081         extra_mem_per_socket = active_sockets == 0 ? total_extra_mem :
2082                         total_extra_mem / active_sockets;
2083
2084         /* the allocation logic is a little bit convoluted, but here's how it
2085          * works, in a nutshell:
2086          *  - if user hasn't specified on which sockets to allocate memory via
2087          *    --socket-mem, we allocate all of our memory on master core socket.
2088          *  - if user has specified sockets to allocate memory on, there may be
2089          *    some "unused" memory left (e.g. if user has specified --socket-mem
2090          *    such that not all memory adds up to 2 gigabytes), so add it to all
2091          *    sockets that are in use equally.
2092          *
2093          * page sizes are sorted by size in descending order, so we can safely
2094          * assume that we dispense with bigger page sizes first.
2095          */
2096
2097         /* create memseg lists */
2098         for (i = 0; i < rte_socket_count(); i++) {
2099                 int hp_sizes = (int) internal_config.num_hugepage_sizes;
2100                 uint64_t max_socket_mem, cur_socket_mem;
2101                 unsigned int master_lcore_socket;
2102                 struct rte_config *cfg = rte_eal_get_configuration();
2103                 bool skip;
2104
2105                 socket_id = rte_socket_id_by_idx(i);
2106
2107 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2108                 /* we can still sort pages by socket in legacy mode */
2109                 if (!internal_config.legacy_mem && socket_id > 0)
2110                         break;
2111 #endif
2112
2113                 /* if we didn't specifically request memory on this socket */
2114                 skip = active_sockets != 0 &&
2115                                 internal_config.socket_mem[socket_id] == 0;
2116                 /* ...or if we didn't specifically request memory on *any*
2117                  * socket, and this is not master lcore
2118                  */
2119                 master_lcore_socket = rte_lcore_to_socket_id(cfg->master_lcore);
2120                 skip |= active_sockets == 0 && socket_id != master_lcore_socket;
2121
2122                 if (skip) {
2123                         RTE_LOG(DEBUG, EAL, "Will not preallocate memory on socket %u\n",
2124                                         socket_id);
2125                         continue;
2126                 }
2127
2128                 /* max amount of memory on this socket */
2129                 max_socket_mem = (active_sockets != 0 ?
2130                                         internal_config.socket_mem[socket_id] :
2131                                         internal_config.memory) +
2132                                         extra_mem_per_socket;
2133                 cur_socket_mem = 0;
2134
2135                 for (hpi_idx = 0; hpi_idx < hp_sizes; hpi_idx++) {
2136                         uint64_t max_pagesz_mem, cur_pagesz_mem = 0;
2137                         uint64_t hugepage_sz;
2138                         struct hugepage_info *hpi;
2139                         int type_msl_idx, max_segs, total_segs = 0;
2140
2141                         hpi = &internal_config.hugepage_info[hpi_idx];
2142                         hugepage_sz = hpi->hugepage_sz;
2143
2144                         /* check if pages are actually available */
2145                         if (hpi->num_pages[socket_id] == 0)
2146                                 continue;
2147
2148                         max_segs = RTE_MAX_MEMSEG_PER_TYPE;
2149                         max_pagesz_mem = max_socket_mem - cur_socket_mem;
2150
2151                         /* make it multiple of page size */
2152                         max_pagesz_mem = RTE_ALIGN_FLOOR(max_pagesz_mem,
2153                                         hugepage_sz);
2154
2155                         RTE_LOG(DEBUG, EAL, "Attempting to preallocate "
2156                                         "%" PRIu64 "M on socket %i\n",
2157                                         max_pagesz_mem >> 20, socket_id);
2158
2159                         type_msl_idx = 0;
2160                         while (cur_pagesz_mem < max_pagesz_mem &&
2161                                         total_segs < max_segs) {
2162                                 uint64_t cur_mem;
2163                                 unsigned int n_segs;
2164
2165                                 if (msl_idx >= RTE_MAX_MEMSEG_LISTS) {
2166                                         RTE_LOG(ERR, EAL,
2167                                                 "No more space in memseg lists, please increase %s\n",
2168                                                 RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2169                                         return -1;
2170                                 }
2171
2172                                 msl = &mcfg->memsegs[msl_idx];
2173
2174                                 cur_mem = get_mem_amount(hugepage_sz,
2175                                                 max_pagesz_mem);
2176                                 n_segs = cur_mem / hugepage_sz;
2177
2178                                 if (alloc_memseg_list(msl, hugepage_sz, n_segs,
2179                                                 socket_id, type_msl_idx)) {
2180                                         /* failing to allocate a memseg list is
2181                                          * a serious error.
2182                                          */
2183                                         RTE_LOG(ERR, EAL, "Cannot allocate memseg list\n");
2184                                         return -1;
2185                                 }
2186
2187                                 if (alloc_va_space(msl)) {
2188                                         /* if we couldn't allocate VA space, we
2189                                          * can try with smaller page sizes.
2190                                          */
2191                                         RTE_LOG(ERR, EAL, "Cannot allocate VA space for memseg list, retrying with different page size\n");
2192                                         /* deallocate memseg list */
2193                                         if (free_memseg_list(msl))
2194                                                 return -1;
2195                                         break;
2196                                 }
2197
2198                                 total_segs += msl->memseg_arr.len;
2199                                 cur_pagesz_mem = total_segs * hugepage_sz;
2200                                 type_msl_idx++;
2201                                 msl_idx++;
2202                         }
2203                         cur_socket_mem += cur_pagesz_mem;
2204                 }
2205                 if (cur_socket_mem == 0) {
2206                         RTE_LOG(ERR, EAL, "Cannot allocate VA space on socket %u\n",
2207                                 socket_id);
2208                         return -1;
2209                 }
2210         }
2211
2212         return 0;
2213 }
2214
2215 static int __rte_unused
2216 memseg_primary_init(void)
2217 {
2218         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2219         struct memtype {
2220                 uint64_t page_sz;
2221                 int socket_id;
2222         } *memtypes = NULL;
2223         int i, hpi_idx, msl_idx, ret = -1; /* fail unless told to succeed */
2224         struct rte_memseg_list *msl;
2225         uint64_t max_mem, max_mem_per_type;
2226         unsigned int max_seglists_per_type;
2227         unsigned int n_memtypes, cur_type;
2228
2229         /* no-huge does not need this at all */
2230         if (internal_config.no_hugetlbfs)
2231                 return 0;
2232
2233         /*
2234          * figuring out amount of memory we're going to have is a long and very
2235          * involved process. the basic element we're operating with is a memory
2236          * type, defined as a combination of NUMA node ID and page size (so that
2237          * e.g. 2 sockets with 2 page sizes yield 4 memory types in total).
2238          *
2239          * deciding amount of memory going towards each memory type is a
2240          * balancing act between maximum segments per type, maximum memory per
2241          * type, and number of detected NUMA nodes. the goal is to make sure
2242          * each memory type gets at least one memseg list.
2243          *
2244          * the total amount of memory is limited by RTE_MAX_MEM_MB value.
2245          *
2246          * the total amount of memory per type is limited by either
2247          * RTE_MAX_MEM_MB_PER_TYPE, or by RTE_MAX_MEM_MB divided by the number
2248          * of detected NUMA nodes. additionally, maximum number of segments per
2249          * type is also limited by RTE_MAX_MEMSEG_PER_TYPE. this is because for
2250          * smaller page sizes, it can take hundreds of thousands of segments to
2251          * reach the above specified per-type memory limits.
2252          *
2253          * additionally, each type may have multiple memseg lists associated
2254          * with it, each limited by either RTE_MAX_MEM_MB_PER_LIST for bigger
2255          * page sizes, or RTE_MAX_MEMSEG_PER_LIST segments for smaller ones.
2256          *
2257          * the number of memseg lists per type is decided based on the above
2258          * limits, and also taking number of detected NUMA nodes, to make sure
2259          * that we don't run out of memseg lists before we populate all NUMA
2260          * nodes with memory.
2261          *
2262          * we do this in three stages. first, we collect the number of types.
2263          * then, we figure out memory constraints and populate the list of
2264          * would-be memseg lists. then, we go ahead and allocate the memseg
2265          * lists.
2266          */
2267
2268         /* create space for mem types */
2269         n_memtypes = internal_config.num_hugepage_sizes * rte_socket_count();
2270         memtypes = calloc(n_memtypes, sizeof(*memtypes));
2271         if (memtypes == NULL) {
2272                 RTE_LOG(ERR, EAL, "Cannot allocate space for memory types\n");
2273                 return -1;
2274         }
2275
2276         /* populate mem types */
2277         cur_type = 0;
2278         for (hpi_idx = 0; hpi_idx < (int) internal_config.num_hugepage_sizes;
2279                         hpi_idx++) {
2280                 struct hugepage_info *hpi;
2281                 uint64_t hugepage_sz;
2282
2283                 hpi = &internal_config.hugepage_info[hpi_idx];
2284                 hugepage_sz = hpi->hugepage_sz;
2285
2286                 for (i = 0; i < (int) rte_socket_count(); i++, cur_type++) {
2287                         int socket_id = rte_socket_id_by_idx(i);
2288
2289 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2290                         /* we can still sort pages by socket in legacy mode */
2291                         if (!internal_config.legacy_mem && socket_id > 0)
2292                                 break;
2293 #endif
2294                         memtypes[cur_type].page_sz = hugepage_sz;
2295                         memtypes[cur_type].socket_id = socket_id;
2296
2297                         RTE_LOG(DEBUG, EAL, "Detected memory type: "
2298                                 "socket_id:%u hugepage_sz:%" PRIu64 "\n",
2299                                 socket_id, hugepage_sz);
2300                 }
2301         }
2302         /* number of memtypes could have been lower due to no NUMA support */
2303         n_memtypes = cur_type;
2304
2305         /* set up limits for types */
2306         max_mem = (uint64_t)RTE_MAX_MEM_MB << 20;
2307         max_mem_per_type = RTE_MIN((uint64_t)RTE_MAX_MEM_MB_PER_TYPE << 20,
2308                         max_mem / n_memtypes);
2309         /*
2310          * limit maximum number of segment lists per type to ensure there's
2311          * space for memseg lists for all NUMA nodes with all page sizes
2312          */
2313         max_seglists_per_type = RTE_MAX_MEMSEG_LISTS / n_memtypes;
2314
2315         if (max_seglists_per_type == 0) {
2316                 RTE_LOG(ERR, EAL, "Cannot accommodate all memory types, please increase %s\n",
2317                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2318                 goto out;
2319         }
2320
2321         /* go through all mem types and create segment lists */
2322         msl_idx = 0;
2323         for (cur_type = 0; cur_type < n_memtypes; cur_type++) {
2324                 unsigned int cur_seglist, n_seglists, n_segs;
2325                 unsigned int max_segs_per_type, max_segs_per_list;
2326                 struct memtype *type = &memtypes[cur_type];
2327                 uint64_t max_mem_per_list, pagesz;
2328                 int socket_id;
2329
2330                 pagesz = type->page_sz;
2331                 socket_id = type->socket_id;
2332
2333                 /*
2334                  * we need to create segment lists for this type. we must take
2335                  * into account the following things:
2336                  *
2337                  * 1. total amount of memory we can use for this memory type
2338                  * 2. total amount of memory per memseg list allowed
2339                  * 3. number of segments needed to fit the amount of memory
2340                  * 4. number of segments allowed per type
2341                  * 5. number of segments allowed per memseg list
2342                  * 6. number of memseg lists we are allowed to take up
2343                  */
2344
2345                 /* calculate how much segments we will need in total */
2346                 max_segs_per_type = max_mem_per_type / pagesz;
2347                 /* limit number of segments to maximum allowed per type */
2348                 max_segs_per_type = RTE_MIN(max_segs_per_type,
2349                                 (unsigned int)RTE_MAX_MEMSEG_PER_TYPE);
2350                 /* limit number of segments to maximum allowed per list */
2351                 max_segs_per_list = RTE_MIN(max_segs_per_type,
2352                                 (unsigned int)RTE_MAX_MEMSEG_PER_LIST);
2353
2354                 /* calculate how much memory we can have per segment list */
2355                 max_mem_per_list = RTE_MIN(max_segs_per_list * pagesz,
2356                                 (uint64_t)RTE_MAX_MEM_MB_PER_LIST << 20);
2357
2358                 /* calculate how many segments each segment list will have */
2359                 n_segs = RTE_MIN(max_segs_per_list, max_mem_per_list / pagesz);
2360
2361                 /* calculate how many segment lists we can have */
2362                 n_seglists = RTE_MIN(max_segs_per_type / n_segs,
2363                                 max_mem_per_type / max_mem_per_list);
2364
2365                 /* limit number of segment lists according to our maximum */
2366                 n_seglists = RTE_MIN(n_seglists, max_seglists_per_type);
2367
2368                 RTE_LOG(DEBUG, EAL, "Creating %i segment lists: "
2369                                 "n_segs:%i socket_id:%i hugepage_sz:%" PRIu64 "\n",
2370                         n_seglists, n_segs, socket_id, pagesz);
2371
2372                 /* create all segment lists */
2373                 for (cur_seglist = 0; cur_seglist < n_seglists; cur_seglist++) {
2374                         if (msl_idx >= RTE_MAX_MEMSEG_LISTS) {
2375                                 RTE_LOG(ERR, EAL,
2376                                         "No more space in memseg lists, please increase %s\n",
2377                                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2378                                 goto out;
2379                         }
2380                         msl = &mcfg->memsegs[msl_idx++];
2381
2382                         if (alloc_memseg_list(msl, pagesz, n_segs,
2383                                         socket_id, cur_seglist))
2384                                 goto out;
2385
2386                         if (alloc_va_space(msl)) {
2387                                 RTE_LOG(ERR, EAL, "Cannot allocate VA space for memseg list\n");
2388                                 goto out;
2389                         }
2390                 }
2391         }
2392         /* we're successful */
2393         ret = 0;
2394 out:
2395         free(memtypes);
2396         return ret;
2397 }
2398
2399 static int
2400 memseg_secondary_init(void)
2401 {
2402         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2403         int msl_idx = 0;
2404         struct rte_memseg_list *msl;
2405
2406         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS; msl_idx++) {
2407
2408                 msl = &mcfg->memsegs[msl_idx];
2409
2410                 /* skip empty memseg lists */
2411                 if (msl->memseg_arr.len == 0)
2412                         continue;
2413
2414                 if (rte_fbarray_attach(&msl->memseg_arr)) {
2415                         RTE_LOG(ERR, EAL, "Cannot attach to primary process memseg lists\n");
2416                         return -1;
2417                 }
2418
2419                 /* preallocate VA space */
2420                 if (alloc_va_space(msl)) {
2421                         RTE_LOG(ERR, EAL, "Cannot preallocate VA space for hugepage memory\n");
2422                         return -1;
2423                 }
2424         }
2425
2426         return 0;
2427 }
2428
2429 int
2430 rte_eal_memseg_init(void)
2431 {
2432         /* increase rlimit to maximum */
2433         struct rlimit lim;
2434
2435         if (getrlimit(RLIMIT_NOFILE, &lim) == 0) {
2436                 /* set limit to maximum */
2437                 lim.rlim_cur = lim.rlim_max;
2438
2439                 if (setrlimit(RLIMIT_NOFILE, &lim) < 0) {
2440                         RTE_LOG(DEBUG, EAL, "Setting maximum number of open files failed: %s\n",
2441                                         strerror(errno));
2442                 } else {
2443                         RTE_LOG(DEBUG, EAL, "Setting maximum number of open files to %"
2444                                         PRIu64 "\n",
2445                                         (uint64_t)lim.rlim_cur);
2446                 }
2447         } else {
2448                 RTE_LOG(ERR, EAL, "Cannot get current resource limits\n");
2449         }
2450 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2451         if (!internal_config.legacy_mem && rte_socket_count() > 1) {
2452                 RTE_LOG(WARNING, EAL, "DPDK is running on a NUMA system, but is compiled without NUMA support.\n");
2453                 RTE_LOG(WARNING, EAL, "This will have adverse consequences for performance and usability.\n");
2454                 RTE_LOG(WARNING, EAL, "Please use --"OPT_LEGACY_MEM" option, or recompile with NUMA support.\n");
2455         }
2456 #endif
2457
2458         return rte_eal_process_type() == RTE_PROC_PRIMARY ?
2459 #ifndef RTE_ARCH_64
2460                         memseg_primary_init_32() :
2461 #else
2462                         memseg_primary_init() :
2463 #endif
2464                         memseg_secondary_init();
2465 }