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