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