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