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