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