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