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