eal/linux: restore specific hugepage ordering for ppc
[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 /*
73  * Get physical address of any mapped virtual address in the current process.
74  */
75 phys_addr_t
76 rte_mem_virt2phy(const void *virtaddr)
77 {
78         int fd, retval;
79         uint64_t page, physaddr;
80         unsigned long virt_pfn;
81         int page_size;
82         off_t offset;
83
84         if (phys_addrs_available == 0)
85                 return RTE_BAD_IOVA;
86
87         /* standard page size */
88         page_size = getpagesize();
89
90         fd = open("/proc/self/pagemap", O_RDONLY);
91         if (fd < 0) {
92                 RTE_LOG(INFO, EAL, "%s(): cannot open /proc/self/pagemap: %s\n",
93                         __func__, strerror(errno));
94                 return RTE_BAD_IOVA;
95         }
96
97         virt_pfn = (unsigned long)virtaddr / page_size;
98         offset = sizeof(uint64_t) * virt_pfn;
99         if (lseek(fd, offset, SEEK_SET) == (off_t) -1) {
100                 RTE_LOG(INFO, EAL, "%s(): seek error in /proc/self/pagemap: %s\n",
101                                 __func__, strerror(errno));
102                 close(fd);
103                 return RTE_BAD_IOVA;
104         }
105
106         retval = read(fd, &page, PFN_MASK_SIZE);
107         close(fd);
108         if (retval < 0) {
109                 RTE_LOG(INFO, EAL, "%s(): cannot read /proc/self/pagemap: %s\n",
110                                 __func__, strerror(errno));
111                 return RTE_BAD_IOVA;
112         } else if (retval != PFN_MASK_SIZE) {
113                 RTE_LOG(INFO, EAL, "%s(): read %d bytes from /proc/self/pagemap "
114                                 "but expected %d:\n",
115                                 __func__, retval, PFN_MASK_SIZE);
116                 return RTE_BAD_IOVA;
117         }
118
119         /*
120          * the pfn (page frame number) are bits 0-54 (see
121          * pagemap.txt in linux Documentation)
122          */
123         if ((page & 0x7fffffffffffffULL) == 0)
124                 return RTE_BAD_IOVA;
125
126         physaddr = ((page & 0x7fffffffffffffULL) * page_size)
127                 + ((unsigned long)virtaddr % page_size);
128
129         return physaddr;
130 }
131
132 rte_iova_t
133 rte_mem_virt2iova(const void *virtaddr)
134 {
135         if (rte_eal_iova_mode() == RTE_IOVA_VA)
136                 return (uintptr_t)virtaddr;
137         return rte_mem_virt2phy(virtaddr);
138 }
139
140 /*
141  * For each hugepage in hugepg_tbl, fill the physaddr value. We find
142  * it by browsing the /proc/self/pagemap special file.
143  */
144 static int
145 find_physaddrs(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
146 {
147         unsigned int i;
148         phys_addr_t addr;
149
150         for (i = 0; i < hpi->num_pages[0]; i++) {
151                 addr = rte_mem_virt2phy(hugepg_tbl[i].orig_va);
152                 if (addr == RTE_BAD_PHYS_ADDR)
153                         return -1;
154                 hugepg_tbl[i].physaddr = addr;
155         }
156         return 0;
157 }
158
159 /*
160  * For each hugepage in hugepg_tbl, fill the physaddr value sequentially.
161  */
162 static int
163 set_physaddrs(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
164 {
165         unsigned int i;
166         static phys_addr_t addr;
167
168         for (i = 0; i < hpi->num_pages[0]; i++) {
169                 hugepg_tbl[i].physaddr = addr;
170                 addr += hugepg_tbl[i].size;
171         }
172         return 0;
173 }
174
175 /*
176  * Check whether address-space layout randomization is enabled in
177  * the kernel. This is important for multi-process as it can prevent
178  * two processes mapping data to the same virtual address
179  * Returns:
180  *    0 - address space randomization disabled
181  *    1/2 - address space randomization enabled
182  *    negative error code on error
183  */
184 static int
185 aslr_enabled(void)
186 {
187         char c;
188         int retval, fd = open(RANDOMIZE_VA_SPACE_FILE, O_RDONLY);
189         if (fd < 0)
190                 return -errno;
191         retval = read(fd, &c, 1);
192         close(fd);
193         if (retval < 0)
194                 return -errno;
195         if (retval == 0)
196                 return -EIO;
197         switch (c) {
198                 case '0' : return 0;
199                 case '1' : return 1;
200                 case '2' : return 2;
201                 default: return -EINVAL;
202         }
203 }
204
205 static sigjmp_buf huge_jmpenv;
206
207 static void huge_sigbus_handler(int signo __rte_unused)
208 {
209         siglongjmp(huge_jmpenv, 1);
210 }
211
212 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
213  * non-static local variable in the stack frame calling sigsetjmp might be
214  * clobbered by a call to longjmp.
215  */
216 static int huge_wrap_sigsetjmp(void)
217 {
218         return sigsetjmp(huge_jmpenv, 1);
219 }
220
221 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
222 /* Callback for numa library. */
223 void numa_error(char *where)
224 {
225         RTE_LOG(ERR, EAL, "%s failed: %s\n", where, strerror(errno));
226 }
227 #endif
228
229 /*
230  * Mmap all hugepages of hugepage table: it first open a file in
231  * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
232  * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
233  * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
234  * map contiguous physical blocks in contiguous virtual blocks.
235  */
236 static unsigned
237 map_all_hugepages(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi,
238                   uint64_t *essential_memory __rte_unused)
239 {
240         int fd;
241         unsigned i;
242         void *virtaddr;
243 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
244         int node_id = -1;
245         int essential_prev = 0;
246         int oldpolicy;
247         struct bitmask *oldmask = NULL;
248         bool have_numa = true;
249         unsigned long maxnode = 0;
250
251         /* Check if kernel supports NUMA. */
252         if (numa_available() != 0) {
253                 RTE_LOG(DEBUG, EAL, "NUMA is not supported.\n");
254                 have_numa = false;
255         }
256
257         if (have_numa) {
258                 RTE_LOG(DEBUG, EAL, "Trying to obtain current memory policy.\n");
259                 oldmask = numa_allocate_nodemask();
260                 if (get_mempolicy(&oldpolicy, oldmask->maskp,
261                                   oldmask->size + 1, 0, 0) < 0) {
262                         RTE_LOG(ERR, EAL,
263                                 "Failed to get current mempolicy: %s. "
264                                 "Assuming MPOL_DEFAULT.\n", strerror(errno));
265                         oldpolicy = MPOL_DEFAULT;
266                 }
267                 for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
268                         if (internal_config.socket_mem[i])
269                                 maxnode = i + 1;
270         }
271 #endif
272
273         for (i = 0; i < hpi->num_pages[0]; i++) {
274                 struct hugepage_file *hf = &hugepg_tbl[i];
275                 uint64_t hugepage_sz = hpi->hugepage_sz;
276
277 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
278                 if (maxnode) {
279                         unsigned int j;
280
281                         for (j = 0; j < maxnode; j++)
282                                 if (essential_memory[j])
283                                         break;
284
285                         if (j == maxnode) {
286                                 node_id = (node_id + 1) % maxnode;
287                                 while (!internal_config.socket_mem[node_id]) {
288                                         node_id++;
289                                         node_id %= maxnode;
290                                 }
291                                 essential_prev = 0;
292                         } else {
293                                 node_id = j;
294                                 essential_prev = essential_memory[j];
295
296                                 if (essential_memory[j] < hugepage_sz)
297                                         essential_memory[j] = 0;
298                                 else
299                                         essential_memory[j] -= hugepage_sz;
300                         }
301
302                         RTE_LOG(DEBUG, EAL,
303                                 "Setting policy MPOL_PREFERRED for socket %d\n",
304                                 node_id);
305                         numa_set_preferred(node_id);
306                 }
307 #endif
308
309                 hf->file_id = i;
310                 hf->size = hugepage_sz;
311                 eal_get_hugefile_path(hf->filepath, sizeof(hf->filepath),
312                                 hpi->hugedir, hf->file_id);
313                 hf->filepath[sizeof(hf->filepath) - 1] = '\0';
314
315                 /* try to create hugepage file */
316                 fd = open(hf->filepath, O_CREAT | O_RDWR, 0600);
317                 if (fd < 0) {
318                         RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n", __func__,
319                                         strerror(errno));
320                         goto out;
321                 }
322
323                 /* map the segment, and populate page tables,
324                  * the kernel fills this segment with zeros. we don't care where
325                  * this gets mapped - we already have contiguous memory areas
326                  * ready for us to map into.
327                  */
328                 virtaddr = mmap(NULL, hugepage_sz, PROT_READ | PROT_WRITE,
329                                 MAP_SHARED | MAP_POPULATE, fd, 0);
330                 if (virtaddr == MAP_FAILED) {
331                         RTE_LOG(DEBUG, EAL, "%s(): mmap failed: %s\n", __func__,
332                                         strerror(errno));
333                         close(fd);
334                         goto out;
335                 }
336
337                 hf->orig_va = virtaddr;
338
339                 /* In linux, hugetlb limitations, like cgroup, are
340                  * enforced at fault time instead of mmap(), even
341                  * with the option of MAP_POPULATE. Kernel will send
342                  * a SIGBUS signal. To avoid to be killed, save stack
343                  * environment here, if SIGBUS happens, we can jump
344                  * back here.
345                  */
346                 if (huge_wrap_sigsetjmp()) {
347                         RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more "
348                                 "hugepages of size %u MB\n",
349                                 (unsigned int)(hugepage_sz / 0x100000));
350                         munmap(virtaddr, hugepage_sz);
351                         close(fd);
352                         unlink(hugepg_tbl[i].filepath);
353 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
354                         if (maxnode)
355                                 essential_memory[node_id] =
356                                         essential_prev;
357 #endif
358                         goto out;
359                 }
360                 *(int *)virtaddr = 0;
361
362                 /* set shared lock on the file. */
363                 if (flock(fd, LOCK_SH) < 0) {
364                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed:%s \n",
365                                 __func__, strerror(errno));
366                         close(fd);
367                         goto out;
368                 }
369
370                 close(fd);
371         }
372
373 out:
374 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
375         if (maxnode) {
376                 RTE_LOG(DEBUG, EAL,
377                         "Restoring previous memory policy: %d\n", oldpolicy);
378                 if (oldpolicy == MPOL_DEFAULT) {
379                         numa_set_localalloc();
380                 } else if (set_mempolicy(oldpolicy, oldmask->maskp,
381                                          oldmask->size + 1) < 0) {
382                         RTE_LOG(ERR, EAL, "Failed to restore mempolicy: %s\n",
383                                 strerror(errno));
384                         numa_set_localalloc();
385                 }
386         }
387         if (oldmask != NULL)
388                 numa_free_cpumask(oldmask);
389 #endif
390         return i;
391 }
392
393 /*
394  * Parse /proc/self/numa_maps to get the NUMA socket ID for each huge
395  * page.
396  */
397 static int
398 find_numasocket(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
399 {
400         int socket_id;
401         char *end, *nodestr;
402         unsigned i, hp_count = 0;
403         uint64_t virt_addr;
404         char buf[BUFSIZ];
405         char hugedir_str[PATH_MAX];
406         FILE *f;
407
408         f = fopen("/proc/self/numa_maps", "r");
409         if (f == NULL) {
410                 RTE_LOG(NOTICE, EAL, "NUMA support not available"
411                         " consider that all memory is in socket_id 0\n");
412                 return 0;
413         }
414
415         snprintf(hugedir_str, sizeof(hugedir_str),
416                         "%s/%s", hpi->hugedir, eal_get_hugefile_prefix());
417
418         /* parse numa map */
419         while (fgets(buf, sizeof(buf), f) != NULL) {
420
421                 /* ignore non huge page */
422                 if (strstr(buf, " huge ") == NULL &&
423                                 strstr(buf, hugedir_str) == NULL)
424                         continue;
425
426                 /* get zone addr */
427                 virt_addr = strtoull(buf, &end, 16);
428                 if (virt_addr == 0 || end == buf) {
429                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
430                         goto error;
431                 }
432
433                 /* get node id (socket id) */
434                 nodestr = strstr(buf, " N");
435                 if (nodestr == NULL) {
436                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
437                         goto error;
438                 }
439                 nodestr += 2;
440                 end = strstr(nodestr, "=");
441                 if (end == NULL) {
442                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
443                         goto error;
444                 }
445                 end[0] = '\0';
446                 end = NULL;
447
448                 socket_id = strtoul(nodestr, &end, 0);
449                 if ((nodestr[0] == '\0') || (end == NULL) || (*end != '\0')) {
450                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
451                         goto error;
452                 }
453
454                 /* if we find this page in our mappings, set socket_id */
455                 for (i = 0; i < hpi->num_pages[0]; i++) {
456                         void *va = (void *)(unsigned long)virt_addr;
457                         if (hugepg_tbl[i].orig_va == va) {
458                                 hugepg_tbl[i].socket_id = socket_id;
459                                 hp_count++;
460 #ifdef RTE_EAL_NUMA_AWARE_HUGEPAGES
461                                 RTE_LOG(DEBUG, EAL,
462                                         "Hugepage %s is on socket %d\n",
463                                         hugepg_tbl[i].filepath, socket_id);
464 #endif
465                         }
466                 }
467         }
468
469         if (hp_count < hpi->num_pages[0])
470                 goto error;
471
472         fclose(f);
473         return 0;
474
475 error:
476         fclose(f);
477         return -1;
478 }
479
480 static int
481 cmp_physaddr(const void *a, const void *b)
482 {
483 #ifndef RTE_ARCH_PPC_64
484         const struct hugepage_file *p1 = a;
485         const struct hugepage_file *p2 = b;
486 #else
487         /* PowerPC needs memory sorted in reverse order from x86 */
488         const struct hugepage_file *p1 = b;
489         const struct hugepage_file *p2 = a;
490 #endif
491         if (p1->physaddr < p2->physaddr)
492                 return -1;
493         else if (p1->physaddr > p2->physaddr)
494                 return 1;
495         else
496                 return 0;
497 }
498
499 /*
500  * Uses mmap to create a shared memory area for storage of data
501  * Used in this file to store the hugepage file map on disk
502  */
503 static void *
504 create_shared_memory(const char *filename, const size_t mem_size)
505 {
506         void *retval;
507         int fd;
508
509         /* if no shared files mode is used, create anonymous memory instead */
510         if (internal_config.no_shconf) {
511                 retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE,
512                                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
513                 if (retval == MAP_FAILED)
514                         return NULL;
515                 return retval;
516         }
517
518         fd = open(filename, O_CREAT | O_RDWR, 0600);
519         if (fd < 0)
520                 return NULL;
521         if (ftruncate(fd, mem_size) < 0) {
522                 close(fd);
523                 return NULL;
524         }
525         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
526         close(fd);
527         if (retval == MAP_FAILED)
528                 return NULL;
529         return retval;
530 }
531
532 /*
533  * this copies *active* hugepages from one hugepage table to another.
534  * destination is typically the shared memory.
535  */
536 static int
537 copy_hugepages_to_shared_mem(struct hugepage_file * dst, int dest_size,
538                 const struct hugepage_file * src, int src_size)
539 {
540         int src_pos, dst_pos = 0;
541
542         for (src_pos = 0; src_pos < src_size; src_pos++) {
543                 if (src[src_pos].orig_va != NULL) {
544                         /* error on overflow attempt */
545                         if (dst_pos == dest_size)
546                                 return -1;
547                         memcpy(&dst[dst_pos], &src[src_pos], sizeof(struct hugepage_file));
548                         dst_pos++;
549                 }
550         }
551         return 0;
552 }
553
554 static int
555 unlink_hugepage_files(struct hugepage_file *hugepg_tbl,
556                 unsigned num_hp_info)
557 {
558         unsigned socket, size;
559         int page, nrpages = 0;
560
561         /* get total number of hugepages */
562         for (size = 0; size < num_hp_info; size++)
563                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
564                         nrpages +=
565                         internal_config.hugepage_info[size].num_pages[socket];
566
567         for (page = 0; page < nrpages; page++) {
568                 struct hugepage_file *hp = &hugepg_tbl[page];
569
570                 if (hp->orig_va != NULL && unlink(hp->filepath)) {
571                         RTE_LOG(WARNING, EAL, "%s(): Removing %s failed: %s\n",
572                                 __func__, hp->filepath, strerror(errno));
573                 }
574         }
575         return 0;
576 }
577
578 /*
579  * unmaps hugepages that are not going to be used. since we originally allocate
580  * ALL hugepages (not just those we need), additional unmapping needs to be done.
581  */
582 static int
583 unmap_unneeded_hugepages(struct hugepage_file *hugepg_tbl,
584                 struct hugepage_info *hpi,
585                 unsigned num_hp_info)
586 {
587         unsigned socket, size;
588         int page, nrpages = 0;
589
590         /* get total number of hugepages */
591         for (size = 0; size < num_hp_info; size++)
592                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
593                         nrpages += internal_config.hugepage_info[size].num_pages[socket];
594
595         for (size = 0; size < num_hp_info; size++) {
596                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++) {
597                         unsigned pages_found = 0;
598
599                         /* traverse until we have unmapped all the unused pages */
600                         for (page = 0; page < nrpages; page++) {
601                                 struct hugepage_file *hp = &hugepg_tbl[page];
602
603                                 /* find a page that matches the criteria */
604                                 if ((hp->size == hpi[size].hugepage_sz) &&
605                                                 (hp->socket_id == (int) socket)) {
606
607                                         /* if we skipped enough pages, unmap the rest */
608                                         if (pages_found == hpi[size].num_pages[socket]) {
609                                                 uint64_t unmap_len;
610
611                                                 unmap_len = hp->size;
612
613                                                 /* get start addr and len of the remaining segment */
614                                                 munmap(hp->orig_va,
615                                                         (size_t)unmap_len);
616
617                                                 hp->orig_va = NULL;
618                                                 if (unlink(hp->filepath) == -1) {
619                                                         RTE_LOG(ERR, EAL, "%s(): Removing %s failed: %s\n",
620                                                                         __func__, hp->filepath, strerror(errno));
621                                                         return -1;
622                                                 }
623                                         } else {
624                                                 /* lock the page and skip */
625                                                 pages_found++;
626                                         }
627
628                                 } /* match page */
629                         } /* foreach page */
630                 } /* foreach socket */
631         } /* foreach pagesize */
632
633         return 0;
634 }
635
636 static int
637 remap_segment(struct hugepage_file *hugepages, int seg_start, int seg_end)
638 {
639         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
640         struct rte_memseg_list *msl;
641         struct rte_fbarray *arr;
642         int cur_page, seg_len;
643         unsigned int msl_idx;
644         int ms_idx;
645         uint64_t page_sz;
646         size_t memseg_len;
647         int socket_id;
648
649         page_sz = hugepages[seg_start].size;
650         socket_id = hugepages[seg_start].socket_id;
651         seg_len = seg_end - seg_start;
652
653         RTE_LOG(DEBUG, EAL, "Attempting to map %" PRIu64 "M on socket %i\n",
654                         (seg_len * page_sz) >> 20ULL, socket_id);
655
656         /* find free space in memseg lists */
657         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS; msl_idx++) {
658                 bool empty;
659                 msl = &mcfg->memsegs[msl_idx];
660                 arr = &msl->memseg_arr;
661
662                 if (msl->page_sz != page_sz)
663                         continue;
664                 if (msl->socket_id != socket_id)
665                         continue;
666
667                 /* leave space for a hole if array is not empty */
668                 empty = arr->count == 0;
669                 ms_idx = rte_fbarray_find_next_n_free(arr, 0,
670                                 seg_len + (empty ? 0 : 1));
671
672                 /* memseg list is full? */
673                 if (ms_idx < 0)
674                         continue;
675
676                 /* leave some space between memsegs, they are not IOVA
677                  * contiguous, so they shouldn't be VA contiguous either.
678                  */
679                 if (!empty)
680                         ms_idx++;
681                 break;
682         }
683         if (msl_idx == RTE_MAX_MEMSEG_LISTS) {
684                 RTE_LOG(ERR, EAL, "Could not find space for memseg. Please increase %s and/or %s in configuration.\n",
685                                 RTE_STR(CONFIG_RTE_MAX_MEMSEG_PER_TYPE),
686                                 RTE_STR(CONFIG_RTE_MAX_MEM_PER_TYPE));
687                 return -1;
688         }
689
690 #ifdef RTE_ARCH_PPC_64
691         /* for PPC64 we go through the list backwards */
692         for (cur_page = seg_end - 1; cur_page >= seg_start;
693                         cur_page--, ms_idx++) {
694 #else
695         for (cur_page = seg_start; cur_page < seg_end; cur_page++, ms_idx++) {
696 #endif
697                 struct hugepage_file *hfile = &hugepages[cur_page];
698                 struct rte_memseg *ms = rte_fbarray_get(arr, ms_idx);
699                 void *addr;
700                 int fd;
701
702                 fd = open(hfile->filepath, O_RDWR);
703                 if (fd < 0) {
704                         RTE_LOG(ERR, EAL, "Could not open '%s': %s\n",
705                                         hfile->filepath, strerror(errno));
706                         return -1;
707                 }
708                 /* set shared lock on the file. */
709                 if (flock(fd, LOCK_SH) < 0) {
710                         RTE_LOG(DEBUG, EAL, "Could not lock '%s': %s\n",
711                                         hfile->filepath, strerror(errno));
712                         close(fd);
713                         return -1;
714                 }
715                 memseg_len = (size_t)page_sz;
716                 addr = RTE_PTR_ADD(msl->base_va, ms_idx * memseg_len);
717
718                 /* we know this address is already mmapped by memseg list, so
719                  * using MAP_FIXED here is safe
720                  */
721                 addr = mmap(addr, page_sz, PROT_READ | PROT_WRITE,
722                                 MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd, 0);
723                 if (addr == MAP_FAILED) {
724                         RTE_LOG(ERR, EAL, "Couldn't remap '%s': %s\n",
725                                         hfile->filepath, strerror(errno));
726                         close(fd);
727                         return -1;
728                 }
729
730                 /* we have a new address, so unmap previous one */
731 #ifndef RTE_ARCH_64
732                 /* in 32-bit legacy mode, we have already unmapped the page */
733                 if (!internal_config.legacy_mem)
734                         munmap(hfile->orig_va, page_sz);
735 #else
736                 munmap(hfile->orig_va, page_sz);
737 #endif
738
739                 hfile->orig_va = NULL;
740                 hfile->final_va = addr;
741
742                 /* rewrite physical addresses in IOVA as VA mode */
743                 if (rte_eal_iova_mode() == RTE_IOVA_VA)
744                         hfile->physaddr = (uintptr_t)addr;
745
746                 /* set up memseg data */
747                 ms->addr = addr;
748                 ms->hugepage_sz = page_sz;
749                 ms->len = memseg_len;
750                 ms->iova = hfile->physaddr;
751                 ms->socket_id = hfile->socket_id;
752                 ms->nchannel = rte_memory_get_nchannel();
753                 ms->nrank = rte_memory_get_nrank();
754
755                 rte_fbarray_set_used(arr, ms_idx);
756
757                 /* store segment fd internally */
758                 if (eal_memalloc_set_seg_fd(msl_idx, ms_idx, fd) < 0)
759                         RTE_LOG(ERR, EAL, "Could not store segment fd: %s\n",
760                                 rte_strerror(rte_errno));
761         }
762         RTE_LOG(DEBUG, EAL, "Allocated %" PRIu64 "M on socket %i\n",
763                         (seg_len * page_sz) >> 20, socket_id);
764         return 0;
765 }
766
767 static uint64_t
768 get_mem_amount(uint64_t page_sz, uint64_t max_mem)
769 {
770         uint64_t area_sz, max_pages;
771
772         /* limit to RTE_MAX_MEMSEG_PER_LIST pages or RTE_MAX_MEM_MB_PER_LIST */
773         max_pages = RTE_MAX_MEMSEG_PER_LIST;
774         max_mem = RTE_MIN((uint64_t)RTE_MAX_MEM_MB_PER_LIST << 20, max_mem);
775
776         area_sz = RTE_MIN(page_sz * max_pages, max_mem);
777
778         /* make sure the list isn't smaller than the page size */
779         area_sz = RTE_MAX(area_sz, page_sz);
780
781         return RTE_ALIGN(area_sz, page_sz);
782 }
783
784 static int
785 free_memseg_list(struct rte_memseg_list *msl)
786 {
787         if (rte_fbarray_destroy(&msl->memseg_arr)) {
788                 RTE_LOG(ERR, EAL, "Cannot destroy memseg list\n");
789                 return -1;
790         }
791         memset(msl, 0, sizeof(*msl));
792         return 0;
793 }
794
795 #define MEMSEG_LIST_FMT "memseg-%" PRIu64 "k-%i-%i"
796 static int
797 alloc_memseg_list(struct rte_memseg_list *msl, uint64_t page_sz,
798                 int n_segs, int socket_id, int type_msl_idx)
799 {
800         char name[RTE_FBARRAY_NAME_LEN];
801
802         snprintf(name, sizeof(name), MEMSEG_LIST_FMT, page_sz >> 10, socket_id,
803                  type_msl_idx);
804         if (rte_fbarray_init(&msl->memseg_arr, name, n_segs,
805                         sizeof(struct rte_memseg))) {
806                 RTE_LOG(ERR, EAL, "Cannot allocate memseg list: %s\n",
807                         rte_strerror(rte_errno));
808                 return -1;
809         }
810
811         msl->page_sz = page_sz;
812         msl->socket_id = socket_id;
813         msl->base_va = NULL;
814
815         RTE_LOG(DEBUG, EAL, "Memseg list allocated: 0x%zxkB at socket %i\n",
816                         (size_t)page_sz >> 10, socket_id);
817
818         return 0;
819 }
820
821 static int
822 alloc_va_space(struct rte_memseg_list *msl)
823 {
824         uint64_t page_sz;
825         size_t mem_sz;
826         void *addr;
827         int flags = 0;
828
829         page_sz = msl->page_sz;
830         mem_sz = page_sz * msl->memseg_arr.len;
831
832         addr = eal_get_virtual_area(msl->base_va, &mem_sz, page_sz, 0, flags);
833         if (addr == NULL) {
834                 if (rte_errno == EADDRNOTAVAIL)
835                         RTE_LOG(ERR, EAL, "Could not mmap %llu bytes at [%p] - please use '--base-virtaddr' option\n",
836                                 (unsigned long long)mem_sz, msl->base_va);
837                 else
838                         RTE_LOG(ERR, EAL, "Cannot reserve memory\n");
839                 return -1;
840         }
841         msl->base_va = addr;
842         msl->len = mem_sz;
843
844         return 0;
845 }
846
847 /*
848  * Our VA space is not preallocated yet, so preallocate it here. We need to know
849  * how many segments there are in order to map all pages into one address space,
850  * and leave appropriate holes between segments so that rte_malloc does not
851  * concatenate them into one big segment.
852  *
853  * we also need to unmap original pages to free up address space.
854  */
855 static int __rte_unused
856 prealloc_segments(struct hugepage_file *hugepages, int n_pages)
857 {
858         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
859         int cur_page, seg_start_page, end_seg, new_memseg;
860         unsigned int hpi_idx, socket, i;
861         int n_contig_segs, n_segs;
862         int msl_idx;
863
864         /* before we preallocate segments, we need to free up our VA space.
865          * we're not removing files, and we already have information about
866          * PA-contiguousness, so it is safe to unmap everything.
867          */
868         for (cur_page = 0; cur_page < n_pages; cur_page++) {
869                 struct hugepage_file *hpi = &hugepages[cur_page];
870                 munmap(hpi->orig_va, hpi->size);
871                 hpi->orig_va = NULL;
872         }
873
874         /* we cannot know how many page sizes and sockets we have discovered, so
875          * loop over all of them
876          */
877         for (hpi_idx = 0; hpi_idx < internal_config.num_hugepage_sizes;
878                         hpi_idx++) {
879                 uint64_t page_sz =
880                         internal_config.hugepage_info[hpi_idx].hugepage_sz;
881
882                 for (i = 0; i < rte_socket_count(); i++) {
883                         struct rte_memseg_list *msl;
884
885                         socket = rte_socket_id_by_idx(i);
886                         n_contig_segs = 0;
887                         n_segs = 0;
888                         seg_start_page = -1;
889
890                         for (cur_page = 0; cur_page < n_pages; cur_page++) {
891                                 struct hugepage_file *prev, *cur;
892                                 int prev_seg_start_page = -1;
893
894                                 cur = &hugepages[cur_page];
895                                 prev = cur_page == 0 ? NULL :
896                                                 &hugepages[cur_page - 1];
897
898                                 new_memseg = 0;
899                                 end_seg = 0;
900
901                                 if (cur->size == 0)
902                                         end_seg = 1;
903                                 else if (cur->socket_id != (int) socket)
904                                         end_seg = 1;
905                                 else if (cur->size != page_sz)
906                                         end_seg = 1;
907                                 else if (cur_page == 0)
908                                         new_memseg = 1;
909 #ifdef RTE_ARCH_PPC_64
910                                 /* On PPC64 architecture, the mmap always start
911                                  * from higher address to lower address. Here,
912                                  * physical addresses are in descending order.
913                                  */
914                                 else if ((prev->physaddr - cur->physaddr) !=
915                                                 cur->size)
916                                         new_memseg = 1;
917 #else
918                                 else if ((cur->physaddr - prev->physaddr) !=
919                                                 cur->size)
920                                         new_memseg = 1;
921 #endif
922                                 if (new_memseg) {
923                                         /* if we're already inside a segment,
924                                          * new segment means end of current one
925                                          */
926                                         if (seg_start_page != -1) {
927                                                 end_seg = 1;
928                                                 prev_seg_start_page =
929                                                                 seg_start_page;
930                                         }
931                                         seg_start_page = cur_page;
932                                 }
933
934                                 if (end_seg) {
935                                         if (prev_seg_start_page != -1) {
936                                                 /* we've found a new segment */
937                                                 n_contig_segs++;
938                                                 n_segs += cur_page -
939                                                         prev_seg_start_page;
940                                         } else if (seg_start_page != -1) {
941                                                 /* we didn't find new segment,
942                                                  * but did end current one
943                                                  */
944                                                 n_contig_segs++;
945                                                 n_segs += cur_page -
946                                                                 seg_start_page;
947                                                 seg_start_page = -1;
948                                                 continue;
949                                         } else {
950                                                 /* we're skipping this page */
951                                                 continue;
952                                         }
953                                 }
954                                 /* segment continues */
955                         }
956                         /* check if we missed last segment */
957                         if (seg_start_page != -1) {
958                                 n_contig_segs++;
959                                 n_segs += cur_page - seg_start_page;
960                         }
961
962                         /* if no segments were found, do not preallocate */
963                         if (n_segs == 0)
964                                 continue;
965
966                         /* we now have total number of pages that we will
967                          * allocate for this segment list. add separator pages
968                          * to the total count, and preallocate VA space.
969                          */
970                         n_segs += n_contig_segs - 1;
971
972                         /* now, preallocate VA space for these segments */
973
974                         /* first, find suitable memseg list for this */
975                         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS;
976                                         msl_idx++) {
977                                 msl = &mcfg->memsegs[msl_idx];
978
979                                 if (msl->base_va != NULL)
980                                         continue;
981                                 break;
982                         }
983                         if (msl_idx == RTE_MAX_MEMSEG_LISTS) {
984                                 RTE_LOG(ERR, EAL, "Not enough space in memseg lists, please increase %s\n",
985                                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
986                                 return -1;
987                         }
988
989                         /* now, allocate fbarray itself */
990                         if (alloc_memseg_list(msl, page_sz, n_segs, socket,
991                                                 msl_idx) < 0)
992                                 return -1;
993
994                         /* finally, allocate VA space */
995                         if (alloc_va_space(msl) < 0)
996                                 return -1;
997                 }
998         }
999         return 0;
1000 }
1001
1002 /*
1003  * We cannot reallocate memseg lists on the fly because PPC64 stores pages
1004  * backwards, therefore we have to process the entire memseg first before
1005  * remapping it into memseg list VA space.
1006  */
1007 static int
1008 remap_needed_hugepages(struct hugepage_file *hugepages, int n_pages)
1009 {
1010         int cur_page, seg_start_page, new_memseg, ret;
1011
1012         seg_start_page = 0;
1013         for (cur_page = 0; cur_page < n_pages; cur_page++) {
1014                 struct hugepage_file *prev, *cur;
1015
1016                 new_memseg = 0;
1017
1018                 cur = &hugepages[cur_page];
1019                 prev = cur_page == 0 ? NULL : &hugepages[cur_page - 1];
1020
1021                 /* if size is zero, no more pages left */
1022                 if (cur->size == 0)
1023                         break;
1024
1025                 if (cur_page == 0)
1026                         new_memseg = 1;
1027                 else if (cur->socket_id != prev->socket_id)
1028                         new_memseg = 1;
1029                 else if (cur->size != prev->size)
1030                         new_memseg = 1;
1031 #ifdef RTE_ARCH_PPC_64
1032                 /* On PPC64 architecture, the mmap always start from higher
1033                  * address to lower address. Here, physical addresses are in
1034                  * descending order.
1035                  */
1036                 else if ((prev->physaddr - cur->physaddr) != cur->size)
1037                         new_memseg = 1;
1038 #else
1039                 else if ((cur->physaddr - prev->physaddr) != cur->size)
1040                         new_memseg = 1;
1041 #endif
1042
1043                 if (new_memseg) {
1044                         /* if this isn't the first time, remap segment */
1045                         if (cur_page != 0) {
1046                                 ret = remap_segment(hugepages, seg_start_page,
1047                                                 cur_page);
1048                                 if (ret != 0)
1049                                         return -1;
1050                         }
1051                         /* remember where we started */
1052                         seg_start_page = cur_page;
1053                 }
1054                 /* continuation of previous memseg */
1055         }
1056         /* we were stopped, but we didn't remap the last segment, do it now */
1057         if (cur_page != 0) {
1058                 ret = remap_segment(hugepages, seg_start_page,
1059                                 cur_page);
1060                 if (ret != 0)
1061                         return -1;
1062         }
1063         return 0;
1064 }
1065
1066 __rte_unused /* function is unused on 32-bit builds */
1067 static inline uint64_t
1068 get_socket_mem_size(int socket)
1069 {
1070         uint64_t size = 0;
1071         unsigned i;
1072
1073         for (i = 0; i < internal_config.num_hugepage_sizes; i++){
1074                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1075                 size += hpi->hugepage_sz * hpi->num_pages[socket];
1076         }
1077
1078         return size;
1079 }
1080
1081 /*
1082  * This function is a NUMA-aware equivalent of calc_num_pages.
1083  * It takes in the list of hugepage sizes and the
1084  * number of pages thereof, and calculates the best number of
1085  * pages of each size to fulfill the request for <memory> ram
1086  */
1087 static int
1088 calc_num_pages_per_socket(uint64_t * memory,
1089                 struct hugepage_info *hp_info,
1090                 struct hugepage_info *hp_used,
1091                 unsigned num_hp_info)
1092 {
1093         unsigned socket, j, i = 0;
1094         unsigned requested, available;
1095         int total_num_pages = 0;
1096         uint64_t remaining_mem, cur_mem;
1097         uint64_t total_mem = internal_config.memory;
1098
1099         if (num_hp_info == 0)
1100                 return -1;
1101
1102         /* if specific memory amounts per socket weren't requested */
1103         if (internal_config.force_sockets == 0) {
1104                 size_t total_size;
1105 #ifdef RTE_ARCH_64
1106                 int cpu_per_socket[RTE_MAX_NUMA_NODES];
1107                 size_t default_size;
1108                 unsigned lcore_id;
1109
1110                 /* Compute number of cores per socket */
1111                 memset(cpu_per_socket, 0, sizeof(cpu_per_socket));
1112                 RTE_LCORE_FOREACH(lcore_id) {
1113                         cpu_per_socket[rte_lcore_to_socket_id(lcore_id)]++;
1114                 }
1115
1116                 /*
1117                  * Automatically spread requested memory amongst detected sockets according
1118                  * to number of cores from cpu mask present on each socket
1119                  */
1120                 total_size = internal_config.memory;
1121                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1122
1123                         /* Set memory amount per socket */
1124                         default_size = (internal_config.memory * cpu_per_socket[socket])
1125                                         / rte_lcore_count();
1126
1127                         /* Limit to maximum available memory on socket */
1128                         default_size = RTE_MIN(default_size, get_socket_mem_size(socket));
1129
1130                         /* Update sizes */
1131                         memory[socket] = default_size;
1132                         total_size -= default_size;
1133                 }
1134
1135                 /*
1136                  * If some memory is remaining, try to allocate it by getting all
1137                  * available memory from sockets, one after the other
1138                  */
1139                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
1140                         /* take whatever is available */
1141                         default_size = RTE_MIN(get_socket_mem_size(socket) - memory[socket],
1142                                                total_size);
1143
1144                         /* Update sizes */
1145                         memory[socket] += default_size;
1146                         total_size -= default_size;
1147                 }
1148 #else
1149                 /* in 32-bit mode, allocate all of the memory only on master
1150                  * lcore socket
1151                  */
1152                 total_size = internal_config.memory;
1153                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0;
1154                                 socket++) {
1155                         struct rte_config *cfg = rte_eal_get_configuration();
1156                         unsigned int master_lcore_socket;
1157
1158                         master_lcore_socket =
1159                                 rte_lcore_to_socket_id(cfg->master_lcore);
1160
1161                         if (master_lcore_socket != socket)
1162                                 continue;
1163
1164                         /* Update sizes */
1165                         memory[socket] = total_size;
1166                         break;
1167                 }
1168 #endif
1169         }
1170
1171         for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_mem != 0; socket++) {
1172                 /* skips if the memory on specific socket wasn't requested */
1173                 for (i = 0; i < num_hp_info && memory[socket] != 0; i++){
1174                         strlcpy(hp_used[i].hugedir, hp_info[i].hugedir,
1175                                 sizeof(hp_used[i].hugedir));
1176                         hp_used[i].num_pages[socket] = RTE_MIN(
1177                                         memory[socket] / hp_info[i].hugepage_sz,
1178                                         hp_info[i].num_pages[socket]);
1179
1180                         cur_mem = hp_used[i].num_pages[socket] *
1181                                         hp_used[i].hugepage_sz;
1182
1183                         memory[socket] -= cur_mem;
1184                         total_mem -= cur_mem;
1185
1186                         total_num_pages += hp_used[i].num_pages[socket];
1187
1188                         /* check if we have met all memory requests */
1189                         if (memory[socket] == 0)
1190                                 break;
1191
1192                         /* check if we have any more pages left at this size, if so
1193                          * move on to next size */
1194                         if (hp_used[i].num_pages[socket] == hp_info[i].num_pages[socket])
1195                                 continue;
1196                         /* At this point we know that there are more pages available that are
1197                          * bigger than the memory we want, so lets see if we can get enough
1198                          * from other page sizes.
1199                          */
1200                         remaining_mem = 0;
1201                         for (j = i+1; j < num_hp_info; j++)
1202                                 remaining_mem += hp_info[j].hugepage_sz *
1203                                 hp_info[j].num_pages[socket];
1204
1205                         /* is there enough other memory, if not allocate another page and quit */
1206                         if (remaining_mem < memory[socket]){
1207                                 cur_mem = RTE_MIN(memory[socket],
1208                                                 hp_info[i].hugepage_sz);
1209                                 memory[socket] -= cur_mem;
1210                                 total_mem -= cur_mem;
1211                                 hp_used[i].num_pages[socket]++;
1212                                 total_num_pages++;
1213                                 break; /* we are done with this socket*/
1214                         }
1215                 }
1216                 /* if we didn't satisfy all memory requirements per socket */
1217                 if (memory[socket] > 0 &&
1218                                 internal_config.socket_mem[socket] != 0) {
1219                         /* to prevent icc errors */
1220                         requested = (unsigned) (internal_config.socket_mem[socket] /
1221                                         0x100000);
1222                         available = requested -
1223                                         ((unsigned) (memory[socket] / 0x100000));
1224                         RTE_LOG(ERR, EAL, "Not enough memory available on socket %u! "
1225                                         "Requested: %uMB, available: %uMB\n", socket,
1226                                         requested, available);
1227                         return -1;
1228                 }
1229         }
1230
1231         /* if we didn't satisfy total memory requirements */
1232         if (total_mem > 0) {
1233                 requested = (unsigned) (internal_config.memory / 0x100000);
1234                 available = requested - (unsigned) (total_mem / 0x100000);
1235                 RTE_LOG(ERR, EAL, "Not enough memory available! Requested: %uMB,"
1236                                 " available: %uMB\n", requested, available);
1237                 return -1;
1238         }
1239         return total_num_pages;
1240 }
1241
1242 static inline size_t
1243 eal_get_hugepage_mem_size(void)
1244 {
1245         uint64_t size = 0;
1246         unsigned i, j;
1247
1248         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
1249                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
1250                 if (strnlen(hpi->hugedir, sizeof(hpi->hugedir)) != 0) {
1251                         for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1252                                 size += hpi->hugepage_sz * hpi->num_pages[j];
1253                         }
1254                 }
1255         }
1256
1257         return (size < SIZE_MAX) ? (size_t)(size) : SIZE_MAX;
1258 }
1259
1260 static struct sigaction huge_action_old;
1261 static int huge_need_recover;
1262
1263 static void
1264 huge_register_sigbus(void)
1265 {
1266         sigset_t mask;
1267         struct sigaction action;
1268
1269         sigemptyset(&mask);
1270         sigaddset(&mask, SIGBUS);
1271         action.sa_flags = 0;
1272         action.sa_mask = mask;
1273         action.sa_handler = huge_sigbus_handler;
1274
1275         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
1276 }
1277
1278 static void
1279 huge_recover_sigbus(void)
1280 {
1281         if (huge_need_recover) {
1282                 sigaction(SIGBUS, &huge_action_old, NULL);
1283                 huge_need_recover = 0;
1284         }
1285 }
1286
1287 /*
1288  * Prepare physical memory mapping: fill configuration structure with
1289  * these infos, return 0 on success.
1290  *  1. map N huge pages in separate files in hugetlbfs
1291  *  2. find associated physical addr
1292  *  3. find associated NUMA socket ID
1293  *  4. sort all huge pages by physical address
1294  *  5. remap these N huge pages in the correct order
1295  *  6. unmap the first mapping
1296  *  7. fill memsegs in configuration with contiguous zones
1297  */
1298 static int
1299 eal_legacy_hugepage_init(void)
1300 {
1301         struct rte_mem_config *mcfg;
1302         struct hugepage_file *hugepage = NULL, *tmp_hp = NULL;
1303         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1304         struct rte_fbarray *arr;
1305         struct rte_memseg *ms;
1306
1307         uint64_t memory[RTE_MAX_NUMA_NODES];
1308
1309         unsigned hp_offset;
1310         int i, j;
1311         int nr_hugefiles, nr_hugepages = 0;
1312         void *addr;
1313
1314         memset(used_hp, 0, sizeof(used_hp));
1315
1316         /* get pointer to global configuration */
1317         mcfg = rte_eal_get_configuration()->mem_config;
1318
1319         /* hugetlbfs can be disabled */
1320         if (internal_config.no_hugetlbfs) {
1321                 struct rte_memseg_list *msl;
1322                 int n_segs, cur_seg, fd, flags;
1323 #ifdef MEMFD_SUPPORTED
1324                 int memfd;
1325 #endif
1326                 uint64_t page_sz;
1327
1328                 /* nohuge mode is legacy mode */
1329                 internal_config.legacy_mem = 1;
1330
1331                 /* nohuge mode is single-file segments mode */
1332                 internal_config.single_file_segments = 1;
1333
1334                 /* create a memseg list */
1335                 msl = &mcfg->memsegs[0];
1336
1337                 page_sz = RTE_PGSIZE_4K;
1338                 n_segs = internal_config.memory / page_sz;
1339
1340                 if (rte_fbarray_init(&msl->memseg_arr, "nohugemem", n_segs,
1341                                         sizeof(struct rte_memseg))) {
1342                         RTE_LOG(ERR, EAL, "Cannot allocate memseg list\n");
1343                         return -1;
1344                 }
1345
1346                 /* set up parameters for anonymous mmap */
1347                 fd = -1;
1348                 flags = MAP_PRIVATE | MAP_ANONYMOUS;
1349
1350 #ifdef MEMFD_SUPPORTED
1351                 /* create a memfd and store it in the segment fd table */
1352                 memfd = memfd_create("nohuge", 0);
1353                 if (memfd < 0) {
1354                         RTE_LOG(DEBUG, EAL, "Cannot create memfd: %s\n",
1355                                         strerror(errno));
1356                         RTE_LOG(DEBUG, EAL, "Falling back to anonymous map\n");
1357                 } else {
1358                         /* we got an fd - now resize it */
1359                         if (ftruncate(memfd, internal_config.memory) < 0) {
1360                                 RTE_LOG(ERR, EAL, "Cannot resize memfd: %s\n",
1361                                                 strerror(errno));
1362                                 RTE_LOG(ERR, EAL, "Falling back to anonymous map\n");
1363                                 close(memfd);
1364                         } else {
1365                                 /* creating memfd-backed file was successful.
1366                                  * we want changes to memfd to be visible to
1367                                  * other processes (such as vhost backend), so
1368                                  * map it as shared memory.
1369                                  */
1370                                 RTE_LOG(DEBUG, EAL, "Using memfd for anonymous memory\n");
1371                                 fd = memfd;
1372                                 flags = MAP_SHARED;
1373                         }
1374                 }
1375 #endif
1376                 addr = mmap(NULL, internal_config.memory, PROT_READ | PROT_WRITE,
1377                                 flags, fd, 0);
1378                 if (addr == MAP_FAILED) {
1379                         RTE_LOG(ERR, EAL, "%s: mmap() failed: %s\n", __func__,
1380                                         strerror(errno));
1381                         return -1;
1382                 }
1383                 msl->base_va = addr;
1384                 msl->page_sz = page_sz;
1385                 msl->socket_id = 0;
1386                 msl->len = internal_config.memory;
1387
1388                 /* we're in single-file segments mode, so only the segment list
1389                  * fd needs to be set up.
1390                  */
1391                 if (fd != -1) {
1392                         if (eal_memalloc_set_seg_list_fd(0, fd) < 0) {
1393                                 RTE_LOG(ERR, EAL, "Cannot set up segment list fd\n");
1394                                 /* not a serious error, proceed */
1395                         }
1396                 }
1397
1398                 /* populate memsegs. each memseg is one page long */
1399                 for (cur_seg = 0; cur_seg < n_segs; cur_seg++) {
1400                         arr = &msl->memseg_arr;
1401
1402                         ms = rte_fbarray_get(arr, cur_seg);
1403                         if (rte_eal_iova_mode() == RTE_IOVA_VA)
1404                                 ms->iova = (uintptr_t)addr;
1405                         else
1406                                 ms->iova = RTE_BAD_IOVA;
1407                         ms->addr = addr;
1408                         ms->hugepage_sz = page_sz;
1409                         ms->socket_id = 0;
1410                         ms->len = page_sz;
1411
1412                         rte_fbarray_set_used(arr, cur_seg);
1413
1414                         addr = RTE_PTR_ADD(addr, (size_t)page_sz);
1415                 }
1416                 if (mcfg->dma_maskbits &&
1417                     rte_mem_check_dma_mask_thread_unsafe(mcfg->dma_maskbits)) {
1418                         RTE_LOG(ERR, EAL,
1419                                 "%s(): couldn't allocate memory due to IOVA exceeding limits of current DMA mask.\n",
1420                                 __func__);
1421                         if (rte_eal_iova_mode() == RTE_IOVA_VA &&
1422                             rte_eal_using_phys_addrs())
1423                                 RTE_LOG(ERR, EAL,
1424                                         "%s(): Please try initializing EAL with --iova-mode=pa parameter.\n",
1425                                         __func__);
1426                         goto fail;
1427                 }
1428                 return 0;
1429         }
1430
1431         /* calculate total number of hugepages available. at this point we haven't
1432          * yet started sorting them so they all are on socket 0 */
1433         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1434                 /* meanwhile, also initialize used_hp hugepage sizes in used_hp */
1435                 used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;
1436
1437                 nr_hugepages += internal_config.hugepage_info[i].num_pages[0];
1438         }
1439
1440         /*
1441          * allocate a memory area for hugepage table.
1442          * this isn't shared memory yet. due to the fact that we need some
1443          * processing done on these pages, shared memory will be created
1444          * at a later stage.
1445          */
1446         tmp_hp = malloc(nr_hugepages * sizeof(struct hugepage_file));
1447         if (tmp_hp == NULL)
1448                 goto fail;
1449
1450         memset(tmp_hp, 0, nr_hugepages * sizeof(struct hugepage_file));
1451
1452         hp_offset = 0; /* where we start the current page size entries */
1453
1454         huge_register_sigbus();
1455
1456         /* make a copy of socket_mem, needed for balanced allocation. */
1457         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1458                 memory[i] = internal_config.socket_mem[i];
1459
1460         /* map all hugepages and sort them */
1461         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
1462                 unsigned pages_old, pages_new;
1463                 struct hugepage_info *hpi;
1464
1465                 /*
1466                  * we don't yet mark hugepages as used at this stage, so
1467                  * we just map all hugepages available to the system
1468                  * all hugepages are still located on socket 0
1469                  */
1470                 hpi = &internal_config.hugepage_info[i];
1471
1472                 if (hpi->num_pages[0] == 0)
1473                         continue;
1474
1475                 /* map all hugepages available */
1476                 pages_old = hpi->num_pages[0];
1477                 pages_new = map_all_hugepages(&tmp_hp[hp_offset], hpi, memory);
1478                 if (pages_new < pages_old) {
1479                         RTE_LOG(DEBUG, EAL,
1480                                 "%d not %d hugepages of size %u MB allocated\n",
1481                                 pages_new, pages_old,
1482                                 (unsigned)(hpi->hugepage_sz / 0x100000));
1483
1484                         int pages = pages_old - pages_new;
1485
1486                         nr_hugepages -= pages;
1487                         hpi->num_pages[0] = pages_new;
1488                         if (pages_new == 0)
1489                                 continue;
1490                 }
1491
1492                 if (rte_eal_using_phys_addrs() &&
1493                                 rte_eal_iova_mode() != RTE_IOVA_VA) {
1494                         /* find physical addresses for each hugepage */
1495                         if (find_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1496                                 RTE_LOG(DEBUG, EAL, "Failed to find phys addr "
1497                                         "for %u MB pages\n",
1498                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1499                                 goto fail;
1500                         }
1501                 } else {
1502                         /* set physical addresses for each hugepage */
1503                         if (set_physaddrs(&tmp_hp[hp_offset], hpi) < 0) {
1504                                 RTE_LOG(DEBUG, EAL, "Failed to set phys addr "
1505                                         "for %u MB pages\n",
1506                                         (unsigned int)(hpi->hugepage_sz / 0x100000));
1507                                 goto fail;
1508                         }
1509                 }
1510
1511                 if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
1512                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
1513                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1514                         goto fail;
1515                 }
1516
1517                 qsort(&tmp_hp[hp_offset], hpi->num_pages[0],
1518                       sizeof(struct hugepage_file), cmp_physaddr);
1519
1520                 /* we have processed a num of hugepages of this size, so inc offset */
1521                 hp_offset += hpi->num_pages[0];
1522         }
1523
1524         huge_recover_sigbus();
1525
1526         if (internal_config.memory == 0 && internal_config.force_sockets == 0)
1527                 internal_config.memory = eal_get_hugepage_mem_size();
1528
1529         nr_hugefiles = nr_hugepages;
1530
1531
1532         /* clean out the numbers of pages */
1533         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
1534                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
1535                         internal_config.hugepage_info[i].num_pages[j] = 0;
1536
1537         /* get hugepages for each socket */
1538         for (i = 0; i < nr_hugefiles; i++) {
1539                 int socket = tmp_hp[i].socket_id;
1540
1541                 /* find a hugepage info with right size and increment num_pages */
1542                 const int nb_hpsizes = RTE_MIN(MAX_HUGEPAGE_SIZES,
1543                                 (int)internal_config.num_hugepage_sizes);
1544                 for (j = 0; j < nb_hpsizes; j++) {
1545                         if (tmp_hp[i].size ==
1546                                         internal_config.hugepage_info[j].hugepage_sz) {
1547                                 internal_config.hugepage_info[j].num_pages[socket]++;
1548                         }
1549                 }
1550         }
1551
1552         /* make a copy of socket_mem, needed for number of pages calculation */
1553         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1554                 memory[i] = internal_config.socket_mem[i];
1555
1556         /* calculate final number of pages */
1557         nr_hugepages = calc_num_pages_per_socket(memory,
1558                         internal_config.hugepage_info, used_hp,
1559                         internal_config.num_hugepage_sizes);
1560
1561         /* error if not enough memory available */
1562         if (nr_hugepages < 0)
1563                 goto fail;
1564
1565         /* reporting in! */
1566         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1567                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1568                         if (used_hp[i].num_pages[j] > 0) {
1569                                 RTE_LOG(DEBUG, EAL,
1570                                         "Requesting %u pages of size %uMB"
1571                                         " from socket %i\n",
1572                                         used_hp[i].num_pages[j],
1573                                         (unsigned)
1574                                         (used_hp[i].hugepage_sz / 0x100000),
1575                                         j);
1576                         }
1577                 }
1578         }
1579
1580         /* create shared memory */
1581         hugepage = create_shared_memory(eal_hugepage_data_path(),
1582                         nr_hugefiles * sizeof(struct hugepage_file));
1583
1584         if (hugepage == NULL) {
1585                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
1586                 goto fail;
1587         }
1588         memset(hugepage, 0, nr_hugefiles * sizeof(struct hugepage_file));
1589
1590         /*
1591          * unmap pages that we won't need (looks at used_hp).
1592          * also, sets final_va to NULL on pages that were unmapped.
1593          */
1594         if (unmap_unneeded_hugepages(tmp_hp, used_hp,
1595                         internal_config.num_hugepage_sizes) < 0) {
1596                 RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
1597                 goto fail;
1598         }
1599
1600         /*
1601          * copy stuff from malloc'd hugepage* to the actual shared memory.
1602          * this procedure only copies those hugepages that have orig_va
1603          * not NULL. has overflow protection.
1604          */
1605         if (copy_hugepages_to_shared_mem(hugepage, nr_hugefiles,
1606                         tmp_hp, nr_hugefiles) < 0) {
1607                 RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
1608                 goto fail;
1609         }
1610
1611 #ifndef RTE_ARCH_64
1612         /* for legacy 32-bit mode, we did not preallocate VA space, so do it */
1613         if (internal_config.legacy_mem &&
1614                         prealloc_segments(hugepage, nr_hugefiles)) {
1615                 RTE_LOG(ERR, EAL, "Could not preallocate VA space for hugepages\n");
1616                 goto fail;
1617         }
1618 #endif
1619
1620         /* remap all pages we do need into memseg list VA space, so that those
1621          * pages become first-class citizens in DPDK memory subsystem
1622          */
1623         if (remap_needed_hugepages(hugepage, nr_hugefiles)) {
1624                 RTE_LOG(ERR, EAL, "Couldn't remap hugepage files into memseg lists\n");
1625                 goto fail;
1626         }
1627
1628         /* free the hugepage backing files */
1629         if (internal_config.hugepage_unlink &&
1630                 unlink_hugepage_files(tmp_hp, internal_config.num_hugepage_sizes) < 0) {
1631                 RTE_LOG(ERR, EAL, "Unlinking hugepage files failed!\n");
1632                 goto fail;
1633         }
1634
1635         /* free the temporary hugepage table */
1636         free(tmp_hp);
1637         tmp_hp = NULL;
1638
1639         munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1640         hugepage = NULL;
1641
1642         /* we're not going to allocate more pages, so release VA space for
1643          * unused memseg lists
1644          */
1645         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
1646                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
1647                 size_t mem_sz;
1648
1649                 /* skip inactive lists */
1650                 if (msl->base_va == NULL)
1651                         continue;
1652                 /* skip lists where there is at least one page allocated */
1653                 if (msl->memseg_arr.count > 0)
1654                         continue;
1655                 /* this is an unused list, deallocate it */
1656                 mem_sz = msl->len;
1657                 munmap(msl->base_va, mem_sz);
1658                 msl->base_va = NULL;
1659
1660                 /* destroy backing fbarray */
1661                 rte_fbarray_destroy(&msl->memseg_arr);
1662         }
1663
1664         if (mcfg->dma_maskbits &&
1665             rte_mem_check_dma_mask_thread_unsafe(mcfg->dma_maskbits)) {
1666                 RTE_LOG(ERR, EAL,
1667                         "%s(): couldn't allocate memory due to IOVA exceeding limits of current DMA mask.\n",
1668                         __func__);
1669                 goto fail;
1670         }
1671
1672         return 0;
1673
1674 fail:
1675         huge_recover_sigbus();
1676         free(tmp_hp);
1677         if (hugepage != NULL)
1678                 munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1679
1680         return -1;
1681 }
1682
1683 static int __rte_unused
1684 hugepage_count_walk(const struct rte_memseg_list *msl, void *arg)
1685 {
1686         struct hugepage_info *hpi = arg;
1687
1688         if (msl->page_sz != hpi->hugepage_sz)
1689                 return 0;
1690
1691         hpi->num_pages[msl->socket_id] += msl->memseg_arr.len;
1692         return 0;
1693 }
1694
1695 static int
1696 limits_callback(int socket_id, size_t cur_limit, size_t new_len)
1697 {
1698         RTE_SET_USED(socket_id);
1699         RTE_SET_USED(cur_limit);
1700         RTE_SET_USED(new_len);
1701         return -1;
1702 }
1703
1704 static int
1705 eal_hugepage_init(void)
1706 {
1707         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
1708         uint64_t memory[RTE_MAX_NUMA_NODES];
1709         int hp_sz_idx, socket_id;
1710
1711         memset(used_hp, 0, sizeof(used_hp));
1712
1713         for (hp_sz_idx = 0;
1714                         hp_sz_idx < (int) internal_config.num_hugepage_sizes;
1715                         hp_sz_idx++) {
1716 #ifndef RTE_ARCH_64
1717                 struct hugepage_info dummy;
1718                 unsigned int i;
1719 #endif
1720                 /* also initialize used_hp hugepage sizes in used_hp */
1721                 struct hugepage_info *hpi;
1722                 hpi = &internal_config.hugepage_info[hp_sz_idx];
1723                 used_hp[hp_sz_idx].hugepage_sz = hpi->hugepage_sz;
1724
1725 #ifndef RTE_ARCH_64
1726                 /* for 32-bit, limit number of pages on socket to whatever we've
1727                  * preallocated, as we cannot allocate more.
1728                  */
1729                 memset(&dummy, 0, sizeof(dummy));
1730                 dummy.hugepage_sz = hpi->hugepage_sz;
1731                 if (rte_memseg_list_walk(hugepage_count_walk, &dummy) < 0)
1732                         return -1;
1733
1734                 for (i = 0; i < RTE_DIM(dummy.num_pages); i++) {
1735                         hpi->num_pages[i] = RTE_MIN(hpi->num_pages[i],
1736                                         dummy.num_pages[i]);
1737                 }
1738 #endif
1739         }
1740
1741         /* make a copy of socket_mem, needed for balanced allocation. */
1742         for (hp_sz_idx = 0; hp_sz_idx < RTE_MAX_NUMA_NODES; hp_sz_idx++)
1743                 memory[hp_sz_idx] = internal_config.socket_mem[hp_sz_idx];
1744
1745         /* calculate final number of pages */
1746         if (calc_num_pages_per_socket(memory,
1747                         internal_config.hugepage_info, used_hp,
1748                         internal_config.num_hugepage_sizes) < 0)
1749                 return -1;
1750
1751         for (hp_sz_idx = 0;
1752                         hp_sz_idx < (int)internal_config.num_hugepage_sizes;
1753                         hp_sz_idx++) {
1754                 for (socket_id = 0; socket_id < RTE_MAX_NUMA_NODES;
1755                                 socket_id++) {
1756                         struct rte_memseg **pages;
1757                         struct hugepage_info *hpi = &used_hp[hp_sz_idx];
1758                         unsigned int num_pages = hpi->num_pages[socket_id];
1759                         unsigned int num_pages_alloc;
1760
1761                         if (num_pages == 0)
1762                                 continue;
1763
1764                         RTE_LOG(DEBUG, EAL, "Allocating %u pages of size %" PRIu64 "M on socket %i\n",
1765                                 num_pages, hpi->hugepage_sz >> 20, socket_id);
1766
1767                         /* we may not be able to allocate all pages in one go,
1768                          * because we break up our memory map into multiple
1769                          * memseg lists. therefore, try allocating multiple
1770                          * times and see if we can get the desired number of
1771                          * pages from multiple allocations.
1772                          */
1773
1774                         num_pages_alloc = 0;
1775                         do {
1776                                 int i, cur_pages, needed;
1777
1778                                 needed = num_pages - num_pages_alloc;
1779
1780                                 pages = malloc(sizeof(*pages) * needed);
1781
1782                                 /* do not request exact number of pages */
1783                                 cur_pages = eal_memalloc_alloc_seg_bulk(pages,
1784                                                 needed, hpi->hugepage_sz,
1785                                                 socket_id, false);
1786                                 if (cur_pages <= 0) {
1787                                         free(pages);
1788                                         return -1;
1789                                 }
1790
1791                                 /* mark preallocated pages as unfreeable */
1792                                 for (i = 0; i < cur_pages; i++) {
1793                                         struct rte_memseg *ms = pages[i];
1794                                         ms->flags |= RTE_MEMSEG_FLAG_DO_NOT_FREE;
1795                                 }
1796                                 free(pages);
1797
1798                                 num_pages_alloc += cur_pages;
1799                         } while (num_pages_alloc != num_pages);
1800                 }
1801         }
1802         /* if socket limits were specified, set them */
1803         if (internal_config.force_socket_limits) {
1804                 unsigned int i;
1805                 for (i = 0; i < RTE_MAX_NUMA_NODES; i++) {
1806                         uint64_t limit = internal_config.socket_limit[i];
1807                         if (limit == 0)
1808                                 continue;
1809                         if (rte_mem_alloc_validator_register("socket-limit",
1810                                         limits_callback, i, limit))
1811                                 RTE_LOG(ERR, EAL, "Failed to register socket limits validator callback\n");
1812                 }
1813         }
1814         return 0;
1815 }
1816
1817 /*
1818  * uses fstat to report the size of a file on disk
1819  */
1820 static off_t
1821 getFileSize(int fd)
1822 {
1823         struct stat st;
1824         if (fstat(fd, &st) < 0)
1825                 return 0;
1826         return st.st_size;
1827 }
1828
1829 /*
1830  * This creates the memory mappings in the secondary process to match that of
1831  * the server process. It goes through each memory segment in the DPDK runtime
1832  * configuration and finds the hugepages which form that segment, mapping them
1833  * in order to form a contiguous block in the virtual memory space
1834  */
1835 static int
1836 eal_legacy_hugepage_attach(void)
1837 {
1838         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1839         struct hugepage_file *hp = NULL;
1840         unsigned int num_hp = 0;
1841         unsigned int i = 0;
1842         unsigned int cur_seg;
1843         off_t size = 0;
1844         int fd, fd_hugepage = -1;
1845
1846         if (aslr_enabled() > 0) {
1847                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
1848                                 "(ASLR) is enabled in the kernel.\n");
1849                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
1850                                 "into secondary processes\n");
1851         }
1852
1853         fd_hugepage = open(eal_hugepage_data_path(), O_RDONLY);
1854         if (fd_hugepage < 0) {
1855                 RTE_LOG(ERR, EAL, "Could not open %s\n",
1856                                 eal_hugepage_data_path());
1857                 goto error;
1858         }
1859
1860         size = getFileSize(fd_hugepage);
1861         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
1862         if (hp == MAP_FAILED) {
1863                 RTE_LOG(ERR, EAL, "Could not mmap %s\n",
1864                                 eal_hugepage_data_path());
1865                 goto error;
1866         }
1867
1868         num_hp = size / sizeof(struct hugepage_file);
1869         RTE_LOG(DEBUG, EAL, "Analysing %u files\n", num_hp);
1870
1871         /* map all segments into memory to make sure we get the addrs. the
1872          * segments themselves are already in memseg list (which is shared and
1873          * has its VA space already preallocated), so we just need to map
1874          * everything into correct addresses.
1875          */
1876         for (i = 0; i < num_hp; i++) {
1877                 struct hugepage_file *hf = &hp[i];
1878                 size_t map_sz = hf->size;
1879                 void *map_addr = hf->final_va;
1880                 int msl_idx, ms_idx;
1881                 struct rte_memseg_list *msl;
1882                 struct rte_memseg *ms;
1883
1884                 /* if size is zero, no more pages left */
1885                 if (map_sz == 0)
1886                         break;
1887
1888                 fd = open(hf->filepath, O_RDWR);
1889                 if (fd < 0) {
1890                         RTE_LOG(ERR, EAL, "Could not open %s: %s\n",
1891                                 hf->filepath, strerror(errno));
1892                         goto error;
1893                 }
1894
1895                 map_addr = mmap(map_addr, map_sz, PROT_READ | PROT_WRITE,
1896                                 MAP_SHARED | MAP_FIXED, fd, 0);
1897                 if (map_addr == MAP_FAILED) {
1898                         RTE_LOG(ERR, EAL, "Could not map %s: %s\n",
1899                                 hf->filepath, strerror(errno));
1900                         goto fd_error;
1901                 }
1902
1903                 /* set shared lock on the file. */
1904                 if (flock(fd, LOCK_SH) < 0) {
1905                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed: %s\n",
1906                                 __func__, strerror(errno));
1907                         goto fd_error;
1908                 }
1909
1910                 /* find segment data */
1911                 msl = rte_mem_virt2memseg_list(map_addr);
1912                 if (msl == NULL) {
1913                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg list\n",
1914                                 __func__);
1915                         goto fd_error;
1916                 }
1917                 ms = rte_mem_virt2memseg(map_addr, msl);
1918                 if (ms == NULL) {
1919                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg\n",
1920                                 __func__);
1921                         goto fd_error;
1922                 }
1923
1924                 msl_idx = msl - mcfg->memsegs;
1925                 ms_idx = rte_fbarray_find_idx(&msl->memseg_arr, ms);
1926                 if (ms_idx < 0) {
1927                         RTE_LOG(DEBUG, EAL, "%s(): Cannot find memseg idx\n",
1928                                 __func__);
1929                         goto fd_error;
1930                 }
1931
1932                 /* store segment fd internally */
1933                 if (eal_memalloc_set_seg_fd(msl_idx, ms_idx, fd) < 0)
1934                         RTE_LOG(ERR, EAL, "Could not store segment fd: %s\n",
1935                                 rte_strerror(rte_errno));
1936         }
1937         /* unmap the hugepage config file, since we are done using it */
1938         munmap(hp, size);
1939         close(fd_hugepage);
1940         return 0;
1941
1942 fd_error:
1943         close(fd);
1944 error:
1945         /* map all segments into memory to make sure we get the addrs */
1946         cur_seg = 0;
1947         for (cur_seg = 0; cur_seg < i; cur_seg++) {
1948                 struct hugepage_file *hf = &hp[i];
1949                 size_t map_sz = hf->size;
1950                 void *map_addr = hf->final_va;
1951
1952                 munmap(map_addr, map_sz);
1953         }
1954         if (hp != NULL && hp != MAP_FAILED)
1955                 munmap(hp, size);
1956         if (fd_hugepage >= 0)
1957                 close(fd_hugepage);
1958         return -1;
1959 }
1960
1961 static int
1962 eal_hugepage_attach(void)
1963 {
1964         if (eal_memalloc_sync_with_primary()) {
1965                 RTE_LOG(ERR, EAL, "Could not map memory from primary process\n");
1966                 if (aslr_enabled() > 0)
1967                         RTE_LOG(ERR, EAL, "It is recommended to disable ASLR in the kernel and retry running both primary and secondary processes\n");
1968                 return -1;
1969         }
1970         return 0;
1971 }
1972
1973 int
1974 rte_eal_hugepage_init(void)
1975 {
1976         return internal_config.legacy_mem ?
1977                         eal_legacy_hugepage_init() :
1978                         eal_hugepage_init();
1979 }
1980
1981 int
1982 rte_eal_hugepage_attach(void)
1983 {
1984         return internal_config.legacy_mem ?
1985                         eal_legacy_hugepage_attach() :
1986                         eal_hugepage_attach();
1987 }
1988
1989 int
1990 rte_eal_using_phys_addrs(void)
1991 {
1992         if (phys_addrs_available == -1) {
1993                 uint64_t tmp = 0;
1994
1995                 if (rte_eal_has_hugepages() != 0 &&
1996                     rte_mem_virt2phy(&tmp) != RTE_BAD_PHYS_ADDR)
1997                         phys_addrs_available = 1;
1998                 else
1999                         phys_addrs_available = 0;
2000         }
2001         return phys_addrs_available;
2002 }
2003
2004 static int __rte_unused
2005 memseg_primary_init_32(void)
2006 {
2007         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2008         int active_sockets, hpi_idx, msl_idx = 0;
2009         unsigned int socket_id, i;
2010         struct rte_memseg_list *msl;
2011         uint64_t extra_mem_per_socket, total_extra_mem, total_requested_mem;
2012         uint64_t max_mem;
2013
2014         /* no-huge does not need this at all */
2015         if (internal_config.no_hugetlbfs)
2016                 return 0;
2017
2018         /* this is a giant hack, but desperate times call for desperate
2019          * measures. in legacy 32-bit mode, we cannot preallocate VA space,
2020          * because having upwards of 2 gigabytes of VA space already mapped will
2021          * interfere with our ability to map and sort hugepages.
2022          *
2023          * therefore, in legacy 32-bit mode, we will be initializing memseg
2024          * lists much later - in eal_memory.c, right after we unmap all the
2025          * unneeded pages. this will not affect secondary processes, as those
2026          * should be able to mmap the space without (too many) problems.
2027          */
2028         if (internal_config.legacy_mem)
2029                 return 0;
2030
2031         /* 32-bit mode is a very special case. we cannot know in advance where
2032          * the user will want to allocate their memory, so we have to do some
2033          * heuristics.
2034          */
2035         active_sockets = 0;
2036         total_requested_mem = 0;
2037         if (internal_config.force_sockets)
2038                 for (i = 0; i < rte_socket_count(); i++) {
2039                         uint64_t mem;
2040
2041                         socket_id = rte_socket_id_by_idx(i);
2042                         mem = internal_config.socket_mem[socket_id];
2043
2044                         if (mem == 0)
2045                                 continue;
2046
2047                         active_sockets++;
2048                         total_requested_mem += mem;
2049                 }
2050         else
2051                 total_requested_mem = internal_config.memory;
2052
2053         max_mem = (uint64_t)RTE_MAX_MEM_MB << 20;
2054         if (total_requested_mem > max_mem) {
2055                 RTE_LOG(ERR, EAL, "Invalid parameters: 32-bit process can at most use %uM of memory\n",
2056                                 (unsigned int)(max_mem >> 20));
2057                 return -1;
2058         }
2059         total_extra_mem = max_mem - total_requested_mem;
2060         extra_mem_per_socket = active_sockets == 0 ? total_extra_mem :
2061                         total_extra_mem / active_sockets;
2062
2063         /* the allocation logic is a little bit convoluted, but here's how it
2064          * works, in a nutshell:
2065          *  - if user hasn't specified on which sockets to allocate memory via
2066          *    --socket-mem, we allocate all of our memory on master core socket.
2067          *  - if user has specified sockets to allocate memory on, there may be
2068          *    some "unused" memory left (e.g. if user has specified --socket-mem
2069          *    such that not all memory adds up to 2 gigabytes), so add it to all
2070          *    sockets that are in use equally.
2071          *
2072          * page sizes are sorted by size in descending order, so we can safely
2073          * assume that we dispense with bigger page sizes first.
2074          */
2075
2076         /* create memseg lists */
2077         for (i = 0; i < rte_socket_count(); i++) {
2078                 int hp_sizes = (int) internal_config.num_hugepage_sizes;
2079                 uint64_t max_socket_mem, cur_socket_mem;
2080                 unsigned int master_lcore_socket;
2081                 struct rte_config *cfg = rte_eal_get_configuration();
2082                 bool skip;
2083
2084                 socket_id = rte_socket_id_by_idx(i);
2085
2086 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2087                 /* we can still sort pages by socket in legacy mode */
2088                 if (!internal_config.legacy_mem && socket_id > 0)
2089                         break;
2090 #endif
2091
2092                 /* if we didn't specifically request memory on this socket */
2093                 skip = active_sockets != 0 &&
2094                                 internal_config.socket_mem[socket_id] == 0;
2095                 /* ...or if we didn't specifically request memory on *any*
2096                  * socket, and this is not master lcore
2097                  */
2098                 master_lcore_socket = rte_lcore_to_socket_id(cfg->master_lcore);
2099                 skip |= active_sockets == 0 && socket_id != master_lcore_socket;
2100
2101                 if (skip) {
2102                         RTE_LOG(DEBUG, EAL, "Will not preallocate memory on socket %u\n",
2103                                         socket_id);
2104                         continue;
2105                 }
2106
2107                 /* max amount of memory on this socket */
2108                 max_socket_mem = (active_sockets != 0 ?
2109                                         internal_config.socket_mem[socket_id] :
2110                                         internal_config.memory) +
2111                                         extra_mem_per_socket;
2112                 cur_socket_mem = 0;
2113
2114                 for (hpi_idx = 0; hpi_idx < hp_sizes; hpi_idx++) {
2115                         uint64_t max_pagesz_mem, cur_pagesz_mem = 0;
2116                         uint64_t hugepage_sz;
2117                         struct hugepage_info *hpi;
2118                         int type_msl_idx, max_segs, total_segs = 0;
2119
2120                         hpi = &internal_config.hugepage_info[hpi_idx];
2121                         hugepage_sz = hpi->hugepage_sz;
2122
2123                         /* check if pages are actually available */
2124                         if (hpi->num_pages[socket_id] == 0)
2125                                 continue;
2126
2127                         max_segs = RTE_MAX_MEMSEG_PER_TYPE;
2128                         max_pagesz_mem = max_socket_mem - cur_socket_mem;
2129
2130                         /* make it multiple of page size */
2131                         max_pagesz_mem = RTE_ALIGN_FLOOR(max_pagesz_mem,
2132                                         hugepage_sz);
2133
2134                         RTE_LOG(DEBUG, EAL, "Attempting to preallocate "
2135                                         "%" PRIu64 "M on socket %i\n",
2136                                         max_pagesz_mem >> 20, socket_id);
2137
2138                         type_msl_idx = 0;
2139                         while (cur_pagesz_mem < max_pagesz_mem &&
2140                                         total_segs < max_segs) {
2141                                 uint64_t cur_mem;
2142                                 unsigned int n_segs;
2143
2144                                 if (msl_idx >= RTE_MAX_MEMSEG_LISTS) {
2145                                         RTE_LOG(ERR, EAL,
2146                                                 "No more space in memseg lists, please increase %s\n",
2147                                                 RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2148                                         return -1;
2149                                 }
2150
2151                                 msl = &mcfg->memsegs[msl_idx];
2152
2153                                 cur_mem = get_mem_amount(hugepage_sz,
2154                                                 max_pagesz_mem);
2155                                 n_segs = cur_mem / hugepage_sz;
2156
2157                                 if (alloc_memseg_list(msl, hugepage_sz, n_segs,
2158                                                 socket_id, type_msl_idx)) {
2159                                         /* failing to allocate a memseg list is
2160                                          * a serious error.
2161                                          */
2162                                         RTE_LOG(ERR, EAL, "Cannot allocate memseg list\n");
2163                                         return -1;
2164                                 }
2165
2166                                 if (alloc_va_space(msl)) {
2167                                         /* if we couldn't allocate VA space, we
2168                                          * can try with smaller page sizes.
2169                                          */
2170                                         RTE_LOG(ERR, EAL, "Cannot allocate VA space for memseg list, retrying with different page size\n");
2171                                         /* deallocate memseg list */
2172                                         if (free_memseg_list(msl))
2173                                                 return -1;
2174                                         break;
2175                                 }
2176
2177                                 total_segs += msl->memseg_arr.len;
2178                                 cur_pagesz_mem = total_segs * hugepage_sz;
2179                                 type_msl_idx++;
2180                                 msl_idx++;
2181                         }
2182                         cur_socket_mem += cur_pagesz_mem;
2183                 }
2184                 if (cur_socket_mem == 0) {
2185                         RTE_LOG(ERR, EAL, "Cannot allocate VA space on socket %u\n",
2186                                 socket_id);
2187                         return -1;
2188                 }
2189         }
2190
2191         return 0;
2192 }
2193
2194 static int __rte_unused
2195 memseg_primary_init(void)
2196 {
2197         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2198         struct memtype {
2199                 uint64_t page_sz;
2200                 int socket_id;
2201         } *memtypes = NULL;
2202         int i, hpi_idx, msl_idx, ret = -1; /* fail unless told to succeed */
2203         struct rte_memseg_list *msl;
2204         uint64_t max_mem, max_mem_per_type;
2205         unsigned int max_seglists_per_type;
2206         unsigned int n_memtypes, cur_type;
2207
2208         /* no-huge does not need this at all */
2209         if (internal_config.no_hugetlbfs)
2210                 return 0;
2211
2212         /*
2213          * figuring out amount of memory we're going to have is a long and very
2214          * involved process. the basic element we're operating with is a memory
2215          * type, defined as a combination of NUMA node ID and page size (so that
2216          * e.g. 2 sockets with 2 page sizes yield 4 memory types in total).
2217          *
2218          * deciding amount of memory going towards each memory type is a
2219          * balancing act between maximum segments per type, maximum memory per
2220          * type, and number of detected NUMA nodes. the goal is to make sure
2221          * each memory type gets at least one memseg list.
2222          *
2223          * the total amount of memory is limited by RTE_MAX_MEM_MB value.
2224          *
2225          * the total amount of memory per type is limited by either
2226          * RTE_MAX_MEM_MB_PER_TYPE, or by RTE_MAX_MEM_MB divided by the number
2227          * of detected NUMA nodes. additionally, maximum number of segments per
2228          * type is also limited by RTE_MAX_MEMSEG_PER_TYPE. this is because for
2229          * smaller page sizes, it can take hundreds of thousands of segments to
2230          * reach the above specified per-type memory limits.
2231          *
2232          * additionally, each type may have multiple memseg lists associated
2233          * with it, each limited by either RTE_MAX_MEM_MB_PER_LIST for bigger
2234          * page sizes, or RTE_MAX_MEMSEG_PER_LIST segments for smaller ones.
2235          *
2236          * the number of memseg lists per type is decided based on the above
2237          * limits, and also taking number of detected NUMA nodes, to make sure
2238          * that we don't run out of memseg lists before we populate all NUMA
2239          * nodes with memory.
2240          *
2241          * we do this in three stages. first, we collect the number of types.
2242          * then, we figure out memory constraints and populate the list of
2243          * would-be memseg lists. then, we go ahead and allocate the memseg
2244          * lists.
2245          */
2246
2247         /* create space for mem types */
2248         n_memtypes = internal_config.num_hugepage_sizes * rte_socket_count();
2249         memtypes = calloc(n_memtypes, sizeof(*memtypes));
2250         if (memtypes == NULL) {
2251                 RTE_LOG(ERR, EAL, "Cannot allocate space for memory types\n");
2252                 return -1;
2253         }
2254
2255         /* populate mem types */
2256         cur_type = 0;
2257         for (hpi_idx = 0; hpi_idx < (int) internal_config.num_hugepage_sizes;
2258                         hpi_idx++) {
2259                 struct hugepage_info *hpi;
2260                 uint64_t hugepage_sz;
2261
2262                 hpi = &internal_config.hugepage_info[hpi_idx];
2263                 hugepage_sz = hpi->hugepage_sz;
2264
2265                 for (i = 0; i < (int) rte_socket_count(); i++, cur_type++) {
2266                         int socket_id = rte_socket_id_by_idx(i);
2267
2268 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2269                         /* we can still sort pages by socket in legacy mode */
2270                         if (!internal_config.legacy_mem && socket_id > 0)
2271                                 break;
2272 #endif
2273                         memtypes[cur_type].page_sz = hugepage_sz;
2274                         memtypes[cur_type].socket_id = socket_id;
2275
2276                         RTE_LOG(DEBUG, EAL, "Detected memory type: "
2277                                 "socket_id:%u hugepage_sz:%" PRIu64 "\n",
2278                                 socket_id, hugepage_sz);
2279                 }
2280         }
2281         /* number of memtypes could have been lower due to no NUMA support */
2282         n_memtypes = cur_type;
2283
2284         /* set up limits for types */
2285         max_mem = (uint64_t)RTE_MAX_MEM_MB << 20;
2286         max_mem_per_type = RTE_MIN((uint64_t)RTE_MAX_MEM_MB_PER_TYPE << 20,
2287                         max_mem / n_memtypes);
2288         /*
2289          * limit maximum number of segment lists per type to ensure there's
2290          * space for memseg lists for all NUMA nodes with all page sizes
2291          */
2292         max_seglists_per_type = RTE_MAX_MEMSEG_LISTS / n_memtypes;
2293
2294         if (max_seglists_per_type == 0) {
2295                 RTE_LOG(ERR, EAL, "Cannot accommodate all memory types, please increase %s\n",
2296                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2297                 goto out;
2298         }
2299
2300         /* go through all mem types and create segment lists */
2301         msl_idx = 0;
2302         for (cur_type = 0; cur_type < n_memtypes; cur_type++) {
2303                 unsigned int cur_seglist, n_seglists, n_segs;
2304                 unsigned int max_segs_per_type, max_segs_per_list;
2305                 struct memtype *type = &memtypes[cur_type];
2306                 uint64_t max_mem_per_list, pagesz;
2307                 int socket_id;
2308
2309                 pagesz = type->page_sz;
2310                 socket_id = type->socket_id;
2311
2312                 /*
2313                  * we need to create segment lists for this type. we must take
2314                  * into account the following things:
2315                  *
2316                  * 1. total amount of memory we can use for this memory type
2317                  * 2. total amount of memory per memseg list allowed
2318                  * 3. number of segments needed to fit the amount of memory
2319                  * 4. number of segments allowed per type
2320                  * 5. number of segments allowed per memseg list
2321                  * 6. number of memseg lists we are allowed to take up
2322                  */
2323
2324                 /* calculate how much segments we will need in total */
2325                 max_segs_per_type = max_mem_per_type / pagesz;
2326                 /* limit number of segments to maximum allowed per type */
2327                 max_segs_per_type = RTE_MIN(max_segs_per_type,
2328                                 (unsigned int)RTE_MAX_MEMSEG_PER_TYPE);
2329                 /* limit number of segments to maximum allowed per list */
2330                 max_segs_per_list = RTE_MIN(max_segs_per_type,
2331                                 (unsigned int)RTE_MAX_MEMSEG_PER_LIST);
2332
2333                 /* calculate how much memory we can have per segment list */
2334                 max_mem_per_list = RTE_MIN(max_segs_per_list * pagesz,
2335                                 (uint64_t)RTE_MAX_MEM_MB_PER_LIST << 20);
2336
2337                 /* calculate how many segments each segment list will have */
2338                 n_segs = RTE_MIN(max_segs_per_list, max_mem_per_list / pagesz);
2339
2340                 /* calculate how many segment lists we can have */
2341                 n_seglists = RTE_MIN(max_segs_per_type / n_segs,
2342                                 max_mem_per_type / max_mem_per_list);
2343
2344                 /* limit number of segment lists according to our maximum */
2345                 n_seglists = RTE_MIN(n_seglists, max_seglists_per_type);
2346
2347                 RTE_LOG(DEBUG, EAL, "Creating %i segment lists: "
2348                                 "n_segs:%i socket_id:%i hugepage_sz:%" PRIu64 "\n",
2349                         n_seglists, n_segs, socket_id, pagesz);
2350
2351                 /* create all segment lists */
2352                 for (cur_seglist = 0; cur_seglist < n_seglists; cur_seglist++) {
2353                         if (msl_idx >= RTE_MAX_MEMSEG_LISTS) {
2354                                 RTE_LOG(ERR, EAL,
2355                                         "No more space in memseg lists, please increase %s\n",
2356                                         RTE_STR(CONFIG_RTE_MAX_MEMSEG_LISTS));
2357                                 goto out;
2358                         }
2359                         msl = &mcfg->memsegs[msl_idx++];
2360
2361                         if (alloc_memseg_list(msl, pagesz, n_segs,
2362                                         socket_id, cur_seglist))
2363                                 goto out;
2364
2365                         if (alloc_va_space(msl)) {
2366                                 RTE_LOG(ERR, EAL, "Cannot allocate VA space for memseg list\n");
2367                                 goto out;
2368                         }
2369                 }
2370         }
2371         /* we're successful */
2372         ret = 0;
2373 out:
2374         free(memtypes);
2375         return ret;
2376 }
2377
2378 static int
2379 memseg_secondary_init(void)
2380 {
2381         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
2382         int msl_idx = 0;
2383         struct rte_memseg_list *msl;
2384
2385         for (msl_idx = 0; msl_idx < RTE_MAX_MEMSEG_LISTS; msl_idx++) {
2386
2387                 msl = &mcfg->memsegs[msl_idx];
2388
2389                 /* skip empty memseg lists */
2390                 if (msl->memseg_arr.len == 0)
2391                         continue;
2392
2393                 if (rte_fbarray_attach(&msl->memseg_arr)) {
2394                         RTE_LOG(ERR, EAL, "Cannot attach to primary process memseg lists\n");
2395                         return -1;
2396                 }
2397
2398                 /* preallocate VA space */
2399                 if (alloc_va_space(msl)) {
2400                         RTE_LOG(ERR, EAL, "Cannot preallocate VA space for hugepage memory\n");
2401                         return -1;
2402                 }
2403         }
2404
2405         return 0;
2406 }
2407
2408 int
2409 rte_eal_memseg_init(void)
2410 {
2411         /* increase rlimit to maximum */
2412         struct rlimit lim;
2413
2414         if (getrlimit(RLIMIT_NOFILE, &lim) == 0) {
2415                 /* set limit to maximum */
2416                 lim.rlim_cur = lim.rlim_max;
2417
2418                 if (setrlimit(RLIMIT_NOFILE, &lim) < 0) {
2419                         RTE_LOG(DEBUG, EAL, "Setting maximum number of open files failed: %s\n",
2420                                         strerror(errno));
2421                 } else {
2422                         RTE_LOG(DEBUG, EAL, "Setting maximum number of open files to %"
2423                                         PRIu64 "\n",
2424                                         (uint64_t)lim.rlim_cur);
2425                 }
2426         } else {
2427                 RTE_LOG(ERR, EAL, "Cannot get current resource limits\n");
2428         }
2429 #ifndef RTE_EAL_NUMA_AWARE_HUGEPAGES
2430         if (!internal_config.legacy_mem && rte_socket_count() > 1) {
2431                 RTE_LOG(WARNING, EAL, "DPDK is running on a NUMA system, but is compiled without NUMA support.\n");
2432                 RTE_LOG(WARNING, EAL, "This will have adverse consequences for performance and usability.\n");
2433                 RTE_LOG(WARNING, EAL, "Please use --"OPT_LEGACY_MEM" option, or recompile with NUMA support.\n");
2434         }
2435 #endif
2436
2437         return rte_eal_process_type() == RTE_PROC_PRIMARY ?
2438 #ifndef RTE_ARCH_64
2439                         memseg_primary_init_32() :
2440 #else
2441                         memseg_primary_init() :
2442 #endif
2443                         memseg_secondary_init();
2444 }