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