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