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