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