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