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