remove version in all files
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_memory.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2012 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  */
34
35 #include <errno.h>
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <stdint.h>
40 #include <inttypes.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <sys/mman.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/queue.h>
47 #include <fcntl.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <errno.h>
51 #include <sys/ioctl.h>
52
53 #include <rte_log.h>
54 #include <rte_memory.h>
55 #include <rte_memzone.h>
56 #include <rte_launch.h>
57 #include <rte_tailq.h>
58 #include <rte_eal.h>
59 #include <rte_per_lcore.h>
60 #include <rte_lcore.h>
61 #include <rte_common.h>
62 #include <rte_string_fns.h>
63
64 #include "eal_private.h"
65 #include "eal_internal_cfg.h"
66 #include "eal_fs_paths.h"
67 #include "eal_hugepages.h"
68
69 /**
70  * @file
71  * Huge page mapping under linux
72  *
73  * To reserve a big contiguous amount of memory, we use the hugepage
74  * feature of linux. For that, we need to have hugetlbfs mounted. This
75  * code will create many files in this directory (one per page) and
76  * map them in virtual memory. For each page, we will retrieve its
77  * physical address and remap it in order to have a virtual contiguous
78  * zone as well as a physical contiguous zone.
79  */
80
81
82 #define RANDOMIZE_VA_SPACE_FILE "/proc/sys/kernel/randomize_va_space"
83
84 /*
85  * Check whether address-space layout randomization is enabled in
86  * the kernel. This is important for multi-process as it can prevent
87  * two processes mapping data to the same virtual address
88  * Returns:
89  *    0 - address space randomization disabled
90  *    1/2 - address space randomization enabled
91  *    negative error code on error
92  */
93 static int
94 aslr_enabled(void)
95 {
96         char c;
97         int retval, fd = open(RANDOMIZE_VA_SPACE_FILE, O_RDONLY);
98         if (fd < 0)
99                 return -errno;
100         retval = read(fd, &c, 1);
101         close(fd);
102         if (retval < 0)
103                 return -errno;
104         if (retval == 0)
105                 return -EIO;
106         switch (c) {
107                 case '0' : return 0;
108                 case '1' : return 1;
109                 case '2' : return 2;
110                 default: return -EINVAL;
111         }
112 }
113
114 /*
115  * Try to mmap *size bytes in /dev/zero. If it is succesful, return the
116  * pointer to the mmap'd area and keep *size unmodified. Else, retry
117  * with a smaller zone: decrease *size by hugepage_sz until it reaches
118  * 0. In this case, return NULL. Note: this function returns an address
119  * which is a multiple of hugepage size.
120  */
121 static void *
122 get_virtual_area(uint64_t *size, uint64_t hugepage_sz)
123 {
124         void *addr;
125         int fd;
126         long aligned_addr;
127
128         RTE_LOG(INFO, EAL, "Ask a virtual area of 0x%"PRIx64" bytes\n", *size);
129
130         fd = open("/dev/zero", O_RDONLY);
131         if (fd < 0){
132                 RTE_LOG(ERR, EAL, "Cannot open /dev/zero\n");
133                 return NULL;
134         }
135         do {
136                 addr = mmap(NULL, (*size) + hugepage_sz, PROT_READ, MAP_PRIVATE, fd, 0);
137                 if (addr == MAP_FAILED)
138                         *size -= hugepage_sz;
139         } while (addr == MAP_FAILED && *size > 0);
140
141         if (addr == MAP_FAILED) {
142                 close(fd);
143                 RTE_LOG(INFO, EAL, "Cannot get a virtual area\n");
144                 return NULL;
145         }
146
147         munmap(addr, (*size) + hugepage_sz);
148         close(fd);
149
150         /* align addr to a huge page size boundary */
151         aligned_addr = (long)addr;
152         aligned_addr += (hugepage_sz - 1);
153         aligned_addr &= (~(hugepage_sz - 1));
154         addr = (void *)(aligned_addr);
155
156         RTE_LOG(INFO, EAL, "Virtual area found at %p (size = 0x%"PRIx64")\n",
157                 addr, *size);
158
159         return addr;
160 }
161
162 /*
163  * Mmap all hugepages of hugepage table: it first open a file in
164  * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
165  * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
166  * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
167  * map continguous physical blocks in contiguous virtual blocks.
168  */
169 static int
170 map_all_hugepages(struct hugepage *hugepg_tbl,
171                 struct hugepage_info *hpi, int orig)
172 {
173         int fd;
174         unsigned i;
175         void *virtaddr;
176         void *vma_addr = NULL;
177         uint64_t vma_len = 0;
178
179         for (i = 0; i < hpi->num_pages; i++) {
180                 uint64_t hugepage_sz = hpi->hugepage_sz;
181
182                 if (orig) {
183                         hugepg_tbl[i].file_id = i;
184                         hugepg_tbl[i].size = hugepage_sz;
185                         eal_get_hugefile_path(hugepg_tbl[i].filepath,
186                                         sizeof(hugepg_tbl[i].filepath), hpi->hugedir,
187                                         hugepg_tbl[i].file_id);
188                         hugepg_tbl[i].filepath[sizeof(hugepg_tbl[i].filepath) - 1] = '\0';
189                 }
190 #ifndef RTE_ARCH_X86_64
191                 /* for 32-bit systems, don't remap 1G pages, just reuse original
192                  * map address as final map address.
193                  */
194                 else if (hugepage_sz == RTE_PGSIZE_1G){
195                         hugepg_tbl[i].final_va = hugepg_tbl[i].orig_va;
196                         hugepg_tbl[i].orig_va = NULL;
197                         continue;
198                 }
199 #endif
200                 else if (vma_len == 0) {
201                         unsigned j, num_pages;
202
203                         /* reserve a virtual area for next contiguous
204                          * physical block: count the number of
205                          * contiguous physical pages. */
206                         for (j = i+1; j < hpi->num_pages ; j++) {
207                                 if (hugepg_tbl[j].physaddr !=
208                                     hugepg_tbl[j-1].physaddr + hugepage_sz)
209                                         break;
210                         }
211                         num_pages = j - i;
212                         vma_len = num_pages * hugepage_sz;
213
214                         /* get the biggest virtual memory area up to
215                          * vma_len. If it fails, vma_addr is NULL, so
216                          * let the kernel provide the address. */
217                         vma_addr = get_virtual_area(&vma_len, hpi->hugepage_sz);
218                         if (vma_addr == NULL)
219                                 vma_len = hugepage_sz;
220                 }
221
222                 fd = open(hugepg_tbl[i].filepath, O_CREAT | O_RDWR, 0755);
223                 if (fd < 0) {
224                         RTE_LOG(ERR, EAL, "%s(): open failed: %s", __func__,
225                                         strerror(errno));
226                         return -1;
227                 }
228
229                 virtaddr = mmap(vma_addr, hugepage_sz, PROT_READ | PROT_WRITE,
230                                 MAP_SHARED, fd, 0);
231                 if (virtaddr == MAP_FAILED) {
232                         RTE_LOG(ERR, EAL, "%s(): mmap failed: %s", __func__,
233                                         strerror(errno));
234                         close(fd);
235                         return -1;
236                 }
237                 if (orig) {
238                         hugepg_tbl[i].orig_va = virtaddr;
239                         memset(virtaddr, 0, hugepage_sz);
240                 }
241                 else {
242                         hugepg_tbl[i].final_va = virtaddr;
243                 }
244
245                 vma_addr = (char *)vma_addr + hugepage_sz;
246                 vma_len -= hugepage_sz;
247                 close(fd);
248         }
249         return 0;
250 }
251
252 /* Unmap all hugepages from original mapping. */
253 static int
254 unmap_all_hugepages_orig(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
255 {
256         unsigned i;
257         for (i = 0; i < hpi->num_pages; i++) {
258                 if (hugepg_tbl[i].orig_va) {
259                         munmap(hugepg_tbl[i].orig_va, hpi->hugepage_sz);
260                         hugepg_tbl[i].orig_va = NULL;
261                 }
262         }
263         return 0;
264 }
265
266 /*
267  * For each hugepage in hugepg_tbl, fill the physaddr value. We find
268  * it by browsing the /proc/self/pagemap special file.
269  */
270 static int
271 find_physaddr(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
272 {
273         int fd;
274         unsigned i;
275         uint64_t page;
276         unsigned long virt_pfn;
277         int page_size;
278
279         /* standard page size */
280         page_size = getpagesize();
281
282         fd = open("/proc/self/pagemap", O_RDONLY);
283         if (fd < 0) {
284                 RTE_LOG(ERR, EAL, "%s(): cannot open /proc/self/pagemap: %s",
285                         __func__, strerror(errno));
286                 return -1;
287         }
288
289         for (i = 0; i < hpi->num_pages; i++) {
290                 off_t offset;
291                 virt_pfn = (unsigned long)hugepg_tbl[i].orig_va /
292                         page_size;
293                 offset = sizeof(uint64_t) * virt_pfn;
294                 if (lseek(fd, offset, SEEK_SET) != offset){
295                         RTE_LOG(ERR, EAL, "%s(): seek error in /proc/self/pagemap: %s",
296                                         __func__, strerror(errno));
297                         close(fd);
298                         return -1;
299                 }
300                 if (read(fd, &page, sizeof(uint64_t)) < 0) {
301                         RTE_LOG(ERR, EAL, "%s(): cannot read /proc/self/pagemap: %s",
302                                         __func__, strerror(errno));
303                         close(fd);
304                         return -1;
305                 }
306
307                 /*
308                  * the pfn (page frame number) are bits 0-54 (see
309                  * pagemap.txt in linux Documentation)
310                  */
311                 hugepg_tbl[i].physaddr = ((page & 0x7fffffffffffffULL) * page_size);
312         }
313         close(fd);
314         return 0;
315 }
316
317 /*
318  * Parse /proc/self/numa_maps to get the NUMA socket ID for each huge
319  * page.
320  */
321 static int
322 find_numasocket(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
323 {
324         int socket_id;
325         char *end, *nodestr;
326         unsigned i, hp_count = 0;
327         uint64_t virt_addr;
328         char buf[BUFSIZ];
329         char hugedir_str[PATH_MAX];
330         FILE *f;
331
332         f = fopen("/proc/self/numa_maps", "r");
333         if (f == NULL) {
334                 RTE_LOG(INFO, EAL, "cannot open /proc/self/numa_maps,"
335                                 "consider that all memory is in socket_id 0");
336                 return 0;
337         }
338
339         rte_snprintf(hugedir_str, sizeof(hugedir_str),
340                         "%s/", hpi->hugedir);
341
342         /* parse numa map */
343         while (fgets(buf, sizeof(buf), f) != NULL) {
344
345                 /* ignore non huge page */
346                 if (strstr(buf, " huge ") == NULL &&
347                                 strstr(buf, hugedir_str) == NULL)
348                         continue;
349
350                 /* get zone addr */
351                 virt_addr = strtoull(buf, &end, 16);
352                 if (virt_addr == 0 || end == buf) {
353                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
354                         goto error;
355                 }
356
357                 /* get node id (socket id) */
358                 nodestr = strstr(buf, " N");
359                 if (nodestr == NULL) {
360                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
361                         goto error;
362                 }
363                 nodestr += 2;
364                 end = strstr(nodestr, "=");
365                 if (end == NULL) {
366                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
367                         goto error;
368                 }
369                 end[0] = '\0';
370                 end = NULL;
371
372                 socket_id = strtoul(nodestr, &end, 0);
373                 if ((nodestr[0] == '\0') || (end == NULL) || (*end != '\0')) {
374                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
375                         goto error;
376                 }
377
378                 /* if we find this page in our mappings, set socket_id */
379                 for (i = 0; i < hpi->num_pages; i++) {
380                         void *va = (void *)(unsigned long)virt_addr;
381                         if (hugepg_tbl[i].orig_va == va) {
382                                 hugepg_tbl[i].socket_id = socket_id;
383                                 hp_count++;
384                         }
385                 }
386         }
387         if (hp_count < hpi->num_pages)
388                 goto error;
389         fclose(f);
390         return 0;
391
392 error:
393         fclose(f);
394         return -1;
395 }
396
397 /*
398  * Sort the hugepg_tbl by physical address (lower addresses first). We
399  * use a slow algorithm, but we won't have millions of pages, and this
400  * is only done at init time.
401  */
402 static int
403 sort_by_physaddr(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
404 {
405         unsigned i, j;
406         int smallest_idx;
407         uint64_t smallest_addr;
408         struct hugepage tmp;
409
410         for (i = 0; i < hpi->num_pages; i++) {
411                 smallest_addr = 0;
412                 smallest_idx = -1;
413
414                 /*
415                  * browse all entries starting at 'i', and find the
416                  * entry with the smallest addr
417                  */
418                 for (j=i; j<hpi->num_pages; j++) {
419
420                         if (smallest_addr == 0 ||
421                             hugepg_tbl[j].physaddr < smallest_addr) {
422                                 smallest_addr = hugepg_tbl[j].physaddr;
423                                 smallest_idx = j;
424                         }
425                 }
426
427                 /* should not happen */
428                 if (smallest_idx == -1) {
429                         RTE_LOG(ERR, EAL, "%s(): error in physaddr sorting\n", __func__);
430                         return -1;
431                 }
432
433                 /* swap the 2 entries in the table */
434                 memcpy(&tmp, &hugepg_tbl[smallest_idx], sizeof(struct hugepage));
435                 memcpy(&hugepg_tbl[smallest_idx], &hugepg_tbl[i],
436                                 sizeof(struct hugepage));
437                 memcpy(&hugepg_tbl[i], &tmp, sizeof(struct hugepage));
438         }
439         return 0;
440 }
441
442 /*
443  * Uses mmap to create a shared memory area for storage of data
444  *Used in this file to store the hugepage file map on disk
445  */
446 static void *
447 create_shared_memory(const char *filename, const size_t mem_size)
448 {
449         void *retval;
450         int fd = open(filename, O_CREAT | O_RDWR, 0666);
451         if (fd < 0)
452                 return NULL;
453         if (ftruncate(fd, mem_size) < 0) {
454                 close(fd);
455                 return NULL;
456         }
457         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
458         close(fd);
459         return retval;
460 }
461
462 /*
463  * This function takes in the list of hugepage sizes and the
464  * number of pages thereof, and calculates the best number of
465  * pages of each size to fulfill the request for <memory> ram
466  */
467 static int
468 calc_num_pages(uint64_t memory,
469                 struct hugepage_info *hp_info,
470                 struct hugepage_info *hp_used,
471                 unsigned num_hp_info)
472 {
473         unsigned i = 0;
474         int total_num_pages = 0;
475         if (num_hp_info == 0)
476                 return -1;
477
478         for (i = 0; i < num_hp_info; i++){
479                 hp_used[i].hugepage_sz = hp_info[i].hugepage_sz;
480                 hp_used[i].hugedir = hp_info[i].hugedir;
481                 hp_used[i].num_pages = RTE_MIN(memory / hp_info[i].hugepage_sz,
482                                 hp_info[i].num_pages);
483
484                 memory -= hp_used[i].num_pages * hp_used[i].hugepage_sz;
485                 total_num_pages += hp_used[i].num_pages;
486
487                 /* check if we have met all memory requests */
488                 if (memory == 0)
489                         break;
490                 /* check if we have any more pages left at this size, if so
491                  * move on to next size */
492                 if (hp_used[i].num_pages == hp_info[i].num_pages)
493                         continue;
494                 /* At this point we know that there are more pages available that are
495                  * bigger than the memory we want, so lets see if we can get enough
496                  * from other page sizes.
497                  */
498                 unsigned j;
499                 uint64_t remaining_mem = 0;
500                 for (j = i+1; j < num_hp_info; j++)
501                         remaining_mem += hp_info[j].hugepage_sz * hp_info[j].num_pages;
502
503                 /* is there enough other memory, if not allocate another page and quit*/
504                 if (remaining_mem < memory){
505                         memory -= hp_info[i].hugepage_sz;
506                         hp_used[i].num_pages++;
507                         total_num_pages++;
508                         break; /* we are done */
509                 }
510         }
511         return total_num_pages;
512 }
513
514 /*
515  * Prepare physical memory mapping: fill configuration structure with
516  * these infos, return 0 on success.
517  *  1. map N huge pages in separate files in hugetlbfs
518  *  2. find associated physical addr
519  *  3. find associated NUMA socket ID
520  *  4. sort all huge pages by physical address
521  *  5. remap these N huge pages in the correct order
522  *  6. unmap the first mapping
523  *  7. fill memsegs in configuration with contiguous zones
524  */
525 static int
526 rte_eal_hugepage_init(void)
527 {
528         struct rte_mem_config *mcfg;
529         struct hugepage *hugepage;
530         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
531         int i, j, new_memseg;
532         int nrpages;
533         void *addr;
534
535         memset(used_hp, 0, sizeof(used_hp));
536
537         /* get pointer to global configuration */
538         mcfg = rte_eal_get_configuration()->mem_config;
539
540         /* for debug purposes, hugetlbfs can be disabled */
541         if (internal_config.no_hugetlbfs) {
542                 addr = malloc(internal_config.memory);
543                 mcfg->memseg[0].phys_addr = (unsigned long)addr;
544                 mcfg->memseg[0].addr = addr;
545                 mcfg->memseg[0].len = internal_config.memory;
546                 mcfg->memseg[0].socket_id = 0;
547                 return 0;
548         }
549
550         nrpages = calc_num_pages(internal_config.memory,
551                         &internal_config.hugepage_info[0], &used_hp[0],
552                         internal_config.num_hugepage_sizes);
553         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i++)
554                 RTE_LOG(INFO, EAL, "Requesting %u pages of size %"PRIu64"\n",
555                                 used_hp[i].num_pages, used_hp[i].hugepage_sz);
556
557         hugepage = create_shared_memory(eal_hugepage_info_path(),
558                         nrpages * sizeof(struct hugepage));
559         if (hugepage == NULL)
560                 return -1;
561         memset(hugepage, 0, nrpages * sizeof(struct hugepage));
562
563         unsigned hp_offset = 0; /* where we start the current page size entries */
564         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
565                 struct hugepage_info *hpi = &used_hp[i];
566                 if (hpi->num_pages == 0)
567                         continue;
568
569                 if (map_all_hugepages(&hugepage[hp_offset], hpi, 1) < 0){
570                         RTE_LOG(DEBUG, EAL, "Failed to mmap %u MB hugepages\n",
571                                         (unsigned)(hpi->hugepage_sz / 0x100000));
572                         goto fail;
573                 }
574
575                 if (find_physaddr(&hugepage[hp_offset], hpi) < 0){
576                         RTE_LOG(DEBUG, EAL, "Failed to find phys addr for %u MB pages\n",
577                                         (unsigned)(hpi->hugepage_sz / 0x100000));
578                         goto fail;
579                 }
580
581                 if (find_numasocket(&hugepage[hp_offset], hpi) < 0){
582                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
583                                         (unsigned)(hpi->hugepage_sz / 0x100000));
584                         goto fail;
585                 }
586
587                 if (sort_by_physaddr(&hugepage[hp_offset], hpi) < 0)
588                         goto fail;
589
590                 if (map_all_hugepages(&hugepage[hp_offset], hpi, 0) < 0){
591                         RTE_LOG(DEBUG, EAL, "Failed to remap %u MB pages\n",
592                                         (unsigned)(hpi->hugepage_sz / 0x100000));
593                         goto fail;
594                 }
595
596                 if (unmap_all_hugepages_orig(&hugepage[hp_offset], hpi) < 0)
597                         goto fail;
598
599                 /* we have processed a num of hugepages of this size, so inc offset */
600                 hp_offset += hpi->num_pages;
601         }
602
603         memset(mcfg->memseg, 0, sizeof(mcfg->memseg));
604         j = -1;
605         for (i = 0; i < nrpages; i++) {
606                 new_memseg = 0;
607
608                 /* if this is a new section, create a new memseg */
609                 if (i == 0)
610                         new_memseg = 1;
611                 else if (hugepage[i].socket_id != hugepage[i-1].socket_id)
612                         new_memseg = 1;
613                 else if (hugepage[i].size != hugepage[i-1].size)
614                         new_memseg = 1;
615                 else if ((hugepage[i].physaddr - hugepage[i-1].physaddr) !=
616                          hugepage[i].size)
617                         new_memseg = 1;
618                 else if (((unsigned long)hugepage[i].final_va -
619                      (unsigned long)hugepage[i-1].final_va) != hugepage[i].size)
620                         new_memseg = 1;
621
622                 if (new_memseg) {
623                         j += 1;
624                         if (j == RTE_MAX_MEMSEG)
625                                 break;
626
627                         mcfg->memseg[j].phys_addr = hugepage[i].physaddr;
628                         mcfg->memseg[j].addr = hugepage[i].final_va;
629                         mcfg->memseg[j].len = hugepage[i].size;
630                         mcfg->memseg[j].socket_id = hugepage[i].socket_id;
631                         mcfg->memseg[j].hugepage_sz = hugepage[i].size;
632                 }
633                 /* continuation of previous memseg */
634                 else {
635                         mcfg->memseg[j].len += mcfg->memseg[j].hugepage_sz;
636                 }
637                 hugepage[i].memseg_id = j;
638         }
639
640         return 0;
641
642
643  fail:
644         return -1;
645 }
646
647 /*
648  * uses fstat to report the size of a file on disk
649  */
650 static off_t
651 getFileSize(int fd)
652 {
653         struct stat st;
654         if (fstat(fd, &st) < 0)
655                 return 0;
656         return st.st_size;
657 }
658
659 /*
660  * This creates the memory mappings in the secondary process to match that of
661  * the server process. It goes through each memory segment in the DPDK runtime
662  * configuration and finds the hugepages which form that segment, mapping them
663  * in order to form a contiguous block in the virtual memory space
664  */
665 static int
666 rte_eal_hugepage_attach(void)
667 {
668         const struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
669         const struct hugepage *hp = NULL;
670         unsigned num_hp = 0;
671         unsigned i, s = 0; /* s used to track the segment number */
672         off_t size;
673         int fd, fd_zero = -1, fd_hugepage = -1;
674
675         if (aslr_enabled() > 0) {
676                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
677                                 "(ASLR) is enabled in the kernel.\n");
678                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
679                                 "into secondary processes\n");
680         }
681
682         fd_zero = open("/dev/zero", O_RDONLY);
683         if (fd_zero < 0) {
684                 RTE_LOG(ERR, EAL, "Could not open /dev/zero\n");
685                 goto error;
686         }
687         fd_hugepage = open(eal_hugepage_info_path(), O_RDONLY);
688         if (fd_hugepage < 0) {
689                 RTE_LOG(ERR, EAL, "Could not open %s\n", eal_hugepage_info_path());
690                 goto error;
691         }
692
693         size = getFileSize(fd_hugepage);
694         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
695         if (hp == NULL) {
696                 RTE_LOG(ERR, EAL, "Could not mmap %s\n", eal_hugepage_info_path());
697                 goto error;
698         }
699
700         num_hp = size / sizeof(struct hugepage);
701         RTE_LOG(DEBUG, EAL, "Analysing %u hugepages\n", num_hp);
702
703         while (s < RTE_MAX_MEMSEG && mcfg->memseg[s].len > 0){
704                 void *addr, *base_addr;
705                 uintptr_t offset = 0;
706
707                 /* fdzero is mmapped to get a contiguous block of virtual addresses
708                  * get a block of free memory of the appropriate size -
709                  * use mmap to attempt to get an identical address as server.
710                  */
711                 base_addr = mmap(mcfg->memseg[s].addr, mcfg->memseg[s].len,
712                                 PROT_READ, MAP_PRIVATE, fd_zero, 0);
713                 if (base_addr == MAP_FAILED || base_addr != mcfg->memseg[s].addr) {
714                         RTE_LOG(ERR, EAL, "Could not mmap %llu bytes "
715                                 "in /dev/zero to requested address [%p]\n",
716                                 (unsigned long long)mcfg->memseg[s].len,
717                                 mcfg->memseg[s].addr);
718                         if (aslr_enabled() > 0)
719                                 RTE_LOG(ERR, EAL, "It is recommended to disable ASLR in the kernel "
720                                                 "and retry running both primary and secondary processes\n");
721                         goto error;
722                 }
723                 /* free memory so we can map the hugepages into the space */
724                 munmap(base_addr, mcfg->memseg[s].len);
725
726                 /* find the hugepages for this segment and map them
727                  * we don't need to worry about order, as the server sorted the
728                  * entries before it did the second mmap of them */
729                 for (i = 0; i < num_hp && offset < mcfg->memseg[s].len; i++){
730                         if (hp[i].memseg_id == (int)s){
731                                 fd = open(hp[i].filepath, O_RDWR);
732                                 if (fd < 0) {
733                                         RTE_LOG(ERR, EAL, "Could not open %s\n",
734                                                 hp[i].filepath);
735                                         goto error;
736                                 }
737                                 addr = mmap(RTE_PTR_ADD(base_addr, offset),
738                                                 hp[i].size, PROT_READ | PROT_WRITE,
739                                                 MAP_SHARED | MAP_FIXED, fd, 0);
740                                 close(fd); /* close file both on success and on failure */
741                                 if (addr == MAP_FAILED) {
742                                         RTE_LOG(ERR, EAL, "Could not mmap %s\n",
743                                                 hp[i].filepath);
744                                         goto error;
745                                 }
746                                 offset+=hp[i].size;
747                         }
748                 }
749                 RTE_LOG(DEBUG, EAL, "Mapped segment %u of size 0x%llx\n", s,
750                                 (unsigned long long)mcfg->memseg[s].len);
751                 s++;
752         }
753         close(fd_zero);
754         close(fd_hugepage);
755         return 0;
756
757 error:
758         if (fd_zero >= 0)
759                 close(fd_zero);
760         if (fd_hugepage >= 0)
761                 close(fd_hugepage);
762         return -1;
763 }
764
765 static int
766 rte_eal_memdevice_init(void)
767 {
768         struct rte_config *config;
769
770         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
771                 return 0;
772
773         config = rte_eal_get_configuration();
774         config->mem_config->nchannel = internal_config.force_nchannel;
775         config->mem_config->nrank = internal_config.force_nrank;
776
777         return 0;
778 }
779
780
781 /* init memory subsystem */
782 int
783 rte_eal_memory_init(void)
784 {
785         const int retval = rte_eal_process_type() == RTE_PROC_PRIMARY ?
786                         rte_eal_hugepage_init() :
787                         rte_eal_hugepage_attach();
788         if (retval < 0)
789                 return -1;
790
791         if (internal_config.no_shconf == 0 && rte_eal_memdevice_init() < 0)
792                 return -1;
793
794         return 0;
795 }