mem: allow virtual memory address hinting
[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 /*
117  * Check whether address-space layout randomization is enabled in
118  * the kernel. This is important for multi-process as it can prevent
119  * two processes mapping data to the same virtual address
120  * Returns:
121  *    0 - address space randomization disabled
122  *    1/2 - address space randomization enabled
123  *    negative error code on error
124  */
125 static int
126 aslr_enabled(void)
127 {
128         char c;
129         int retval, fd = open(RANDOMIZE_VA_SPACE_FILE, O_RDONLY);
130         if (fd < 0)
131                 return -errno;
132         retval = read(fd, &c, 1);
133         close(fd);
134         if (retval < 0)
135                 return -errno;
136         if (retval == 0)
137                 return -EIO;
138         switch (c) {
139                 case '0' : return 0;
140                 case '1' : return 1;
141                 case '2' : return 2;
142                 default: return -EINVAL;
143         }
144 }
145
146 /*
147  * Try to mmap *size bytes in /dev/zero. If it is succesful, return the
148  * pointer to the mmap'd area and keep *size unmodified. Else, retry
149  * with a smaller zone: decrease *size by hugepage_sz until it reaches
150  * 0. In this case, return NULL. Note: this function returns an address
151  * which is a multiple of hugepage size.
152  */
153 static void *
154 get_virtual_area(size_t *size, size_t hugepage_sz)
155 {
156         void *addr;
157         int fd;
158         long aligned_addr;
159
160         if (internal_config.base_virtaddr != 0) {
161                 addr = (void*) (uintptr_t) (internal_config.base_virtaddr +
162                                 baseaddr_offset);
163         }
164         else addr = NULL;
165
166         RTE_LOG(INFO, EAL, "Ask a virtual area of 0x%zx bytes\n", *size);
167
168         fd = open("/dev/zero", O_RDONLY);
169         if (fd < 0){
170                 RTE_LOG(ERR, EAL, "Cannot open /dev/zero\n");
171                 return NULL;
172         }
173         do {
174                 addr = mmap(addr,
175                                 (*size) + hugepage_sz, PROT_READ, MAP_PRIVATE, fd, 0);
176                 if (addr == MAP_FAILED)
177                         *size -= hugepage_sz;
178         } while (addr == MAP_FAILED && *size > 0);
179
180         if (addr == MAP_FAILED) {
181                 close(fd);
182                 RTE_LOG(INFO, EAL, "Cannot get a virtual area\n");
183                 return NULL;
184         }
185
186         munmap(addr, (*size) + hugepage_sz);
187         close(fd);
188
189         /* align addr to a huge page size boundary */
190         aligned_addr = (long)addr;
191         aligned_addr += (hugepage_sz - 1);
192         aligned_addr &= (~(hugepage_sz - 1));
193         addr = (void *)(aligned_addr);
194
195         RTE_LOG(INFO, EAL, "Virtual area found at %p (size = 0x%zx)\n",
196                 addr, *size);
197
198         /* increment offset */
199         baseaddr_offset += *size;
200
201         return addr;
202 }
203
204 /*
205  * Mmap all hugepages of hugepage table: it first open a file in
206  * hugetlbfs, then mmap() hugepage_sz data in it. If orig is set, the
207  * virtual address is stored in hugepg_tbl[i].orig_va, else it is stored
208  * in hugepg_tbl[i].final_va. The second mapping (when orig is 0) tries to
209  * map continguous physical blocks in contiguous virtual blocks.
210  */
211 static int
212 map_all_hugepages(struct hugepage *hugepg_tbl,
213                 struct hugepage_info *hpi, int orig)
214 {
215         int fd;
216         unsigned i;
217         void *virtaddr;
218         void *vma_addr = NULL;
219         size_t vma_len = 0;
220
221         for (i = 0; i < hpi->num_pages[0]; i++) {
222                 size_t hugepage_sz = hpi->hugepage_sz;
223
224                 if (orig) {
225                         hugepg_tbl[i].file_id = i;
226                         hugepg_tbl[i].size = hugepage_sz;
227                         eal_get_hugefile_path(hugepg_tbl[i].filepath,
228                                         sizeof(hugepg_tbl[i].filepath), hpi->hugedir,
229                                         hugepg_tbl[i].file_id);
230                         hugepg_tbl[i].filepath[sizeof(hugepg_tbl[i].filepath) - 1] = '\0';
231                 }
232 #ifndef RTE_ARCH_X86_64
233                 /* for 32-bit systems, don't remap 1G pages, just reuse original
234                  * map address as final map address.
235                  */
236                 else if (hugepage_sz == RTE_PGSIZE_1G){
237                         hugepg_tbl[i].final_va = hugepg_tbl[i].orig_va;
238                         hugepg_tbl[i].orig_va = NULL;
239                         continue;
240                 }
241 #endif
242                 else if (vma_len == 0) {
243                         unsigned j, num_pages;
244
245                         /* reserve a virtual area for next contiguous
246                          * physical block: count the number of
247                          * contiguous physical pages. */
248                         for (j = i+1; j < hpi->num_pages[0] ; j++) {
249                                 if (hugepg_tbl[j].physaddr !=
250                                     hugepg_tbl[j-1].physaddr + hugepage_sz)
251                                         break;
252                         }
253                         num_pages = j - i;
254                         vma_len = num_pages * hugepage_sz;
255
256                         /* get the biggest virtual memory area up to
257                          * vma_len. If it fails, vma_addr is NULL, so
258                          * let the kernel provide the address. */
259                         vma_addr = get_virtual_area(&vma_len, hpi->hugepage_sz);
260                         if (vma_addr == NULL)
261                                 vma_len = hugepage_sz;
262                 }
263
264                 /* try to create hugepage file */
265                 fd = open(hugepg_tbl[i].filepath, O_CREAT | O_RDWR, 0755);
266                 if (fd < 0) {
267                         RTE_LOG(ERR, EAL, "%s(): open failed: %s\n", __func__,
268                                         strerror(errno));
269                         return -1;
270                 }
271
272                 virtaddr = mmap(vma_addr, hugepage_sz, PROT_READ | PROT_WRITE,
273                                 MAP_SHARED, fd, 0);
274                 if (virtaddr == MAP_FAILED) {
275                         RTE_LOG(ERR, EAL, "%s(): mmap failed: %s\n", __func__,
276                                         strerror(errno));
277                         close(fd);
278                         return -1;
279                 }
280
281                 if (orig) {
282                         hugepg_tbl[i].orig_va = virtaddr;
283                         memset(virtaddr, 0, hugepage_sz);
284                 }
285                 else {
286                         hugepg_tbl[i].final_va = virtaddr;
287                 }
288
289                 /* set shared flock on the file. */
290                 if (flock(fd, LOCK_SH | LOCK_NB) == -1) {
291                         RTE_LOG(ERR, EAL, "%s(): Locking file failed:%s \n",
292                                 __func__, strerror(errno));
293                         close(fd);
294                         return -1;
295                 }
296
297                 close(fd);
298
299                 vma_addr = (char *)vma_addr + hugepage_sz;
300                 vma_len -= hugepage_sz;
301         }
302         return 0;
303 }
304
305 /* Unmap all hugepages from original mapping. */
306 static int
307 unmap_all_hugepages_orig(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
308 {
309         unsigned i;
310         for (i = 0; i < hpi->num_pages[0]; i++) {
311                 if (hugepg_tbl[i].orig_va) {
312                         munmap(hugepg_tbl[i].orig_va, hpi->hugepage_sz);
313                         hugepg_tbl[i].orig_va = NULL;
314                 }
315         }
316         return 0;
317 }
318
319 /*
320  * For each hugepage in hugepg_tbl, fill the physaddr value. We find
321  * it by browsing the /proc/self/pagemap special file.
322  */
323 static int
324 find_physaddr(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
325 {
326         int fd;
327         unsigned i;
328         uint64_t page;
329         unsigned long virt_pfn;
330         int page_size;
331
332         /* standard page size */
333         page_size = getpagesize();
334
335         fd = open("/proc/self/pagemap", O_RDONLY);
336         if (fd < 0) {
337                 RTE_LOG(ERR, EAL, "%s(): cannot open /proc/self/pagemap: %s\n",
338                         __func__, strerror(errno));
339                 return -1;
340         }
341
342         for (i = 0; i < hpi->num_pages[0]; i++) {
343                 off_t offset;
344                 virt_pfn = (unsigned long)hugepg_tbl[i].orig_va /
345                         page_size;
346                 offset = sizeof(uint64_t) * virt_pfn;
347                 if (lseek(fd, offset, SEEK_SET) == (off_t) -1) {
348                         RTE_LOG(ERR, EAL, "%s(): seek error in /proc/self/pagemap: %s\n",
349                                         __func__, strerror(errno));
350                         close(fd);
351                         return -1;
352                 }
353                 if (read(fd, &page, sizeof(uint64_t)) < 0) {
354                         RTE_LOG(ERR, EAL, "%s(): cannot read /proc/self/pagemap: %s\n",
355                                         __func__, strerror(errno));
356                         close(fd);
357                         return -1;
358                 }
359
360                 /*
361                  * the pfn (page frame number) are bits 0-54 (see
362                  * pagemap.txt in linux Documentation)
363                  */
364                 hugepg_tbl[i].physaddr = ((page & 0x7fffffffffffffULL) * page_size);
365         }
366         close(fd);
367         return 0;
368 }
369
370 /*
371  * Parse /proc/self/numa_maps to get the NUMA socket ID for each huge
372  * page.
373  */
374 static int
375 find_numasocket(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
376 {
377         int socket_id;
378         char *end, *nodestr;
379         unsigned i, hp_count = 0;
380         uint64_t virt_addr;
381         char buf[BUFSIZ];
382         char hugedir_str[PATH_MAX];
383         FILE *f;
384
385         f = fopen("/proc/self/numa_maps", "r");
386         if (f == NULL) {
387                 RTE_LOG(INFO, EAL, "cannot open /proc/self/numa_maps,"
388                                 " consider that all memory is in socket_id 0\n");
389                 return 0;
390         }
391
392         rte_snprintf(hugedir_str, sizeof(hugedir_str),
393                         "%s/", hpi->hugedir);
394
395         /* parse numa map */
396         while (fgets(buf, sizeof(buf), f) != NULL) {
397
398                 /* ignore non huge page */
399                 if (strstr(buf, " huge ") == NULL &&
400                                 strstr(buf, hugedir_str) == NULL)
401                         continue;
402
403                 /* get zone addr */
404                 virt_addr = strtoull(buf, &end, 16);
405                 if (virt_addr == 0 || end == buf) {
406                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
407                         goto error;
408                 }
409
410                 /* get node id (socket id) */
411                 nodestr = strstr(buf, " N");
412                 if (nodestr == NULL) {
413                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
414                         goto error;
415                 }
416                 nodestr += 2;
417                 end = strstr(nodestr, "=");
418                 if (end == NULL) {
419                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
420                         goto error;
421                 }
422                 end[0] = '\0';
423                 end = NULL;
424
425                 socket_id = strtoul(nodestr, &end, 0);
426                 if ((nodestr[0] == '\0') || (end == NULL) || (*end != '\0')) {
427                         RTE_LOG(ERR, EAL, "%s(): error in numa_maps parsing\n", __func__);
428                         goto error;
429                 }
430
431                 /* if we find this page in our mappings, set socket_id */
432                 for (i = 0; i < hpi->num_pages[0]; i++) {
433                         void *va = (void *)(unsigned long)virt_addr;
434                         if (hugepg_tbl[i].orig_va == va) {
435                                 hugepg_tbl[i].socket_id = socket_id;
436                                 hp_count++;
437                         }
438                 }
439         }
440
441         if (hp_count < hpi->num_pages[0])
442                 goto error;
443
444         fclose(f);
445         return 0;
446
447 error:
448         fclose(f);
449         return -1;
450 }
451
452 /*
453  * Sort the hugepg_tbl by physical address (lower addresses first). We
454  * use a slow algorithm, but we won't have millions of pages, and this
455  * is only done at init time.
456  */
457 static int
458 sort_by_physaddr(struct hugepage *hugepg_tbl, struct hugepage_info *hpi)
459 {
460         unsigned i, j;
461         int smallest_idx;
462         uint64_t smallest_addr;
463         struct hugepage tmp;
464
465         for (i = 0; i < hpi->num_pages[0]; i++) {
466                 smallest_addr = 0;
467                 smallest_idx = -1;
468
469                 /*
470                  * browse all entries starting at 'i', and find the
471                  * entry with the smallest addr
472                  */
473                 for (j=i; j< hpi->num_pages[0]; j++) {
474
475                         if (smallest_addr == 0 ||
476                             hugepg_tbl[j].physaddr < smallest_addr) {
477                                 smallest_addr = hugepg_tbl[j].physaddr;
478                                 smallest_idx = j;
479                         }
480                 }
481
482                 /* should not happen */
483                 if (smallest_idx == -1) {
484                         RTE_LOG(ERR, EAL, "%s(): error in physaddr sorting\n", __func__);
485                         return -1;
486                 }
487
488                 /* swap the 2 entries in the table */
489                 memcpy(&tmp, &hugepg_tbl[smallest_idx], sizeof(struct hugepage));
490                 memcpy(&hugepg_tbl[smallest_idx], &hugepg_tbl[i],
491                                 sizeof(struct hugepage));
492                 memcpy(&hugepg_tbl[i], &tmp, sizeof(struct hugepage));
493         }
494         return 0;
495 }
496
497 /*
498  * Uses mmap to create a shared memory area for storage of data
499  * Used in this file to store the hugepage file map on disk
500  */
501 static void *
502 create_shared_memory(const char *filename, const size_t mem_size)
503 {
504         void *retval;
505         int fd = open(filename, O_CREAT | O_RDWR, 0666);
506         if (fd < 0)
507                 return NULL;
508         if (ftruncate(fd, mem_size) < 0) {
509                 close(fd);
510                 return NULL;
511         }
512         retval = mmap(NULL, mem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
513         close(fd);
514         return retval;
515 }
516
517 /*
518  * this copies *active* hugepages from one hugepage table to another.
519  * destination is typically the shared memory.
520  */
521 static int
522 copy_hugepages_to_shared_mem(struct hugepage * dst, int dest_size,
523                 const struct hugepage * src, int src_size)
524 {
525         int src_pos, dst_pos = 0;
526
527         for (src_pos = 0; src_pos < src_size; src_pos++) {
528                 if (src[src_pos].final_va != NULL) {
529                         /* error on overflow attempt */
530                         if (dst_pos == dest_size)
531                                 return -1;
532                         memcpy(&dst[dst_pos], &src[src_pos], sizeof(struct hugepage));
533                         dst_pos++;
534                 }
535         }
536         return 0;
537 }
538
539 /*
540  * unmaps hugepages that are not going to be used. since we originally allocate
541  * ALL hugepages (not just those we need), additional unmapping needs to be done.
542  */
543 static int
544 unmap_unneeded_hugepages(struct hugepage *hugepg_tbl,
545                 struct hugepage_info *hpi,
546                 unsigned num_hp_info)
547 {
548         unsigned socket, size;
549         int page, nrpages = 0;
550
551         /* get total number of hugepages */
552         for (size = 0; size < num_hp_info; size++)
553                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++)
554                         nrpages += internal_config.hugepage_info[size].num_pages[socket];
555
556         for (size = 0; size < num_hp_info; size++) {
557                 for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++) {
558                         unsigned pages_found = 0;
559                         /* traverse until we have unmapped all the unused pages */
560                         for (page = 0; page < nrpages; page++) {
561                                 struct hugepage *hp = &hugepg_tbl[page];
562
563                                 /* find a page that matches the criteria */
564                                 if ((hp->size == hpi[size].hugepage_sz) &&
565                                                 (hp->socket_id == (int) socket)) {
566
567                                         /* if we skipped enough pages, unmap the rest */
568                                         if (pages_found == hpi[size].num_pages[socket]) {
569                                                 munmap(hp->final_va, hp->size);
570                                                 hp->final_va = NULL;
571                                                 if (remove(hp->filepath) == -1) {
572                                                         RTE_LOG(ERR, EAL, "%s(): Removing %s failed: %s\n",
573                                                                         __func__, hp->filepath, strerror(errno));
574                                                         return -1;
575                                                 }
576                                         }
577                                         /* lock the page and skip */
578                                         else
579                                                 pages_found++;
580
581                                 } /* match page */
582                         } /* foreach page */
583                 } /* foreach socket */
584         } /* foreach pagesize */
585
586         return 0;
587 }
588
589 static inline uint64_t
590 get_socket_mem_size(int socket)
591 {
592         uint64_t size = 0;
593         unsigned i;
594
595         for (i = 0; i < internal_config.num_hugepage_sizes; i++){
596                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
597                 if (hpi->hugedir != NULL)
598                         size += hpi->hugepage_sz * hpi->num_pages[socket];
599         }
600
601         return (size);
602 }
603
604 /*
605  * This function is a NUMA-aware equivalent of calc_num_pages.
606  * It takes in the list of hugepage sizes and the
607  * number of pages thereof, and calculates the best number of
608  * pages of each size to fulfill the request for <memory> ram
609  */
610 static int
611 calc_num_pages_per_socket(uint64_t * memory,
612                 struct hugepage_info *hp_info,
613                 struct hugepage_info *hp_used,
614                 unsigned num_hp_info)
615 {
616         unsigned socket, j, i = 0;
617         unsigned requested, available;
618         int total_num_pages = 0;
619         uint64_t remaining_mem, cur_mem;
620         uint64_t total_mem = internal_config.memory;
621
622         if (num_hp_info == 0)
623                 return -1;
624
625         for (socket = 0; socket < RTE_MAX_NUMA_NODES && total_mem != 0; socket++) {
626                 /* if specific memory amounts per socket weren't requested */
627                 if (internal_config.force_sockets == 0) {
628                         /* take whatever is available */
629                         memory[socket] = RTE_MIN(get_socket_mem_size(socket),
630                                         total_mem);
631                 }
632                 /* skips if the memory on specific socket wasn't requested */
633                 for (i = 0; i < num_hp_info && memory[socket] != 0; i++){
634                         hp_used[i].hugedir = hp_info[i].hugedir;
635                         hp_used[i].num_pages[socket] = RTE_MIN(
636                                         memory[socket] / hp_info[i].hugepage_sz,
637                                         hp_info[i].num_pages[socket]);
638
639                         cur_mem = hp_used[i].num_pages[socket] *
640                                         hp_used[i].hugepage_sz;
641
642                         memory[socket] -= cur_mem;
643                         total_mem -= cur_mem;
644
645                         total_num_pages += hp_used[i].num_pages[socket];
646
647                         /* check if we have met all memory requests */
648                         if (memory[socket] == 0)
649                                 break;
650
651                         /* check if we have any more pages left at this size, if so
652                          * move on to next size */
653                         if (hp_used[i].num_pages[socket] == hp_info[i].num_pages[socket])
654                                 continue;
655                         /* At this point we know that there are more pages available that are
656                          * bigger than the memory we want, so lets see if we can get enough
657                          * from other page sizes.
658                          */
659                         remaining_mem = 0;
660                         for (j = i+1; j < num_hp_info; j++)
661                                 remaining_mem += hp_info[j].hugepage_sz *
662                                 hp_info[j].num_pages[socket];
663
664                         /* is there enough other memory, if not allocate another page and quit */
665                         if (remaining_mem < memory[socket]){
666                                 cur_mem = RTE_MIN(memory[socket],
667                                                 hp_info[i].hugepage_sz);
668                                 memory[socket] -= cur_mem;
669                                 total_mem -= cur_mem;
670                                 hp_used[i].num_pages[socket]++;
671                                 total_num_pages++;
672                                 break; /* we are done with this socket*/
673                         }
674                 }
675                 /* if we didn't satisfy all memory requirements per socket */
676                 if (memory[socket] > 0) {
677                         /* to prevent icc errors */
678                         requested = (unsigned) (internal_config.socket_mem[socket] /
679                                         0x100000);
680                         available = requested -
681                                         ((unsigned) (memory[socket] / 0x100000));
682                         RTE_LOG(INFO, EAL, "Not enough memory available on socket %u! "
683                                         "Requested: %uMB, available: %uMB\n", socket,
684                                         requested, available);
685                         return -1;
686                 }
687         }
688
689         /* if we didn't satisfy total memory requirements */
690         if (total_mem > 0) {
691                 requested = (unsigned) (internal_config.memory / 0x100000);
692                 available = requested - (unsigned) (total_mem / 0x100000);
693                 RTE_LOG(INFO, EAL, "Not enough memory available! Requested: %uMB,"
694                                 " available: %uMB\n", requested, available);
695                 return -1;
696         }
697         return total_num_pages;
698 }
699
700 /*
701  * Prepare physical memory mapping: fill configuration structure with
702  * these infos, return 0 on success.
703  *  1. map N huge pages in separate files in hugetlbfs
704  *  2. find associated physical addr
705  *  3. find associated NUMA socket ID
706  *  4. sort all huge pages by physical address
707  *  5. remap these N huge pages in the correct order
708  *  6. unmap the first mapping
709  *  7. fill memsegs in configuration with contiguous zones
710  */
711 static int
712 rte_eal_hugepage_init(void)
713 {
714         struct rte_mem_config *mcfg;
715         struct hugepage *hugepage, *tmp_hp = NULL;
716         struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];
717
718         uint64_t memory[RTE_MAX_NUMA_NODES];
719
720         unsigned hp_offset;
721         int i, j, new_memseg;
722         int nrpages, total_pages = 0;
723         void *addr;
724
725         memset(used_hp, 0, sizeof(used_hp));
726
727         /* get pointer to global configuration */
728         mcfg = rte_eal_get_configuration()->mem_config;
729
730         /* for debug purposes, hugetlbfs can be disabled */
731         if (internal_config.no_hugetlbfs) {
732                 addr = malloc(internal_config.memory);
733                 mcfg->memseg[0].phys_addr = (phys_addr_t)(uintptr_t)addr;
734                 mcfg->memseg[0].addr = addr;
735                 mcfg->memseg[0].len = internal_config.memory;
736                 mcfg->memseg[0].socket_id = 0;
737                 return 0;
738         }
739
740
741         /* calculate total number of hugepages available. at this point we haven't
742          * yet started sorting them so they all are on socket 0 */
743         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
744                 /* meanwhile, also initialize used_hp hugepage sizes in used_hp */
745                 used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;
746
747                 total_pages += internal_config.hugepage_info[i].num_pages[0];
748         }
749
750         /*
751          * allocate a memory area for hugepage table.
752          * this isn't shared memory yet. due to the fact that we need some
753          * processing done on these pages, shared memory will be created
754          * at a later stage.
755          */
756         tmp_hp = malloc(total_pages * sizeof(struct hugepage));
757         if (tmp_hp == NULL)
758                 goto fail;
759
760         memset(tmp_hp, 0, total_pages * sizeof(struct hugepage));
761
762         hp_offset = 0; /* where we start the current page size entries */
763
764         /* map all hugepages and sort them */
765         for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
766                 struct hugepage_info *hpi;
767
768                 /*
769                  * we don't yet mark hugepages as used at this stage, so
770                  * we just map all hugepages available to the system
771                  * all hugepages are still located on socket 0
772                  */
773                 hpi = &internal_config.hugepage_info[i];
774
775                 if (hpi->num_pages == 0)
776                         continue;
777
778                 /* map all hugepages available */
779                 if (map_all_hugepages(&tmp_hp[hp_offset], hpi, 1) < 0){
780                         RTE_LOG(DEBUG, EAL, "Failed to mmap %u MB hugepages\n",
781                                         (unsigned)(hpi->hugepage_sz / 0x100000));
782                         goto fail;
783                 }
784
785                 /* find physical addresses and sockets for each hugepage */
786                 if (find_physaddr(&tmp_hp[hp_offset], hpi) < 0){
787                         RTE_LOG(DEBUG, EAL, "Failed to find phys addr for %u MB pages\n",
788                                         (unsigned)(hpi->hugepage_sz / 0x100000));
789                         goto fail;
790                 }
791
792                 if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
793                         RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
794                                         (unsigned)(hpi->hugepage_sz / 0x100000));
795                         goto fail;
796                 }
797
798                 if (sort_by_physaddr(&tmp_hp[hp_offset], hpi) < 0)
799                         goto fail;
800
801                 /* remap all hugepages */
802                 if (map_all_hugepages(&tmp_hp[hp_offset], hpi, 0) < 0){
803                         RTE_LOG(DEBUG, EAL, "Failed to remap %u MB pages\n",
804                                         (unsigned)(hpi->hugepage_sz / 0x100000));
805                         goto fail;
806                 }
807
808                 /* unmap original mappings */
809                 if (unmap_all_hugepages_orig(&tmp_hp[hp_offset], hpi) < 0)
810                         goto fail;
811
812                 /* we have processed a num of hugepages of this size, so inc offset */
813                 hp_offset += hpi->num_pages[0];
814         }
815
816         /* clean out the numbers of pages */
817         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
818                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
819                         internal_config.hugepage_info[i].num_pages[j] = 0;
820
821         /* get hugepages for each socket */
822         for (i = 0; i < total_pages; i++) {
823                 int socket = tmp_hp[i].socket_id;
824
825                 /* find a hugepage info with right size and increment num_pages */
826                 for (j = 0; j < (int) internal_config.num_hugepage_sizes; j++) {
827                         if (tmp_hp[i].size ==
828                                         internal_config.hugepage_info[j].hugepage_sz) {
829                                 internal_config.hugepage_info[j].num_pages[socket]++;
830                         }
831                 }
832         }
833
834         /* make a copy of socket_mem, needed for number of pages calculation */
835         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
836                 memory[i] = internal_config.socket_mem[i];
837
838         /* calculate final number of pages */
839         nrpages = calc_num_pages_per_socket(memory,
840                         internal_config.hugepage_info, used_hp,
841                         internal_config.num_hugepage_sizes);
842
843         /* error if not enough memory available */
844         if (nrpages < 0)
845                 goto fail;
846
847         /* reporting in! */
848         for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
849                 for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
850                         if (used_hp[i].num_pages[j] > 0) {
851                                 RTE_LOG(INFO, EAL,
852                                                 "Requesting %u pages of size %uMB"
853                                                 " from socket %i\n",
854                                                 used_hp[i].num_pages[j],
855                                                 (unsigned)
856                                                         (used_hp[i].hugepage_sz / 0x100000),
857                                                 j);
858                         }
859                 }
860         }
861
862         /* create shared memory */
863         hugepage = create_shared_memory(eal_hugepage_info_path(),
864                                         nrpages * sizeof(struct hugepage));
865
866         if (hugepage == NULL) {
867                 RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
868                 goto fail;
869         }
870
871         /*
872          * unmap pages that we won't need (looks at used_hp).
873          * also, sets final_va to NULL on pages that were unmapped.
874          */
875         if (unmap_unneeded_hugepages(tmp_hp, used_hp,
876                         internal_config.num_hugepage_sizes) < 0) {
877                 RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
878                 goto fail;
879         }
880
881         /*
882          * copy stuff from malloc'd hugepage* to the actual shared memory.
883          * this procedure only copies those hugepages that have final_va
884          * not NULL. has overflow protection.
885          */
886         if (copy_hugepages_to_shared_mem(hugepage, nrpages,
887                         tmp_hp, total_pages) < 0) {
888                 RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
889                 goto fail;
890         }
891
892         /* free the temporary hugepage table */
893         free(tmp_hp);
894         tmp_hp = NULL;
895
896         memset(mcfg->memseg, 0, sizeof(mcfg->memseg));
897         j = -1;
898         for (i = 0; i < nrpages; i++) {
899                 new_memseg = 0;
900
901                 /* if this is a new section, create a new memseg */
902                 if (i == 0)
903                         new_memseg = 1;
904                 else if (hugepage[i].socket_id != hugepage[i-1].socket_id)
905                         new_memseg = 1;
906                 else if (hugepage[i].size != hugepage[i-1].size)
907                         new_memseg = 1;
908                 else if ((hugepage[i].physaddr - hugepage[i-1].physaddr) !=
909                     hugepage[i].size)
910                         new_memseg = 1;
911                 else if (((unsigned long)hugepage[i].final_va -
912                     (unsigned long)hugepage[i-1].final_va) != hugepage[i].size)
913                         new_memseg = 1;
914
915                 if (new_memseg) {
916                         j += 1;
917                         if (j == RTE_MAX_MEMSEG)
918                                 break;
919
920                         mcfg->memseg[j].phys_addr = hugepage[i].physaddr;
921                         mcfg->memseg[j].addr = hugepage[i].final_va;
922                         mcfg->memseg[j].len = hugepage[i].size;
923                         mcfg->memseg[j].socket_id = hugepage[i].socket_id;
924                         mcfg->memseg[j].hugepage_sz = hugepage[i].size;
925                 }
926                 /* continuation of previous memseg */
927                 else {
928                         mcfg->memseg[j].len += mcfg->memseg[j].hugepage_sz;
929                 }
930                 hugepage[i].memseg_id = j;
931         }
932
933         if (i < nrpages) {
934                 RTE_LOG(ERR, EAL, "Can only reserve %d pages "
935                         "from %d requested\n"
936                         "Current %s=%d is not enough\n"
937                         "Please either increase it or request less amount "
938                         "of memory.\n",
939                         i, nrpages, RTE_STR(CONFIG_RTE_MAX_MEMSEG),
940                         RTE_MAX_MEMSEG);
941                 return (-ENOMEM);
942         }
943         
944
945         return 0;
946
947
948 fail:
949         if (tmp_hp)
950                 free(tmp_hp);
951         return -1;
952 }
953
954 /*
955  * uses fstat to report the size of a file on disk
956  */
957 static off_t
958 getFileSize(int fd)
959 {
960         struct stat st;
961         if (fstat(fd, &st) < 0)
962                 return 0;
963         return st.st_size;
964 }
965
966 /*
967  * This creates the memory mappings in the secondary process to match that of
968  * the server process. It goes through each memory segment in the DPDK runtime
969  * configuration and finds the hugepages which form that segment, mapping them
970  * in order to form a contiguous block in the virtual memory space
971  */
972 static int
973 rte_eal_hugepage_attach(void)
974 {
975         const struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
976         const struct hugepage *hp = NULL;
977         unsigned num_hp = 0;
978         unsigned i, s = 0; /* s used to track the segment number */
979         off_t size;
980         int fd, fd_zero = -1, fd_hugepage = -1;
981
982         if (aslr_enabled() > 0) {
983                 RTE_LOG(WARNING, EAL, "WARNING: Address Space Layout Randomization "
984                                 "(ASLR) is enabled in the kernel.\n");
985                 RTE_LOG(WARNING, EAL, "   This may cause issues with mapping memory "
986                                 "into secondary processes\n");
987         }
988
989         fd_zero = open("/dev/zero", O_RDONLY);
990         if (fd_zero < 0) {
991                 RTE_LOG(ERR, EAL, "Could not open /dev/zero\n");
992                 goto error;
993         }
994         fd_hugepage = open(eal_hugepage_info_path(), O_RDONLY);
995         if (fd_hugepage < 0) {
996                 RTE_LOG(ERR, EAL, "Could not open %s\n", eal_hugepage_info_path());
997                 goto error;
998         }
999
1000         /* map all segments into memory to make sure we get the addrs */
1001         for (s = 0; s < RTE_MAX_MEMSEG; ++s) {
1002                 void *base_addr;
1003
1004                 /*
1005                  * the first memory segment with len==0 is the one that
1006                  * follows the last valid segment.
1007                  */
1008                 if (mcfg->memseg[s].len == 0)
1009                         break;
1010
1011                 /*
1012                  * fdzero is mmapped to get a contiguous block of virtual
1013                  * addresses of the appropriate memseg size.
1014                  * use mmap to get identical addresses as the primary process.
1015                  */
1016                 base_addr = mmap(mcfg->memseg[s].addr, mcfg->memseg[s].len,
1017                                  PROT_READ, MAP_PRIVATE, fd_zero, 0);
1018                 if (base_addr == MAP_FAILED ||
1019                     base_addr != mcfg->memseg[s].addr) {
1020                         RTE_LOG(ERR, EAL, "Could not mmap %llu bytes "
1021                                 "in /dev/zero to requested address [%p]\n",
1022                                 (unsigned long long)mcfg->memseg[s].len,
1023                                 mcfg->memseg[s].addr);
1024                         if (aslr_enabled() > 0) {
1025                                 RTE_LOG(ERR, EAL, "It is recommended to "
1026                                         "disable ASLR in the kernel "
1027                                         "and retry running both primary "
1028                                         "and secondary processes\n");
1029                         }
1030                         goto error;
1031                 }
1032         }
1033
1034         size = getFileSize(fd_hugepage);
1035         hp = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd_hugepage, 0);
1036         if (hp == NULL) {
1037                 RTE_LOG(ERR, EAL, "Could not mmap %s\n", eal_hugepage_info_path());
1038                 goto error;
1039         }
1040
1041         num_hp = size / sizeof(struct hugepage);
1042         RTE_LOG(DEBUG, EAL, "Analysing %u hugepages\n", num_hp);
1043
1044         s = 0;
1045         while (s < RTE_MAX_MEMSEG && mcfg->memseg[s].len > 0){
1046                 void *addr, *base_addr;
1047                 uintptr_t offset = 0;
1048
1049                 /*
1050                  * free previously mapped memory so we can map the
1051                  * hugepages into the space
1052                  */
1053                 base_addr = mcfg->memseg[s].addr;
1054                 munmap(base_addr, mcfg->memseg[s].len);
1055
1056                 /* find the hugepages for this segment and map them
1057                  * we don't need to worry about order, as the server sorted the
1058                  * entries before it did the second mmap of them */
1059                 for (i = 0; i < num_hp && offset < mcfg->memseg[s].len; i++){
1060                         if (hp[i].memseg_id == (int)s){
1061                                 fd = open(hp[i].filepath, O_RDWR);
1062                                 if (fd < 0) {
1063                                         RTE_LOG(ERR, EAL, "Could not open %s\n",
1064                                                 hp[i].filepath);
1065                                         goto error;
1066                                 }
1067                                 addr = mmap(RTE_PTR_ADD(base_addr, offset),
1068                                                 hp[i].size, PROT_READ | PROT_WRITE,
1069                                                 MAP_SHARED | MAP_FIXED, fd, 0);
1070                                 close(fd); /* close file both on success and on failure */
1071                                 if (addr == MAP_FAILED) {
1072                                         RTE_LOG(ERR, EAL, "Could not mmap %s\n",
1073                                                 hp[i].filepath);
1074                                         goto error;
1075                                 }
1076                                 offset+=hp[i].size;
1077                         }
1078                 }
1079                 RTE_LOG(DEBUG, EAL, "Mapped segment %u of size 0x%llx\n", s,
1080                                 (unsigned long long)mcfg->memseg[s].len);
1081                 s++;
1082         }
1083         /* unmap the hugepage config file, since we are done using it */
1084         munmap((void *)(uintptr_t)hp, size);
1085         close(fd_zero);
1086         close(fd_hugepage);
1087         return 0;
1088
1089 error:
1090         if (fd_zero >= 0)
1091                 close(fd_zero);
1092         if (fd_hugepage >= 0)
1093                 close(fd_hugepage);
1094         return -1;
1095 }
1096
1097 static int
1098 rte_eal_memdevice_init(void)
1099 {
1100         struct rte_config *config;
1101
1102         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1103                 return 0;
1104
1105         config = rte_eal_get_configuration();
1106         config->mem_config->nchannel = internal_config.force_nchannel;
1107         config->mem_config->nrank = internal_config.force_nrank;
1108
1109         return 0;
1110 }
1111
1112
1113 /* init memory subsystem */
1114 int
1115 rte_eal_memory_init(void)
1116 {
1117         RTE_LOG(INFO, EAL, "Setting up hugepage memory...\n");
1118         const int retval = rte_eal_process_type() == RTE_PROC_PRIMARY ?
1119                         rte_eal_hugepage_init() :
1120                         rte_eal_hugepage_attach();
1121         if (retval < 0)
1122                 return -1;
1123
1124         if (internal_config.no_shconf == 0 && rte_eal_memdevice_init() < 0)
1125                 return -1;
1126
1127         return 0;
1128 }