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