Imported Upstream version 16.11
[deb_dpdk.git] / lib / librte_eal / linuxapp / eal / eal_memory.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 /*   BSD LICENSE
34  *
35  *   Copyright(c) 2013 6WIND.
36  *
37  *   Redistribution and use in source and binary forms, with or without
38  *   modification, are permitted provided that the following conditions
39  *   are met:
40  *
41  *     * Redistributions of source code must retain the above copyright
42  *       notice, this list of conditions and the following disclaimer.
43  *     * Redistributions in binary form must reproduce the above copyright
44  *       notice, this list of conditions and the following disclaimer in
45  *       the documentation and/or other materials provided with the
46  *       distribution.
47  *     * Neither the name of 6WIND S.A. nor the names of its
48  *       contributors may be used to endorse or promote products derived
49  *       from this software without specific prior written permission.
50  *
51  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
52  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
53  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
54  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
55  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
56  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
57  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
58  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
59  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
61  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62  */
63
64 #define _FILE_OFFSET_BITS 64
65 #include <errno.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <stdio.h>
69 #include <stdint.h>
70 #include <inttypes.h>
71 #include <string.h>
72 #include <stdarg.h>
73 #include <sys/mman.h>
74 #include <sys/types.h>
75 #include <sys/stat.h>
76 #include <sys/queue.h>
77 #include <sys/file.h>
78 #include <unistd.h>
79 #include <limits.h>
80 #include <errno.h>
81 #include <sys/ioctl.h>
82 #include <sys/time.h>
83 #include <signal.h>
84 #include <setjmp.h>
85
86 #include <rte_log.h>
87 #include <rte_memory.h>
88 #include <rte_memzone.h>
89 #include <rte_launch.h>
90 #include <rte_eal.h>
91 #include <rte_eal_memconfig.h>
92 #include <rte_per_lcore.h>
93 #include <rte_lcore.h>
94 #include <rte_common.h>
95 #include <rte_string_fns.h>
96
97 #include "eal_private.h"
98 #include "eal_internal_cfg.h"
99 #include "eal_filesystem.h"
100 #include "eal_hugepages.h"
101
102 #define PFN_MASK_SIZE   8
103
104 #ifdef RTE_LIBRTE_XEN_DOM0
105 int rte_xen_dom0_supported(void)
106 {
107         return internal_config.xen_dom0_support;
108 }
109 #endif
110
111 /**
112  * @file
113  * Huge page mapping under linux
114  *
115  * To reserve a big contiguous amount of memory, we use the hugepage
116  * feature of linux. For that, we need to have hugetlbfs mounted. This
117  * code will create many files in this directory (one per page) and
118  * map them in virtual memory. For each page, we will retrieve its
119  * physical address and remap it in order to have a virtual contiguous
120  * zone as well as a physical contiguous zone.
121  */
122
123 static uint64_t baseaddr_offset;
124
125 static unsigned proc_pagemap_readable;
126
127 #define RANDOMIZE_VA_SPACE_FILE "/proc/sys/kernel/randomize_va_space"
128
129 static void
130 test_proc_pagemap_readable(void)
131 {
132         int fd = open("/proc/self/pagemap", O_RDONLY);
133
134         if (fd < 0) {
135                 RTE_LOG(ERR, EAL,
136                         "Cannot open /proc/self/pagemap: %s. "
137                         "virt2phys address translation will not work\n",
138                         strerror(errno));
139                 return;
140         }
141
142         /* Is readable */
143         close(fd);
144         proc_pagemap_readable = 1;
145 }
146
147 /* Lock page in physical memory and prevent from swapping. */
148 int
149 rte_mem_lock_page(const void *virt)
150 {
151         unsigned long virtual = (unsigned long)virt;
152         int page_size = getpagesize();
153         unsigned long aligned = (virtual & ~ (page_size - 1));
154         return mlock((void*)aligned, page_size);
155 }
156
157 /*
158  * Get physical address of any mapped virtual address in the current process.
159  */
160 phys_addr_t
161 rte_mem_virt2phy(const void *virtaddr)
162 {
163         int fd, retval;
164         uint64_t page, physaddr;
165         unsigned long virt_pfn;
166         int page_size;
167         off_t offset;
168
169         /* when using dom0, /proc/self/pagemap always returns 0, check in
170          * dpdk memory by browsing the memsegs */
171         if (rte_xen_dom0_supported()) {
172                 struct rte_mem_config *mcfg;
173                 struct rte_memseg *memseg;
174                 unsigned i;
175
176                 mcfg = rte_eal_get_configuration()->mem_config;
177                 for (i = 0; i < RTE_MAX_MEMSEG; i++) {
178                         memseg = &mcfg->memseg[i];
179                         if (memseg->addr == NULL)
180                                 break;
181                         if (virtaddr > memseg->addr &&
182                                         virtaddr < RTE_PTR_ADD(memseg->addr,
183                                                 memseg->len)) {
184                                 return memseg->phys_addr +
185                                         RTE_PTR_DIFF(virtaddr, memseg->addr);
186                         }
187                 }
188
189                 return RTE_BAD_PHYS_ADDR;
190         }
191
192         /* Cannot parse /proc/self/pagemap, no need to log errors everywhere */
193         if (!proc_pagemap_readable)
194                 return RTE_BAD_PHYS_ADDR;
195
196         /* standard page size */
197         page_size = getpagesize();
198
199         fd = open("/proc/self/pagemap", O_RDONLY);
200         if (fd < 0) {
201                 RTE_LOG(ERR, EAL, "%s(): cannot open /proc/self/pagemap: %s\n",
202                         __func__, strerror(errno));
203                 return RTE_BAD_PHYS_ADDR;
204         }
205
206         virt_pfn = (unsigned long)virtaddr / page_size;
207         offset = sizeof(uint64_t) * virt_pfn;
208         if (lseek(fd, offset, SEEK_SET) == (off_t) -1) {
209                 RTE_LOG(ERR, EAL, "%s(): seek error in /proc/self/pagemap: %s\n",
210                                 __func__, strerror(errno));
211                 close(fd);
212                 return RTE_BAD_PHYS_ADDR;
213         }
214
215         retval = read(fd, &page, PFN_MASK_SIZE);
216         close(fd);
217         if (retval < 0) {
218                 RTE_LOG(ERR, EAL, "%s(): cannot read /proc/self/pagemap: %s\n",
219                                 __func__, strerror(errno));
220                 return RTE_BAD_PHYS_ADDR;
221         } else if (retval != PFN_MASK_SIZE) {
222                 RTE_LOG(ERR, EAL, "%s(): read %d bytes from /proc/self/pagemap "
223                                 "but expected %d:\n",
224                                 __func__, retval, PFN_MASK_SIZE);
225                 return RTE_BAD_PHYS_ADDR;
226         }
227
228         /*
229          * the pfn (page frame number) are bits 0-54 (see
230          * pagemap.txt in linux Documentation)
231          */
232         physaddr = ((page & 0x7fffffffffffffULL) * page_size)
233                 + ((unsigned long)virtaddr % page_size);
234
235         return physaddr;
236 }
237
238 /*
239  * For each hugepage in hugepg_tbl, fill the physaddr value. We find
240  * it by browsing the /proc/self/pagemap special file.
241  */
242 static int
243 find_physaddrs(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
244 {
245         unsigned i;
246         phys_addr_t addr;
247
248         for (i = 0; i < hpi->num_pages[0]; i++) {
249                 addr = rte_mem_virt2phy(hugepg_tbl[i].orig_va);
250                 if (addr == RTE_BAD_PHYS_ADDR)
251                         return -1;
252                 hugepg_tbl[i].physaddr = addr;
253         }
254         return 0;
255 }
256
257 /*
258  * Check whether address-space layout randomization is enabled in
259  * the kernel. This is important for multi-process as it can prevent
260  * two processes mapping data to the same virtual address
261  * Returns:
262  *    0 - address space randomization disabled
263  *    1/2 - address space randomization enabled
264  *    negative error code on error
265  */
266 static int
267 aslr_enabled(void)
268 {
269         char c;
270         int retval, fd = open(RANDOMIZE_VA_SPACE_FILE, O_RDONLY);
271         if (fd < 0)
272                 return -errno;
273         retval = read(fd, &c, 1);
274         close(fd);
275         if (retval < 0)
276                 return -errno;
277         if (retval == 0)
278                 return -EIO;
279         switch (c) {
280                 case '0' : return 0;
281                 case '1' : return 1;
282                 case '2' : return 2;
283                 default: return -EINVAL;
284         }
285 }
286
287 /*
288  * Try to mmap *size bytes in /dev/zero. If it is successful, return the
289  * pointer to the mmap'd area and keep *size unmodified. Else, retry
290  * with a smaller zone: decrease *size by hugepage_sz until it reaches
291  * 0. In this case, return NULL. Note: this function returns an address
292  * which is a multiple of hugepage size.
293  */
294 static void *
295 get_virtual_area(size_t *size, size_t hugepage_sz)
296 {
297         void *addr;
298         int fd;
299         long aligned_addr;
300
301         if (internal_config.base_virtaddr != 0) {
302                 addr = (void*) (uintptr_t) (internal_config.base_virtaddr +
303                                 baseaddr_offset);
304         }
305         else addr = NULL;
306
307         RTE_LOG(DEBUG, EAL, "Ask a virtual area of 0x%zx bytes\n", *size);
308
309         fd = open("/dev/zero", O_RDONLY);
310         if (fd < 0){
311                 RTE_LOG(ERR, EAL, "Cannot open /dev/zero\n");
312                 return NULL;
313         }
314         do {
315                 addr = mmap(addr,
316                                 (*size) + hugepage_sz, PROT_READ, MAP_PRIVATE, fd, 0);
317                 if (addr == MAP_FAILED)
318                         *size -= hugepage_sz;
319         } while (addr == MAP_FAILED && *size > 0);
320
321         if (addr == MAP_FAILED) {
322                 close(fd);
323                 RTE_LOG(ERR, EAL, "Cannot get a virtual area: %s\n",
324                         strerror(errno));
325                 return NULL;
326         }
327
328         munmap(addr, (*size) + hugepage_sz);
329         close(fd);
330
331         /* align addr to a huge page size boundary */
332         aligned_addr = (long)addr;
333         aligned_addr += (hugepage_sz - 1);
334         aligned_addr &= (~(hugepage_sz - 1));
335         addr = (void *)(aligned_addr);
336
337         RTE_LOG(DEBUG, EAL, "Virtual area found at %p (size = 0x%zx)\n",
338                 addr, *size);
339
340         /* increment offset */
341         baseaddr_offset += *size;
342
343         return addr;
344 }
345
346 static sigjmp_buf huge_jmpenv;
347
348 static void huge_sigbus_handler(int signo __rte_unused)
349 {
350         siglongjmp(huge_jmpenv, 1);
351 }
352
353 /* Put setjmp into a wrap method to avoid compiling error. Any non-volatile,
354  * non-static local variable in the stack frame calling sigsetjmp might be
355  * clobbered by a call to longjmp.
356  */
357 static int huge_wrap_sigsetjmp(void)
358 {
359         return sigsetjmp(huge_jmpenv, 1);
360 }
361
362 /*
363  * Mmap all hugepages of hugepage table: it first open a file in
364  * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
365  * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
366  * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
367  * map continguous physical blocks in contiguous virtual blocks.
368  */
369 static unsigned
370 map_all_hugepages(struct hugepage_file *hugepg_tbl,
371                 struct hugepage_info *hpi, int orig)
372 {
373         int fd;
374         unsigned i;
375         void *virtaddr;
376         void *vma_addr = NULL;
377         size_t vma_len = 0;
378
379         for (i = 0; i < hpi->num_pages[0]; i++) {
380                 uint64_t hugepage_sz = hpi->hugepage_sz;
381
382                 if (orig) {
383                         hugepg_tbl[i].file_id = i;
384                         hugepg_tbl[i].size = hugepage_sz;
385                         eal_get_hugefile_path(hugepg_tbl[i].filepath,
386                                         sizeof(hugepg_tbl[i].filepath), hpi->hugedir,
387                                         hugepg_tbl[i].file_id);
388                         hugepg_tbl[i].filepath[sizeof(hugepg_tbl[i].filepath) - 1] = '\0';
389                 }
390 #ifndef RTE_ARCH_64
391                 /* for 32-bit systems, don't remap 1G and 16G pages, just reuse
392                  * original map address as final map address.
393                  */
394                 else if ((hugepage_sz == RTE_PGSIZE_1G)
395                         || (hugepage_sz == RTE_PGSIZE_16G)) {
396                         hugepg_tbl[i].final_va = hugepg_tbl[i].orig_va;
397                         hugepg_tbl[i].orig_va = NULL;
398                         continue;
399                 }
400 #endif
401                 else if (vma_len == 0) {
402                         unsigned j, num_pages;
403
404                         /* reserve a virtual area for next contiguous
405                          * physical block: count the number of
406                          * contiguous physical pages. */
407                         for (j = i+1; j < hpi->num_pages[0] ; j++) {
408 #ifdef RTE_ARCH_PPC_64
409                                 /* The physical addresses are sorted in
410                                  * descending order on PPC64 */
411                                 if (hugepg_tbl[j].physaddr !=
412                                     hugepg_tbl[j-1].physaddr - hugepage_sz)
413                                         break;
414 #else
415                                 if (hugepg_tbl[j].physaddr !=
416                                     hugepg_tbl[j-1].physaddr + hugepage_sz)
417                                         break;
418 #endif
419                         }
420                         num_pages = j - i;
421                         vma_len = num_pages * hugepage_sz;
422
423                         /* get the biggest virtual memory area up to
424                          * vma_len. If it fails, vma_addr is NULL, so
425                          * let the kernel provide the address. */
426                         vma_addr = get_virtual_area(&vma_len, hpi->hugepage_sz);
427                         if (vma_addr == NULL)
428                                 vma_len = hugepage_sz;
429                 }
430
431                 /* try to create hugepage file */
432                 fd = open(hugepg_tbl[i].filepath, O_CREAT | O_RDWR, 0600);
433                 if (fd < 0) {
434                         RTE_LOG(DEBUG, EAL, "%s(): open failed: %s\n", __func__,
435                                         strerror(errno));
436                         return i;
437                 }
438
439                 /* map the segment, and populate page tables,
440                  * the kernel fills this segment with zeros */
441                 virtaddr = mmap(vma_addr, hugepage_sz, PROT_READ | PROT_WRITE,
442                                 MAP_SHARED | MAP_POPULATE, fd, 0);
443                 if (virtaddr == MAP_FAILED) {
444                         RTE_LOG(DEBUG, EAL, "%s(): mmap failed: %s\n", __func__,
445                                         strerror(errno));
446                         close(fd);
447                         return i;
448                 }
449
450                 if (orig) {
451                         hugepg_tbl[i].orig_va = virtaddr;
452                 }
453                 else {
454                         hugepg_tbl[i].final_va = virtaddr;
455                 }
456
457                 if (orig) {
458                         /* In linux, hugetlb limitations, like cgroup, are
459                          * enforced at fault time instead of mmap(), even
460                          * with the option of MAP_POPULATE. Kernel will send
461                          * a SIGBUS signal. To avoid to be killed, save stack
462                          * environment here, if SIGBUS happens, we can jump
463                          * back here.
464                          */
465                         if (huge_wrap_sigsetjmp()) {
466                                 RTE_LOG(DEBUG, EAL, "SIGBUS: Cannot mmap more "
467                                         "hugepages of size %u MB\n",
468                                         (unsigned)(hugepage_sz / 0x100000));
469                                 munmap(virtaddr, hugepage_sz);
470                                 close(fd);
471                                 unlink(hugepg_tbl[i].filepath);
472                                 return i;
473                         }
474                         *(int *)virtaddr = 0;
475                 }
476
477
478                 /* set shared flock on the file. */
479                 if (flock(fd, LOCK_SH | LOCK_NB) == -1) {
480                         RTE_LOG(DEBUG, EAL, "%s(): Locking file failed:%s \n",
481                                 __func__, strerror(errno));
482                         close(fd);
483                         return i;
484                 }
485
486                 close(fd);
487
488                 vma_addr = (char *)vma_addr + hugepage_sz;
489                 vma_len -= hugepage_sz;
490         }
491
492         return i;
493 }
494
495 /* Unmap all hugepages from original mapping */
496 static int
497 unmap_all_hugepages_orig(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
498 {
499         unsigned i;
500         for (i = 0; i < hpi->num_pages[0]; i++) {
501                 if (hugepg_tbl[i].orig_va) {
502                         munmap(hugepg_tbl[i].orig_va, hpi->hugepage_sz);
503                         hugepg_tbl[i].orig_va = NULL;
504                 }
505         }
506         return 0;
507 }
508
509 /*
510  * Parse /proc/self/numa_maps to get the NUMA socket ID for each huge
511  * page.
512  */
513 static int
514 find_numasocket(struct hugepage_file *hugepg_tbl, struct hugepage_info *hpi)
515 {
516         int socket_id;
517         char *end, *nodestr;
518         unsigned i, hp_count = 0;
519         uint64_t virt_addr;
520         char buf[BUFSIZ];
521         char hugedir_str[PATH_MAX];
522         FILE *f;
523
524         f = fopen("/proc/self/numa_maps", "r");
525         if (f == NULL) {
526                 RTE_LOG(NOTICE, EAL, "cannot open /proc/self/numa_maps,"
527                                 " consider that all memory is in socket_id 0\n");
528                 return 0;
529         }
530
531         snprintf(hugedir_str, sizeof(hugedir_str),
532                         "%s/%s", hpi->hugedir, internal_config.hugefile_prefix);
533
534         /* parse numa map */
535         while (fgets(buf, sizeof(buf), f) != NULL) {
536
537                 /* ignore non huge page */
538                 if (strstr(buf, " huge ") == NULL &&
539                                 strstr(buf, hugedir_str) == NULL)
540                         continue;
541
542                 /* get zone addr */
543                 virt_addr = strtoull(buf, &end, 16);
544                 if (virt_addr == 0 || end == buf) {
545                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
546                         goto error;
547                 }
548
549                 /* get node id (socket id) */
550                 nodestr = strstr(buf, " N");
551                 if (nodestr == NULL) {
552                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
553                         goto error;
554                 }
555                 nodestr += 2;
556                 end = strstr(nodestr, "=");
557                 if (end == NULL) {
558                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
559                         goto error;
560                 }
561                 end[0] = '\0';
562                 end = NULL;
563
564                 socket_id = strtoul(nodestr, &end, 0);
565                 if ((nodestr[0] == '\0') || (end == NULL) || (*end != '\0')) {
566                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
567                         goto error;
568                 }
569
570                 /* if we find this page in our mappings, set socket_id */
571                 for (i = 0; i < hpi->num_pages[0]; i++) {
572                         void *va = (void *)(unsigned long)virt_addr;
573                         if (hugepg_tbl[i].orig_va == va) {
574                                 hugepg_tbl[i].socket_id = socket_id;
575                                 hp_count++;
576                         }
577                 }
578         }
579
580         if (hp_count < hpi->num_pages[0])
581                 goto error;
582
583         fclose(f);
584         return 0;
585
586 error:
587         fclose(f);
588         return -1;
589 }
590
591 static int
592 cmp_physaddr(const void *a, const void *b)
593 {
594 #ifndef RTE_ARCH_PPC_64
595         const struct hugepage_file *p1 = (const struct hugepage_file *)a;
596         const struct hugepage_file *p2 = (const struct hugepage_file *)b;
597 #else
598         /* PowerPC needs memory sorted in reverse order from x86 */
599         const struct hugepage_file *p1 = (const struct hugepage_file *)b;
600         const struct hugepage_file *p2 = (const struct hugepage_file *)a;
601 #endif
602         if (p1->physaddr < p2->physaddr)
603                 return -1;
604         else if (p1->physaddr > p2->physaddr)
605                 return 1;
606         else
607                 return 0;
608 }
609
610 /*
611  * Uses mmap to create a shared memory area for storage of data
612  * Used in this file to store the hugepage file map on disk
613  */
614 static void *
615 create_shared_memory(const char *filename, const size_t mem_size)
616 {
617         void *retval;
618         int fd = open(filename, O_CREAT | O_RDWR, 0666);
619         if (fd < 0)
620                 return NULL;
621         if (ftruncate(fd, mem_size) < 0) {
622                 close(fd);
623                 return NULL;
624         }
625         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
626         close(fd);
627         return retval;
628 }
629
630 /*
631  * this copies *active* hugepages from one hugepage table to another.
632  * destination is typically the shared memory.
633  */
634 static int
635 copy_hugepages_to_shared_mem(struct hugepage_file * dst, int dest_size,
636                 const struct hugepage_file * src, int src_size)
637 {
638         int src_pos, dst_pos = 0;
639
640         for (src_pos = 0; src_pos < src_size; src_pos++) {
641                 if (src[src_pos].final_va != NULL) {
642                         /* error on overflow attempt */
643                         if (dst_pos == dest_size)
644                                 return -1;
645                         memcpy(&dst[dst_pos], &src[src_pos], sizeof(struct hugepage_file));
646                         dst_pos++;
647                 }
648         }
649         return 0;
650 }
651
652 static int
653 unlink_hugepage_files(struct hugepage_file *hugepg_tbl,
654                 unsigned num_hp_info)
655 {
656         unsigned socket, size;
657         int page, nrpages = 0;
658
659         /* get total number of hugepages */
660         for (size = 0; size < num_hp_info; size++)
661                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
662                         nrpages +=
663                         internal_config.hugepage_info[size].num_pages[socket];
664
665         for (page = 0; page < nrpages; page++) {
666                 struct hugepage_file *hp = &hugepg_tbl[page];
667
668                 if (hp->final_va != NULL && unlink(hp->filepath)) {
669                         RTE_LOG(WARNING, EAL, "%s(): Removing %s failed: %s\n",
670                                 __func__, hp->filepath, strerror(errno));
671                 }
672         }
673         return 0;
674 }
675
676 /*
677  * unmaps hugepages that are not going to be used. since we originally allocate
678  * ALL hugepages (not just those we need), additional unmapping needs to be done.
679  */
680 static int
681 unmap_unneeded_hugepages(struct hugepage_file *hugepg_tbl,
682                 struct hugepage_info *hpi,
683                 unsigned num_hp_info)
684 {
685         unsigned socket, size;
686         int page, nrpages = 0;
687
688         /* get total number of hugepages */
689         for (size = 0; size < num_hp_info; size++)
690                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
691                         nrpages += internal_config.hugepage_info[size].num_pages[socket];
692
693         for (size = 0; size < num_hp_info; size++) {
694                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++) {
695                         unsigned pages_found = 0;
696
697                         /* traverse until we have unmapped all the unused pages */
698                         for (page = 0; page < nrpages; page++) {
699                                 struct hugepage_file *hp = &hugepg_tbl[page];
700
701                                 /* find a page that matches the criteria */
702                                 if ((hp->size == hpi[size].hugepage_sz) &&
703                                                 (hp->socket_id == (int) socket)) {
704
705                                         /* if we skipped enough pages, unmap the rest */
706                                         if (pages_found == hpi[size].num_pages[socket]) {
707                                                 uint64_t unmap_len;
708
709                                                 unmap_len = hp->size;
710
711                                                 /* get start addr and len of the remaining segment */
712                                                 munmap(hp->final_va, (size_t) unmap_len);
713
714                                                 hp->final_va = NULL;
715                                                 if (unlink(hp->filepath) == -1) {
716                                                         RTE_LOG(ERR, EAL, "%s(): Removing %s failed: %s\n",
717                                                                         __func__, hp->filepath, strerror(errno));
718                                                         return -1;
719                                                 }
720                                         } else {
721                                                 /* lock the page and skip */
722                                                 pages_found++;
723                                         }
724
725                                 } /* match page */
726                         } /* foreach page */
727                 } /* foreach socket */
728         } /* foreach pagesize */
729
730         return 0;
731 }
732
733 static inline uint64_t
734 get_socket_mem_size(int socket)
735 {
736         uint64_t size = 0;
737         unsigned i;
738
739         for (i = 0; i < internal_config.num_hugepage_sizes; i++){
740                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
741                 if (hpi->hugedir != NULL)
742                         size += hpi->hugepage_sz * hpi->num_pages[socket];
743         }
744
745         return size;
746 }
747
748 /*
749  * This function is a NUMA-aware equivalent of calc_num_pages.
750  * It takes in the list of hugepage sizes and the
751  * number of pages thereof, and calculates the best number of
752  * pages of each size to fulfill the request for <memory> ram
753  */
754 static int
755 calc_num_pages_per_socket(uint64_t * memory,
756                 struct hugepage_info *hp_info,
757                 struct hugepage_info *hp_used,
758                 unsigned num_hp_info)
759 {
760         unsigned socket, j, i = 0;
761         unsigned requested, available;
762         int total_num_pages = 0;
763         uint64_t remaining_mem, cur_mem;
764         uint64_t total_mem = internal_config.memory;
765
766         if (num_hp_info == 0)
767                 return -1;
768
769         /* if specific memory amounts per socket weren't requested */
770         if (internal_config.force_sockets == 0) {
771                 int cpu_per_socket[RTE_MAX_NUMA_NODES];
772                 size_t default_size, total_size;
773                 unsigned lcore_id;
774
775                 /* Compute number of cores per socket */
776                 memset(cpu_per_socket, 0, sizeof(cpu_per_socket));
777                 RTE_LCORE_FOREACH(lcore_id) {
778                         cpu_per_socket[rte_lcore_to_socket_id(lcore_id)]++;
779                 }
780
781                 /*
782                  * Automatically spread requested memory amongst detected sockets according
783                  * to number of cores from cpu mask present on each socket
784                  */
785                 total_size = internal_config.memory;
786                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
787
788                         /* Set memory amount per socket */
789                         default_size = (internal_config.memory * cpu_per_socket[socket])
790                                         / rte_lcore_count();
791
792                         /* Limit to maximum available memory on socket */
793                         default_size = RTE_MIN(default_size, get_socket_mem_size(socket));
794
795                         /* Update sizes */
796                         memory[socket] = default_size;
797                         total_size -= default_size;
798                 }
799
800                 /*
801                  * If some memory is remaining, try to allocate it by getting all
802                  * available memory from sockets, one after the other
803                  */
804                 for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_size != 0; socket++) {
805                         /* take whatever is available */
806                         default_size = RTE_MIN(get_socket_mem_size(socket) - memory[socket],
807                                                total_size);
808
809                         /* Update sizes */
810                         memory[socket] += default_size;
811                         total_size -= default_size;
812                 }
813         }
814
815         for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_mem != 0; socket++) {
816                 /* skips if the memory on specific socket wasn't requested */
817                 for (i = 0; i < num_hp_info && memory[socket] != 0; i++){
818                         hp_used[i].hugedir = hp_info[i].hugedir;
819                         hp_used[i].num_pages[socket] = RTE_MIN(
820                                         memory[socket] / hp_info[i].hugepage_sz,
821                                         hp_info[i].num_pages[socket]);
822
823                         cur_mem = hp_used[i].num_pages[socket] *
824                                         hp_used[i].hugepage_sz;
825
826                         memory[socket] -= cur_mem;
827                         total_mem -= cur_mem;
828
829                         total_num_pages += hp_used[i].num_pages[socket];
830
831                         /* check if we have met all memory requests */
832                         if (memory[socket] == 0)
833                                 break;
834
835                         /* check if we have any more pages left at this size, if so
836                          * move on to next size */
837                         if (hp_used[i].num_pages[socket] == hp_info[i].num_pages[socket])
838                                 continue;
839                         /* At this point we know that there are more pages available that are
840                          * bigger than the memory we want, so lets see if we can get enough
841                          * from other page sizes.
842                          */
843                         remaining_mem = 0;
844                         for (j = i+1; j < num_hp_info; j++)
845                                 remaining_mem += hp_info[j].hugepage_sz *
846                                 hp_info[j].num_pages[socket];
847
848                         /* is there enough other memory, if not allocate another page and quit */
849                         if (remaining_mem < memory[socket]){
850                                 cur_mem = RTE_MIN(memory[socket],
851                                                 hp_info[i].hugepage_sz);
852                                 memory[socket] -= cur_mem;
853                                 total_mem -= cur_mem;
854                                 hp_used[i].num_pages[socket]++;
855                                 total_num_pages++;
856                                 break; /* we are done with this socket*/
857                         }
858                 }
859                 /* if we didn't satisfy all memory requirements per socket */
860                 if (memory[socket] > 0) {
861                         /* to prevent icc errors */
862                         requested = (unsigned) (internal_config.socket_mem[socket] /
863                                         0x100000);
864                         available = requested -
865                                         ((unsigned) (memory[socket] / 0x100000));
866                         RTE_LOG(ERR, EAL, "Not enough memory available on socket %u! "
867                                         "Requested: %uMB, available: %uMB\n", socket,
868                                         requested, available);
869                         return -1;
870                 }
871         }
872
873         /* if we didn't satisfy total memory requirements */
874         if (total_mem > 0) {
875                 requested = (unsigned) (internal_config.memory / 0x100000);
876                 available = requested - (unsigned) (total_mem / 0x100000);
877                 RTE_LOG(ERR, EAL, "Not enough memory available! Requested: %uMB,"
878                                 " available: %uMB\n", requested, available);
879                 return -1;
880         }
881         return total_num_pages;
882 }
883
884 static inline size_t
885 eal_get_hugepage_mem_size(void)
886 {
887         uint64_t size = 0;
888         unsigned i, j;
889
890         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
891                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
892                 if (hpi->hugedir != NULL) {
893                         for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
894                                 size += hpi->hugepage_sz * hpi->num_pages[j];
895                         }
896                 }
897         }
898
899         return (size < SIZE_MAX) ? (size_t)(size) : SIZE_MAX;
900 }
901
902 static struct sigaction huge_action_old;
903 static int huge_need_recover;
904
905 static void
906 huge_register_sigbus(void)
907 {
908         sigset_t mask;
909         struct sigaction action;
910
911         sigemptyset(&mask);
912         sigaddset(&mask, SIGBUS);
913         action.sa_flags = 0;
914         action.sa_mask = mask;
915         action.sa_handler = huge_sigbus_handler;
916
917         huge_need_recover = !sigaction(SIGBUS, &action, &huge_action_old);
918 }
919
920 static void
921 huge_recover_sigbus(void)
922 {
923         if (huge_need_recover) {
924                 sigaction(SIGBUS, &huge_action_old, NULL);
925                 huge_need_recover = 0;
926         }
927 }
928
929 /*
930  * Prepare physical memory mapping: fill configuration structure with
931  * these infos, return 0 on success.
932  *  1. map N huge pages in separate files in hugetlbfs
933  *  2. find associated physical addr
934  *  3. find associated NUMA socket ID
935  *  4. sort all huge pages by physical address
936  *  5. remap these N huge pages in the correct order
937  *  6. unmap the first mapping
938  *  7. fill memsegs in configuration with contiguous zones
939  */
940 int
941 rte_eal_hugepage_init(void)
942 {
943         struct rte_mem_config *mcfg;
944         struct hugepage_file *hugepage = NULL, *tmp_hp = NULL;
945         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
946
947         uint64_t memory[RTE_MAX_NUMA_NODES];
948
949         unsigned hp_offset;
950         int i, j, new_memseg;
951         int nr_hugefiles, nr_hugepages = 0;
952         void *addr;
953
954         test_proc_pagemap_readable();
955
956         memset(used_hp, 0, sizeof(used_hp));
957
958         /* get pointer to global configuration */
959         mcfg = rte_eal_get_configuration()->mem_config;
960
961         /* hugetlbfs can be disabled */
962         if (internal_config.no_hugetlbfs) {
963                 addr = mmap(NULL, internal_config.memory, PROT_READ | PROT_WRITE,
964                                 MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
965                 if (addr == MAP_FAILED) {
966                         RTE_LOG(ERR, EAL, "%s: mmap() failed: %s\n", __func__,
967                                         strerror(errno));
968                         return -1;
969                 }
970                 mcfg->memseg[0].phys_addr = (phys_addr_t)(uintptr_t)addr;
971                 mcfg->memseg[0].addr = addr;
972                 mcfg->memseg[0].hugepage_sz = RTE_PGSIZE_4K;
973                 mcfg->memseg[0].len = internal_config.memory;
974                 mcfg->memseg[0].socket_id = 0;
975                 return 0;
976         }
977
978 /* check if app runs on Xen Dom0 */
979         if (internal_config.xen_dom0_support) {
980 #ifdef RTE_LIBRTE_XEN_DOM0
981                 /* use dom0_mm kernel driver to init memory */
982                 if (rte_xen_dom0_memory_init() < 0)
983                         return -1;
984                 else
985                         return 0;
986 #endif
987         }
988
989         /* calculate total number of hugepages available. at this point we haven't
990          * yet started sorting them so they all are on socket 0 */
991         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
992                 /* meanwhile, also initialize used_hp hugepage sizes in used_hp */
993                 used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;
994
995                 nr_hugepages += internal_config.hugepage_info[i].num_pages[0];
996         }
997
998         /*
999          * allocate a memory area for hugepage table.
1000          * this isn't shared memory yet. due to the fact that we need some
1001          * processing done on these pages, shared memory will be created
1002          * at a later stage.
1003          */
1004         tmp_hp = malloc(nr_hugepages * sizeof(struct hugepage_file));
1005         if (tmp_hp == NULL)
1006                 goto fail;
1007
1008         memset(tmp_hp, 0, nr_hugepages * sizeof(struct hugepage_file));
1009
1010         hp_offset = 0; /* where we start the current page size entries */
1011
1012         huge_register_sigbus();
1013
1014         /* map all hugepages and sort them */
1015         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
1016                 unsigned pages_old, pages_new;
1017                 struct hugepage_info *hpi;
1018
1019                 /*
1020                  * we don't yet mark hugepages as used at this stage, so
1021                  * we just map all hugepages available to the system
1022                  * all hugepages are still located on socket 0
1023                  */
1024                 hpi = &internal_config.hugepage_info[i];
1025
1026                 if (hpi->num_pages[0] == 0)
1027                         continue;
1028
1029                 /* map all hugepages available */
1030                 pages_old = hpi->num_pages[0];
1031                 pages_new = map_all_hugepages(&tmp_hp[hp_offset], hpi, 1);
1032                 if (pages_new < pages_old) {
1033                         RTE_LOG(DEBUG, EAL,
1034                                 "%d not %d hugepages of size %u MB allocated\n",
1035                                 pages_new, pages_old,
1036                                 (unsigned)(hpi->hugepage_sz / 0x100000));
1037
1038                         int pages = pages_old - pages_new;
1039
1040                         nr_hugepages -= pages;
1041                         hpi->num_pages[0] = pages_new;
1042                         if (pages_new == 0)
1043                                 continue;
1044                 }
1045
1046                 /* find physical addresses and sockets for each hugepage */
1047                 if (find_physaddrs(&tmp_hp[hp_offset], hpi) < 0){
1048                         RTE_LOG(DEBUG, EAL, "Failed to find phys addr for %u MB pages\n",
1049                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1050                         goto fail;
1051                 }
1052
1053                 if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
1054                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
1055                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1056                         goto fail;
1057                 }
1058
1059                 qsort(&tmp_hp[hp_offset], hpi->num_pages[0],
1060                       sizeof(struct hugepage_file), cmp_physaddr);
1061
1062                 /* remap all hugepages */
1063                 if (map_all_hugepages(&tmp_hp[hp_offset], hpi, 0) !=
1064                     hpi->num_pages[0]) {
1065                         RTE_LOG(ERR, EAL, "Failed to remap %u MB pages\n",
1066                                         (unsigned)(hpi->hugepage_sz / 0x100000));
1067                         goto fail;
1068                 }
1069
1070                 /* unmap original mappings */
1071                 if (unmap_all_hugepages_orig(&tmp_hp[hp_offset], hpi) < 0)
1072                         goto fail;
1073
1074                 /* we have processed a num of hugepages of this size, so inc offset */
1075                 hp_offset += hpi->num_pages[0];
1076         }
1077
1078         huge_recover_sigbus();
1079
1080         if (internal_config.memory == 0 && internal_config.force_sockets == 0)
1081                 internal_config.memory = eal_get_hugepage_mem_size();
1082
1083         nr_hugefiles = nr_hugepages;
1084
1085
1086         /* clean out the numbers of pages */
1087         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
1088                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
1089                         internal_config.hugepage_info[i].num_pages[j] = 0;
1090
1091         /* get hugepages for each socket */
1092         for (i = 0; i < nr_hugefiles; i++) {
1093                 int socket = tmp_hp[i].socket_id;
1094
1095                 /* find a hugepage info with right size and increment num_pages */
1096                 const int nb_hpsizes = RTE_MIN(MAX_HUGEPAGE_SIZES,
1097                                 (int)internal_config.num_hugepage_sizes);
1098                 for (j = 0; j < nb_hpsizes; j++) {
1099                         if (tmp_hp[i].size ==
1100                                         internal_config.hugepage_info[j].hugepage_sz) {
1101                                 internal_config.hugepage_info[j].num_pages[socket]++;
1102                         }
1103                 }
1104         }
1105
1106         /* make a copy of socket_mem, needed for number of pages calculation */
1107         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
1108                 memory[i] = internal_config.socket_mem[i];
1109
1110         /* calculate final number of pages */
1111         nr_hugepages = calc_num_pages_per_socket(memory,
1112                         internal_config.hugepage_info, used_hp,
1113                         internal_config.num_hugepage_sizes);
1114
1115         /* error if not enough memory available */
1116         if (nr_hugepages < 0)
1117                 goto fail;
1118
1119         /* reporting in! */
1120         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
1121                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
1122                         if (used_hp[i].num_pages[j] > 0) {
1123                                 RTE_LOG(DEBUG, EAL,
1124                                         "Requesting %u pages of size %uMB"
1125                                         " from socket %i\n",
1126                                         used_hp[i].num_pages[j],
1127                                         (unsigned)
1128                                         (used_hp[i].hugepage_sz / 0x100000),
1129                                         j);
1130                         }
1131                 }
1132         }
1133
1134         /* create shared memory */
1135         hugepage = create_shared_memory(eal_hugepage_info_path(),
1136                         nr_hugefiles * sizeof(struct hugepage_file));
1137
1138         if (hugepage == NULL) {
1139                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
1140                 goto fail;
1141         }
1142         memset(hugepage, 0, nr_hugefiles * sizeof(struct hugepage_file));
1143
1144         /*
1145          * unmap pages that we won't need (looks at used_hp).
1146          * also, sets final_va to NULL on pages that were unmapped.
1147          */
1148         if (unmap_unneeded_hugepages(tmp_hp, used_hp,
1149                         internal_config.num_hugepage_sizes) < 0) {
1150                 RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
1151                 goto fail;
1152         }
1153
1154         /*
1155          * copy stuff from malloc'd hugepage* to the actual shared memory.
1156          * this procedure only copies those hugepages that have final_va
1157          * not NULL. has overflow protection.
1158          */
1159         if (copy_hugepages_to_shared_mem(hugepage, nr_hugefiles,
1160                         tmp_hp, nr_hugefiles) < 0) {
1161                 RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
1162                 goto fail;
1163         }
1164
1165         /* free the hugepage backing files */
1166         if (internal_config.hugepage_unlink &&
1167                 unlink_hugepage_files(tmp_hp, internal_config.num_hugepage_sizes) < 0) {
1168                 RTE_LOG(ERR, EAL, "Unlinking hugepage files failed!\n");
1169                 goto fail;
1170         }
1171
1172         /* free the temporary hugepage table */
1173         free(tmp_hp);
1174         tmp_hp = NULL;
1175
1176         /* first memseg index shall be 0 after incrementing it below */
1177         j = -1;
1178         for (i = 0; i < nr_hugefiles; i++) {
1179                 new_memseg = 0;
1180
1181                 /* if this is a new section, create a new memseg */
1182                 if (i == 0)
1183                         new_memseg = 1;
1184                 else if (hugepage[i].socket_id != hugepage[i-1].socket_id)
1185                         new_memseg = 1;
1186                 else if (hugepage[i].size != hugepage[i-1].size)
1187                         new_memseg = 1;
1188
1189 #ifdef RTE_ARCH_PPC_64
1190                 /* On PPC64 architecture, the mmap always start from higher
1191                  * virtual address to lower address. Here, both the physical
1192                  * address and virtual address are in descending order */
1193                 else if ((hugepage[i-1].physaddr - hugepage[i].physaddr) !=
1194                     hugepage[i].size)
1195                         new_memseg = 1;
1196                 else if (((unsigned long)hugepage[i-1].final_va -
1197                     (unsigned long)hugepage[i].final_va) != hugepage[i].size)
1198                         new_memseg = 1;
1199 #else
1200                 else if ((hugepage[i].physaddr - hugepage[i-1].physaddr) !=
1201                     hugepage[i].size)
1202                         new_memseg = 1;
1203                 else if (((unsigned long)hugepage[i].final_va -
1204                     (unsigned long)hugepage[i-1].final_va) != hugepage[i].size)
1205                         new_memseg = 1;
1206 #endif
1207
1208                 if (new_memseg) {
1209                         j += 1;
1210                         if (j == RTE_MAX_MEMSEG)
1211                                 break;
1212
1213                         mcfg->memseg[j].phys_addr = hugepage[i].physaddr;
1214                         mcfg->memseg[j].addr = hugepage[i].final_va;
1215                         mcfg->memseg[j].len = hugepage[i].size;
1216                         mcfg->memseg[j].socket_id = hugepage[i].socket_id;
1217                         mcfg->memseg[j].hugepage_sz = hugepage[i].size;
1218                 }
1219                 /* continuation of previous memseg */
1220                 else {
1221 #ifdef RTE_ARCH_PPC_64
1222                 /* Use the phy and virt address of the last page as segment
1223                  * address for IBM Power architecture */
1224                         mcfg->memseg[j].phys_addr = hugepage[i].physaddr;
1225                         mcfg->memseg[j].addr = hugepage[i].final_va;
1226 #endif
1227                         mcfg->memseg[j].len += mcfg->memseg[j].hugepage_sz;
1228                 }
1229                 hugepage[i].memseg_id = j;
1230         }
1231
1232         if (i < nr_hugefiles) {
1233                 RTE_LOG(ERR, EAL, "Can only reserve %d pages "
1234                         "from %d requested\n"
1235                         "Current %s=%d is not enough\n"
1236                         "Please either increase it or request less amount "
1237                         "of memory.\n",
1238                         i, nr_hugefiles, RTE_STR(CONFIG_RTE_MAX_MEMSEG),
1239                         RTE_MAX_MEMSEG);
1240                 goto fail;
1241         }
1242
1243         munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1244
1245         return 0;
1246
1247 fail:
1248         huge_recover_sigbus();
1249         free(tmp_hp);
1250         if (hugepage != NULL)
1251                 munmap(hugepage, nr_hugefiles * sizeof(struct hugepage_file));
1252
1253         return -1;
1254 }
1255
1256 /*
1257  * uses fstat to report the size of a file on disk
1258  */
1259 static off_t
1260 getFileSize(int fd)
1261 {
1262         struct stat st;
1263         if (fstat(fd, &st) < 0)
1264                 return 0;
1265         return st.st_size;
1266 }
1267
1268 /*
1269  * This creates the memory mappings in the secondary process to match that of
1270  * the server process. It goes through each memory segment in the DPDK runtime
1271  * configuration and finds the hugepages which form that segment, mapping them
1272  * in order to form a contiguous block in the virtual memory space
1273  */
1274 int
1275 rte_eal_hugepage_attach(void)
1276 {
1277         const struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1278         struct hugepage_file *hp = NULL;
1279         unsigned num_hp = 0;
1280         unsigned i, s = 0; /* s used to track the segment number */
1281         unsigned max_seg = RTE_MAX_MEMSEG;
1282         off_t size = 0;
1283         int fd, fd_zero = -1, fd_hugepage = -1;
1284
1285         if (aslr_enabled() > 0) {
1286                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
1287                                 "(ASLR) is enabled in the kernel.\n");
1288                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
1289                                 "into secondary processes\n");
1290         }
1291
1292         test_proc_pagemap_readable();
1293
1294         if (internal_config.xen_dom0_support) {
1295 #ifdef RTE_LIBRTE_XEN_DOM0
1296                 if (rte_xen_dom0_memory_attach() < 0) {
1297                         RTE_LOG(ERR, EAL, "Failed to attach memory segments of primary "
1298                                         "process\n");
1299                         return -1;
1300                 }
1301                 return 0;
1302 #endif
1303         }
1304
1305         fd_zero = open("/dev/zero", O_RDONLY);
1306         if (fd_zero < 0) {
1307                 RTE_LOG(ERR, EAL, "Could not open /dev/zero\n");
1308                 goto error;
1309         }
1310         fd_hugepage = open(eal_hugepage_info_path(), O_RDONLY);
1311         if (fd_hugepage < 0) {
1312                 RTE_LOG(ERR, EAL, "Could not open %s\n", eal_hugepage_info_path());
1313                 goto error;
1314         }
1315
1316         /* map all segments into memory to make sure we get the addrs */
1317         for (s = 0; s < RTE_MAX_MEMSEG; ++s) {
1318                 void *base_addr;
1319
1320                 /*
1321                  * the first memory segment with len==0 is the one that
1322                  * follows the last valid segment.
1323                  */
1324                 if (mcfg->memseg[s].len == 0)
1325                         break;
1326
1327                 /*
1328                  * fdzero is mmapped to get a contiguous block of virtual
1329                  * addresses of the appropriate memseg size.
1330                  * use mmap to get identical addresses as the primary process.
1331                  */
1332                 base_addr = mmap(mcfg->memseg[s].addr, mcfg->memseg[s].len,
1333                                  PROT_READ, MAP_PRIVATE, fd_zero, 0);
1334                 if (base_addr == MAP_FAILED ||
1335                     base_addr != mcfg->memseg[s].addr) {
1336                         max_seg = s;
1337                         if (base_addr != MAP_FAILED) {
1338                                 /* errno is stale, don't use */
1339                                 RTE_LOG(ERR, EAL, "Could not mmap %llu bytes "
1340                                         "in /dev/zero at [%p], got [%p] - "
1341                                         "please use '--base-virtaddr' option\n",
1342                                         (unsigned long long)mcfg->memseg[s].len,
1343                                         mcfg->memseg[s].addr, base_addr);
1344                                 munmap(base_addr, mcfg->memseg[s].len);
1345                         } else {
1346                                 RTE_LOG(ERR, EAL, "Could not mmap %llu bytes "
1347                                         "in /dev/zero at [%p]: '%s'\n",
1348                                         (unsigned long long)mcfg->memseg[s].len,
1349                                         mcfg->memseg[s].addr, strerror(errno));
1350                         }
1351                         if (aslr_enabled() > 0) {
1352                                 RTE_LOG(ERR, EAL, "It is recommended to "
1353                                         "disable ASLR in the kernel "
1354                                         "and retry running both primary "
1355                                         "and secondary processes\n");
1356                         }
1357                         goto error;
1358                 }
1359         }
1360
1361         size = getFileSize(fd_hugepage);
1362         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
1363         if (hp == MAP_FAILED) {
1364                 RTE_LOG(ERR, EAL, "Could not mmap %s\n", eal_hugepage_info_path());
1365                 goto error;
1366         }
1367
1368         num_hp = size / sizeof(struct hugepage_file);
1369         RTE_LOG(DEBUG, EAL, "Analysing %u files\n", num_hp);
1370
1371         s = 0;
1372         while (s < RTE_MAX_MEMSEG && mcfg->memseg[s].len > 0){
1373                 void *addr, *base_addr;
1374                 uintptr_t offset = 0;
1375                 size_t mapping_size;
1376                 /*
1377                  * free previously mapped memory so we can map the
1378                  * hugepages into the space
1379                  */
1380                 base_addr = mcfg->memseg[s].addr;
1381                 munmap(base_addr, mcfg->memseg[s].len);
1382
1383                 /* find the hugepages for this segment and map them
1384                  * we don't need to worry about order, as the server sorted the
1385                  * entries before it did the second mmap of them */
1386                 for (i = 0; i < num_hp && offset < mcfg->memseg[s].len; i++){
1387                         if (hp[i].memseg_id == (int)s){
1388                                 fd = open(hp[i].filepath, O_RDWR);
1389                                 if (fd < 0) {
1390                                         RTE_LOG(ERR, EAL, "Could not open %s\n",
1391                                                 hp[i].filepath);
1392                                         goto error;
1393                                 }
1394                                 mapping_size = hp[i].size;
1395                                 addr = mmap(RTE_PTR_ADD(base_addr, offset),
1396                                                 mapping_size, PROT_READ | PROT_WRITE,
1397                                                 MAP_SHARED, fd, 0);
1398                                 close(fd); /* close file both on success and on failure */
1399                                 if (addr == MAP_FAILED ||
1400                                                 addr != RTE_PTR_ADD(base_addr, offset)) {
1401                                         RTE_LOG(ERR, EAL, "Could not mmap %s\n",
1402                                                 hp[i].filepath);
1403                                         goto error;
1404                                 }
1405                                 offset+=mapping_size;
1406                         }
1407                 }
1408                 RTE_LOG(DEBUG, EAL, "Mapped segment %u of size 0x%llx\n", s,
1409                                 (unsigned long long)mcfg->memseg[s].len);
1410                 s++;
1411         }
1412         /* unmap the hugepage config file, since we are done using it */
1413         munmap(hp, size);
1414         close(fd_zero);
1415         close(fd_hugepage);
1416         return 0;
1417
1418 error:
1419         for (i = 0; i < max_seg && mcfg->memseg[i].len > 0; i++)
1420                 munmap(mcfg->memseg[i].addr, mcfg->memseg[i].len);
1421         if (hp != NULL && hp != MAP_FAILED)
1422                 munmap(hp, size);
1423         if (fd_zero >= 0)
1424                 close(fd_zero);
1425         if (fd_hugepage >= 0)
1426                 close(fd_hugepage);
1427         return -1;
1428 }