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