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