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