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