New upstream version 18.08
[deb_dpdk.git] / lib / librte_eal / common / malloc_heap.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4 #include <stdint.h>
5 #include <stddef.h>
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <stdarg.h>
9 #include <errno.h>
10 #include <sys/queue.h>
11
12 #include <rte_memory.h>
13 #include <rte_errno.h>
14 #include <rte_eal.h>
15 #include <rte_eal_memconfig.h>
16 #include <rte_launch.h>
17 #include <rte_per_lcore.h>
18 #include <rte_lcore.h>
19 #include <rte_common.h>
20 #include <rte_string_fns.h>
21 #include <rte_spinlock.h>
22 #include <rte_memcpy.h>
23 #include <rte_atomic.h>
24 #include <rte_fbarray.h>
25
26 #include "eal_internal_cfg.h"
27 #include "eal_memalloc.h"
28 #include "malloc_elem.h"
29 #include "malloc_heap.h"
30 #include "malloc_mp.h"
31
32 static unsigned
33 check_hugepage_sz(unsigned flags, uint64_t hugepage_sz)
34 {
35         unsigned check_flag = 0;
36
37         if (!(flags & ~RTE_MEMZONE_SIZE_HINT_ONLY))
38                 return 1;
39
40         switch (hugepage_sz) {
41         case RTE_PGSIZE_256K:
42                 check_flag = RTE_MEMZONE_256KB;
43                 break;
44         case RTE_PGSIZE_2M:
45                 check_flag = RTE_MEMZONE_2MB;
46                 break;
47         case RTE_PGSIZE_16M:
48                 check_flag = RTE_MEMZONE_16MB;
49                 break;
50         case RTE_PGSIZE_256M:
51                 check_flag = RTE_MEMZONE_256MB;
52                 break;
53         case RTE_PGSIZE_512M:
54                 check_flag = RTE_MEMZONE_512MB;
55                 break;
56         case RTE_PGSIZE_1G:
57                 check_flag = RTE_MEMZONE_1GB;
58                 break;
59         case RTE_PGSIZE_4G:
60                 check_flag = RTE_MEMZONE_4GB;
61                 break;
62         case RTE_PGSIZE_16G:
63                 check_flag = RTE_MEMZONE_16GB;
64         }
65
66         return check_flag & flags;
67 }
68
69 /*
70  * Expand the heap with a memory area.
71  */
72 static struct malloc_elem *
73 malloc_heap_add_memory(struct malloc_heap *heap, struct rte_memseg_list *msl,
74                 void *start, size_t len)
75 {
76         struct malloc_elem *elem = start;
77
78         malloc_elem_init(elem, heap, msl, len);
79
80         malloc_elem_insert(elem);
81
82         elem = malloc_elem_join_adjacent_free(elem);
83
84         malloc_elem_free_list_insert(elem);
85
86         return elem;
87 }
88
89 static int
90 malloc_add_seg(const struct rte_memseg_list *msl,
91                 const struct rte_memseg *ms, size_t len, void *arg __rte_unused)
92 {
93         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
94         struct rte_memseg_list *found_msl;
95         struct malloc_heap *heap;
96         int msl_idx;
97
98         heap = &mcfg->malloc_heaps[msl->socket_id];
99
100         /* msl is const, so find it */
101         msl_idx = msl - mcfg->memsegs;
102
103         if (msl_idx < 0 || msl_idx >= RTE_MAX_MEMSEG_LISTS)
104                 return -1;
105
106         found_msl = &mcfg->memsegs[msl_idx];
107
108         malloc_heap_add_memory(heap, found_msl, ms->addr, len);
109
110         heap->total_size += len;
111
112         RTE_LOG(DEBUG, EAL, "Added %zuM to heap on socket %i\n", len >> 20,
113                         msl->socket_id);
114         return 0;
115 }
116
117 /*
118  * Iterates through the freelist for a heap to find a free element
119  * which can store data of the required size and with the requested alignment.
120  * If size is 0, find the biggest available elem.
121  * Returns null on failure, or pointer to element on success.
122  */
123 static struct malloc_elem *
124 find_suitable_element(struct malloc_heap *heap, size_t size,
125                 unsigned int flags, size_t align, size_t bound, bool contig)
126 {
127         size_t idx;
128         struct malloc_elem *elem, *alt_elem = NULL;
129
130         for (idx = malloc_elem_free_list_index(size);
131                         idx < RTE_HEAP_NUM_FREELISTS; idx++) {
132                 for (elem = LIST_FIRST(&heap->free_head[idx]);
133                                 !!elem; elem = LIST_NEXT(elem, free_list)) {
134                         if (malloc_elem_can_hold(elem, size, align, bound,
135                                         contig)) {
136                                 if (check_hugepage_sz(flags,
137                                                 elem->msl->page_sz))
138                                         return elem;
139                                 if (alt_elem == NULL)
140                                         alt_elem = elem;
141                         }
142                 }
143         }
144
145         if ((alt_elem != NULL) && (flags & RTE_MEMZONE_SIZE_HINT_ONLY))
146                 return alt_elem;
147
148         return NULL;
149 }
150
151 /*
152  * Iterates through the freelist for a heap to find a free element with the
153  * biggest size and requested alignment. Will also set size to whatever element
154  * size that was found.
155  * Returns null on failure, or pointer to element on success.
156  */
157 static struct malloc_elem *
158 find_biggest_element(struct malloc_heap *heap, size_t *size,
159                 unsigned int flags, size_t align, bool contig)
160 {
161         struct malloc_elem *elem, *max_elem = NULL;
162         size_t idx, max_size = 0;
163
164         for (idx = 0; idx < RTE_HEAP_NUM_FREELISTS; idx++) {
165                 for (elem = LIST_FIRST(&heap->free_head[idx]);
166                                 !!elem; elem = LIST_NEXT(elem, free_list)) {
167                         size_t cur_size;
168                         if (!check_hugepage_sz(flags, elem->msl->page_sz))
169                                 continue;
170                         if (contig) {
171                                 cur_size =
172                                         malloc_elem_find_max_iova_contig(elem,
173                                                         align);
174                         } else {
175                                 void *data_start = RTE_PTR_ADD(elem,
176                                                 MALLOC_ELEM_HEADER_LEN);
177                                 void *data_end = RTE_PTR_ADD(elem, elem->size -
178                                                 MALLOC_ELEM_TRAILER_LEN);
179                                 void *aligned = RTE_PTR_ALIGN_CEIL(data_start,
180                                                 align);
181                                 /* check if aligned data start is beyond end */
182                                 if (aligned >= data_end)
183                                         continue;
184                                 cur_size = RTE_PTR_DIFF(data_end, aligned);
185                         }
186                         if (cur_size > max_size) {
187                                 max_size = cur_size;
188                                 max_elem = elem;
189                         }
190                 }
191         }
192
193         *size = max_size;
194         return max_elem;
195 }
196
197 /*
198  * Main function to allocate a block of memory from the heap.
199  * It locks the free list, scans it, and adds a new memseg if the
200  * scan fails. Once the new memseg is added, it re-scans and should return
201  * the new element after releasing the lock.
202  */
203 static void *
204 heap_alloc(struct malloc_heap *heap, const char *type __rte_unused, size_t size,
205                 unsigned int flags, size_t align, size_t bound, bool contig)
206 {
207         struct malloc_elem *elem;
208
209         size = RTE_CACHE_LINE_ROUNDUP(size);
210         align = RTE_CACHE_LINE_ROUNDUP(align);
211
212         elem = find_suitable_element(heap, size, flags, align, bound, contig);
213         if (elem != NULL) {
214                 elem = malloc_elem_alloc(elem, size, align, bound, contig);
215
216                 /* increase heap's count of allocated elements */
217                 heap->alloc_count++;
218         }
219
220         return elem == NULL ? NULL : (void *)(&elem[1]);
221 }
222
223 static void *
224 heap_alloc_biggest(struct malloc_heap *heap, const char *type __rte_unused,
225                 unsigned int flags, size_t align, bool contig)
226 {
227         struct malloc_elem *elem;
228         size_t size;
229
230         align = RTE_CACHE_LINE_ROUNDUP(align);
231
232         elem = find_biggest_element(heap, &size, flags, align, contig);
233         if (elem != NULL) {
234                 elem = malloc_elem_alloc(elem, size, align, 0, contig);
235
236                 /* increase heap's count of allocated elements */
237                 heap->alloc_count++;
238         }
239
240         return elem == NULL ? NULL : (void *)(&elem[1]);
241 }
242
243 /* this function is exposed in malloc_mp.h */
244 void
245 rollback_expand_heap(struct rte_memseg **ms, int n_segs,
246                 struct malloc_elem *elem, void *map_addr, size_t map_len)
247 {
248         if (elem != NULL) {
249                 malloc_elem_free_list_remove(elem);
250                 malloc_elem_hide_region(elem, map_addr, map_len);
251         }
252
253         eal_memalloc_free_seg_bulk(ms, n_segs);
254 }
255
256 /* this function is exposed in malloc_mp.h */
257 struct malloc_elem *
258 alloc_pages_on_heap(struct malloc_heap *heap, uint64_t pg_sz, size_t elt_size,
259                 int socket, unsigned int flags, size_t align, size_t bound,
260                 bool contig, struct rte_memseg **ms, int n_segs)
261 {
262         struct rte_memseg_list *msl;
263         struct malloc_elem *elem = NULL;
264         size_t alloc_sz;
265         int allocd_pages;
266         void *ret, *map_addr;
267
268         alloc_sz = (size_t)pg_sz * n_segs;
269
270         /* first, check if we're allowed to allocate this memory */
271         if (eal_memalloc_mem_alloc_validate(socket,
272                         heap->total_size + alloc_sz) < 0) {
273                 RTE_LOG(DEBUG, EAL, "User has disallowed allocation\n");
274                 return NULL;
275         }
276
277         allocd_pages = eal_memalloc_alloc_seg_bulk(ms, n_segs, pg_sz,
278                         socket, true);
279
280         /* make sure we've allocated our pages... */
281         if (allocd_pages < 0)
282                 return NULL;
283
284         map_addr = ms[0]->addr;
285         msl = rte_mem_virt2memseg_list(map_addr);
286
287         /* check if we wanted contiguous memory but didn't get it */
288         if (contig && !eal_memalloc_is_contig(msl, map_addr, alloc_sz)) {
289                 RTE_LOG(DEBUG, EAL, "%s(): couldn't allocate physically contiguous space\n",
290                                 __func__);
291                 goto fail;
292         }
293
294         /* add newly minted memsegs to malloc heap */
295         elem = malloc_heap_add_memory(heap, msl, map_addr, alloc_sz);
296
297         /* try once more, as now we have allocated new memory */
298         ret = find_suitable_element(heap, elt_size, flags, align, bound,
299                         contig);
300
301         if (ret == NULL)
302                 goto fail;
303
304         return elem;
305
306 fail:
307         rollback_expand_heap(ms, n_segs, elem, map_addr, alloc_sz);
308         return NULL;
309 }
310
311 static int
312 try_expand_heap_primary(struct malloc_heap *heap, uint64_t pg_sz,
313                 size_t elt_size, int socket, unsigned int flags, size_t align,
314                 size_t bound, bool contig)
315 {
316         struct malloc_elem *elem;
317         struct rte_memseg **ms;
318         void *map_addr;
319         size_t alloc_sz;
320         int n_segs;
321         bool callback_triggered = false;
322
323         alloc_sz = RTE_ALIGN_CEIL(align + elt_size +
324                         MALLOC_ELEM_TRAILER_LEN, pg_sz);
325         n_segs = alloc_sz / pg_sz;
326
327         /* we can't know in advance how many pages we'll need, so we malloc */
328         ms = malloc(sizeof(*ms) * n_segs);
329
330         memset(ms, 0, sizeof(*ms) * n_segs);
331
332         if (ms == NULL)
333                 return -1;
334
335         elem = alloc_pages_on_heap(heap, pg_sz, elt_size, socket, flags, align,
336                         bound, contig, ms, n_segs);
337
338         if (elem == NULL)
339                 goto free_ms;
340
341         map_addr = ms[0]->addr;
342
343         /* notify user about changes in memory map */
344         eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC, map_addr, alloc_sz);
345
346         /* notify other processes that this has happened */
347         if (request_sync()) {
348                 /* we couldn't ensure all processes have mapped memory,
349                  * so free it back and notify everyone that it's been
350                  * freed back.
351                  *
352                  * technically, we could've avoided adding memory addresses to
353                  * the map, but that would've led to inconsistent behavior
354                  * between primary and secondary processes, as those get
355                  * callbacks during sync. therefore, force primary process to
356                  * do alloc-and-rollback syncs as well.
357                  */
358                 callback_triggered = true;
359                 goto free_elem;
360         }
361         heap->total_size += alloc_sz;
362
363         RTE_LOG(DEBUG, EAL, "Heap on socket %d was expanded by %zdMB\n",
364                 socket, alloc_sz >> 20ULL);
365
366         free(ms);
367
368         return 0;
369
370 free_elem:
371         if (callback_triggered)
372                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
373                                 map_addr, alloc_sz);
374
375         rollback_expand_heap(ms, n_segs, elem, map_addr, alloc_sz);
376
377         request_sync();
378 free_ms:
379         free(ms);
380
381         return -1;
382 }
383
384 static int
385 try_expand_heap_secondary(struct malloc_heap *heap, uint64_t pg_sz,
386                 size_t elt_size, int socket, unsigned int flags, size_t align,
387                 size_t bound, bool contig)
388 {
389         struct malloc_mp_req req;
390         int req_result;
391
392         memset(&req, 0, sizeof(req));
393
394         req.t = REQ_TYPE_ALLOC;
395         req.alloc_req.align = align;
396         req.alloc_req.bound = bound;
397         req.alloc_req.contig = contig;
398         req.alloc_req.flags = flags;
399         req.alloc_req.elt_size = elt_size;
400         req.alloc_req.page_sz = pg_sz;
401         req.alloc_req.socket = socket;
402         req.alloc_req.heap = heap; /* it's in shared memory */
403
404         req_result = request_to_primary(&req);
405
406         if (req_result != 0)
407                 return -1;
408
409         if (req.result != REQ_RESULT_SUCCESS)
410                 return -1;
411
412         return 0;
413 }
414
415 static int
416 try_expand_heap(struct malloc_heap *heap, uint64_t pg_sz, size_t elt_size,
417                 int socket, unsigned int flags, size_t align, size_t bound,
418                 bool contig)
419 {
420         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
421         int ret;
422
423         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
424
425         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
426                 ret = try_expand_heap_primary(heap, pg_sz, elt_size, socket,
427                                 flags, align, bound, contig);
428         } else {
429                 ret = try_expand_heap_secondary(heap, pg_sz, elt_size, socket,
430                                 flags, align, bound, contig);
431         }
432
433         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
434         return ret;
435 }
436
437 static int
438 compare_pagesz(const void *a, const void *b)
439 {
440         const struct rte_memseg_list * const*mpa = a;
441         const struct rte_memseg_list * const*mpb = b;
442         const struct rte_memseg_list *msla = *mpa;
443         const struct rte_memseg_list *mslb = *mpb;
444         uint64_t pg_sz_a = msla->page_sz;
445         uint64_t pg_sz_b = mslb->page_sz;
446
447         if (pg_sz_a < pg_sz_b)
448                 return -1;
449         if (pg_sz_a > pg_sz_b)
450                 return 1;
451         return 0;
452 }
453
454 static int
455 alloc_more_mem_on_socket(struct malloc_heap *heap, size_t size, int socket,
456                 unsigned int flags, size_t align, size_t bound, bool contig)
457 {
458         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
459         struct rte_memseg_list *requested_msls[RTE_MAX_MEMSEG_LISTS];
460         struct rte_memseg_list *other_msls[RTE_MAX_MEMSEG_LISTS];
461         uint64_t requested_pg_sz[RTE_MAX_MEMSEG_LISTS];
462         uint64_t other_pg_sz[RTE_MAX_MEMSEG_LISTS];
463         uint64_t prev_pg_sz;
464         int i, n_other_msls, n_other_pg_sz, n_requested_msls, n_requested_pg_sz;
465         bool size_hint = (flags & RTE_MEMZONE_SIZE_HINT_ONLY) > 0;
466         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
467         void *ret;
468
469         memset(requested_msls, 0, sizeof(requested_msls));
470         memset(other_msls, 0, sizeof(other_msls));
471         memset(requested_pg_sz, 0, sizeof(requested_pg_sz));
472         memset(other_pg_sz, 0, sizeof(other_pg_sz));
473
474         /*
475          * go through memseg list and take note of all the page sizes available,
476          * and if any of them were specifically requested by the user.
477          */
478         n_requested_msls = 0;
479         n_other_msls = 0;
480         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
481                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
482
483                 if (msl->socket_id != socket)
484                         continue;
485
486                 if (msl->base_va == NULL)
487                         continue;
488
489                 /* if pages of specific size were requested */
490                 if (size_flags != 0 && check_hugepage_sz(size_flags,
491                                 msl->page_sz))
492                         requested_msls[n_requested_msls++] = msl;
493                 else if (size_flags == 0 || size_hint)
494                         other_msls[n_other_msls++] = msl;
495         }
496
497         /* sort the lists, smallest first */
498         qsort(requested_msls, n_requested_msls, sizeof(requested_msls[0]),
499                         compare_pagesz);
500         qsort(other_msls, n_other_msls, sizeof(other_msls[0]),
501                         compare_pagesz);
502
503         /* now, extract page sizes we are supposed to try */
504         prev_pg_sz = 0;
505         n_requested_pg_sz = 0;
506         for (i = 0; i < n_requested_msls; i++) {
507                 uint64_t pg_sz = requested_msls[i]->page_sz;
508
509                 if (prev_pg_sz != pg_sz) {
510                         requested_pg_sz[n_requested_pg_sz++] = pg_sz;
511                         prev_pg_sz = pg_sz;
512                 }
513         }
514         prev_pg_sz = 0;
515         n_other_pg_sz = 0;
516         for (i = 0; i < n_other_msls; i++) {
517                 uint64_t pg_sz = other_msls[i]->page_sz;
518
519                 if (prev_pg_sz != pg_sz) {
520                         other_pg_sz[n_other_pg_sz++] = pg_sz;
521                         prev_pg_sz = pg_sz;
522                 }
523         }
524
525         /* finally, try allocating memory of specified page sizes, starting from
526          * the smallest sizes
527          */
528         for (i = 0; i < n_requested_pg_sz; i++) {
529                 uint64_t pg_sz = requested_pg_sz[i];
530
531                 /*
532                  * do not pass the size hint here, as user expects other page
533                  * sizes first, before resorting to best effort allocation.
534                  */
535                 if (!try_expand_heap(heap, pg_sz, size, socket, size_flags,
536                                 align, bound, contig))
537                         return 0;
538         }
539         if (n_other_pg_sz == 0)
540                 return -1;
541
542         /* now, check if we can reserve anything with size hint */
543         ret = find_suitable_element(heap, size, flags, align, bound, contig);
544         if (ret != NULL)
545                 return 0;
546
547         /*
548          * we still couldn't reserve memory, so try expanding heap with other
549          * page sizes, if there are any
550          */
551         for (i = 0; i < n_other_pg_sz; i++) {
552                 uint64_t pg_sz = other_pg_sz[i];
553
554                 if (!try_expand_heap(heap, pg_sz, size, socket, flags,
555                                 align, bound, contig))
556                         return 0;
557         }
558         return -1;
559 }
560
561 /* this will try lower page sizes first */
562 static void *
563 heap_alloc_on_socket(const char *type, size_t size, int socket,
564                 unsigned int flags, size_t align, size_t bound, bool contig)
565 {
566         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
567         struct malloc_heap *heap = &mcfg->malloc_heaps[socket];
568         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
569         void *ret;
570
571         rte_spinlock_lock(&(heap->lock));
572
573         align = align == 0 ? 1 : align;
574
575         /* for legacy mode, try once and with all flags */
576         if (internal_config.legacy_mem) {
577                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
578                 goto alloc_unlock;
579         }
580
581         /*
582          * we do not pass the size hint here, because even if allocation fails,
583          * we may still be able to allocate memory from appropriate page sizes,
584          * we just need to request more memory first.
585          */
586         ret = heap_alloc(heap, type, size, size_flags, align, bound, contig);
587         if (ret != NULL)
588                 goto alloc_unlock;
589
590         if (!alloc_more_mem_on_socket(heap, size, socket, flags, align, bound,
591                         contig)) {
592                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
593
594                 /* this should have succeeded */
595                 if (ret == NULL)
596                         RTE_LOG(ERR, EAL, "Error allocating from heap\n");
597         }
598 alloc_unlock:
599         rte_spinlock_unlock(&(heap->lock));
600         return ret;
601 }
602
603 void *
604 malloc_heap_alloc(const char *type, size_t size, int socket_arg,
605                 unsigned int flags, size_t align, size_t bound, bool contig)
606 {
607         int socket, i, cur_socket;
608         void *ret;
609
610         /* return NULL if size is 0 or alignment is not power-of-2 */
611         if (size == 0 || (align && !rte_is_power_of_2(align)))
612                 return NULL;
613
614         if (!rte_eal_has_hugepages())
615                 socket_arg = SOCKET_ID_ANY;
616
617         if (socket_arg == SOCKET_ID_ANY)
618                 socket = malloc_get_numa_socket();
619         else
620                 socket = socket_arg;
621
622         /* Check socket parameter */
623         if (socket >= RTE_MAX_NUMA_NODES)
624                 return NULL;
625
626         ret = heap_alloc_on_socket(type, size, socket, flags, align, bound,
627                         contig);
628         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
629                 return ret;
630
631         /* try other heaps */
632         for (i = 0; i < (int) rte_socket_count(); i++) {
633                 cur_socket = rte_socket_id_by_idx(i);
634                 if (cur_socket == socket)
635                         continue;
636                 ret = heap_alloc_on_socket(type, size, cur_socket, flags,
637                                 align, bound, contig);
638                 if (ret != NULL)
639                         return ret;
640         }
641         return NULL;
642 }
643
644 static void *
645 heap_alloc_biggest_on_socket(const char *type, int socket, unsigned int flags,
646                 size_t align, bool contig)
647 {
648         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
649         struct malloc_heap *heap = &mcfg->malloc_heaps[socket];
650         void *ret;
651
652         rte_spinlock_lock(&(heap->lock));
653
654         align = align == 0 ? 1 : align;
655
656         ret = heap_alloc_biggest(heap, type, flags, align, contig);
657
658         rte_spinlock_unlock(&(heap->lock));
659
660         return ret;
661 }
662
663 void *
664 malloc_heap_alloc_biggest(const char *type, int socket_arg, unsigned int flags,
665                 size_t align, bool contig)
666 {
667         int socket, i, cur_socket;
668         void *ret;
669
670         /* return NULL if align is not power-of-2 */
671         if ((align && !rte_is_power_of_2(align)))
672                 return NULL;
673
674         if (!rte_eal_has_hugepages())
675                 socket_arg = SOCKET_ID_ANY;
676
677         if (socket_arg == SOCKET_ID_ANY)
678                 socket = malloc_get_numa_socket();
679         else
680                 socket = socket_arg;
681
682         /* Check socket parameter */
683         if (socket >= RTE_MAX_NUMA_NODES)
684                 return NULL;
685
686         ret = heap_alloc_biggest_on_socket(type, socket, flags, align,
687                         contig);
688         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
689                 return ret;
690
691         /* try other heaps */
692         for (i = 0; i < (int) rte_socket_count(); i++) {
693                 cur_socket = rte_socket_id_by_idx(i);
694                 if (cur_socket == socket)
695                         continue;
696                 ret = heap_alloc_biggest_on_socket(type, cur_socket, flags,
697                                 align, contig);
698                 if (ret != NULL)
699                         return ret;
700         }
701         return NULL;
702 }
703
704 /* this function is exposed in malloc_mp.h */
705 int
706 malloc_heap_free_pages(void *aligned_start, size_t aligned_len)
707 {
708         int n_segs, seg_idx, max_seg_idx;
709         struct rte_memseg_list *msl;
710         size_t page_sz;
711
712         msl = rte_mem_virt2memseg_list(aligned_start);
713         if (msl == NULL)
714                 return -1;
715
716         page_sz = (size_t)msl->page_sz;
717         n_segs = aligned_len / page_sz;
718         seg_idx = RTE_PTR_DIFF(aligned_start, msl->base_va) / page_sz;
719         max_seg_idx = seg_idx + n_segs;
720
721         for (; seg_idx < max_seg_idx; seg_idx++) {
722                 struct rte_memseg *ms;
723
724                 ms = rte_fbarray_get(&msl->memseg_arr, seg_idx);
725                 eal_memalloc_free_seg(ms);
726         }
727         return 0;
728 }
729
730 int
731 malloc_heap_free(struct malloc_elem *elem)
732 {
733         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
734         struct malloc_heap *heap;
735         void *start, *aligned_start, *end, *aligned_end;
736         size_t len, aligned_len, page_sz;
737         struct rte_memseg_list *msl;
738         unsigned int i, n_segs, before_space, after_space;
739         int ret;
740
741         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
742                 return -1;
743
744         /* elem may be merged with previous element, so keep heap address */
745         heap = elem->heap;
746         msl = elem->msl;
747         page_sz = (size_t)msl->page_sz;
748
749         rte_spinlock_lock(&(heap->lock));
750
751         /* mark element as free */
752         elem->state = ELEM_FREE;
753
754         elem = malloc_elem_free(elem);
755
756         /* anything after this is a bonus */
757         ret = 0;
758
759         /* ...of which we can't avail if we are in legacy mode */
760         if (internal_config.legacy_mem)
761                 goto free_unlock;
762
763         /* check if we can free any memory back to the system */
764         if (elem->size < page_sz)
765                 goto free_unlock;
766
767         /* probably, but let's make sure, as we may not be using up full page */
768         start = elem;
769         len = elem->size;
770         aligned_start = RTE_PTR_ALIGN_CEIL(start, page_sz);
771         end = RTE_PTR_ADD(elem, len);
772         aligned_end = RTE_PTR_ALIGN_FLOOR(end, page_sz);
773
774         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
775
776         /* can't free anything */
777         if (aligned_len < page_sz)
778                 goto free_unlock;
779
780         /* we can free something. however, some of these pages may be marked as
781          * unfreeable, so also check that as well
782          */
783         n_segs = aligned_len / page_sz;
784         for (i = 0; i < n_segs; i++) {
785                 const struct rte_memseg *tmp =
786                                 rte_mem_virt2memseg(aligned_start, msl);
787
788                 if (tmp->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
789                         /* this is an unfreeable segment, so move start */
790                         aligned_start = RTE_PTR_ADD(tmp->addr, tmp->len);
791                 }
792         }
793
794         /* recalculate length and number of segments */
795         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
796         n_segs = aligned_len / page_sz;
797
798         /* check if we can still free some pages */
799         if (n_segs == 0)
800                 goto free_unlock;
801
802         /* We're not done yet. We also have to check if by freeing space we will
803          * be leaving free elements that are too small to store new elements.
804          * Check if we have enough space in the beginning and at the end, or if
805          * start/end are exactly page aligned.
806          */
807         before_space = RTE_PTR_DIFF(aligned_start, elem);
808         after_space = RTE_PTR_DIFF(end, aligned_end);
809         if (before_space != 0 &&
810                         before_space < MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
811                 /* There is not enough space before start, but we may be able to
812                  * move the start forward by one page.
813                  */
814                 if (n_segs == 1)
815                         goto free_unlock;
816
817                 /* move start */
818                 aligned_start = RTE_PTR_ADD(aligned_start, page_sz);
819                 aligned_len -= page_sz;
820                 n_segs--;
821         }
822         if (after_space != 0 && after_space <
823                         MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
824                 /* There is not enough space after end, but we may be able to
825                  * move the end backwards by one page.
826                  */
827                 if (n_segs == 1)
828                         goto free_unlock;
829
830                 /* move end */
831                 aligned_end = RTE_PTR_SUB(aligned_end, page_sz);
832                 aligned_len -= page_sz;
833                 n_segs--;
834         }
835
836         /* now we can finally free us some pages */
837
838         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
839
840         /*
841          * we allow secondary processes to clear the heap of this allocated
842          * memory because it is safe to do so, as even if notifications about
843          * unmapped pages don't make it to other processes, heap is shared
844          * across all processes, and will become empty of this memory anyway,
845          * and nothing can allocate it back unless primary process will be able
846          * to deliver allocation message to every single running process.
847          */
848
849         malloc_elem_free_list_remove(elem);
850
851         malloc_elem_hide_region(elem, (void *) aligned_start, aligned_len);
852
853         heap->total_size -= aligned_len;
854
855         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
856                 /* notify user about changes in memory map */
857                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
858                                 aligned_start, aligned_len);
859
860                 /* don't care if any of this fails */
861                 malloc_heap_free_pages(aligned_start, aligned_len);
862
863                 request_sync();
864         } else {
865                 struct malloc_mp_req req;
866
867                 memset(&req, 0, sizeof(req));
868
869                 req.t = REQ_TYPE_FREE;
870                 req.free_req.addr = aligned_start;
871                 req.free_req.len = aligned_len;
872
873                 /*
874                  * we request primary to deallocate pages, but we don't do it
875                  * in this thread. instead, we notify primary that we would like
876                  * to deallocate pages, and this process will receive another
877                  * request (in parallel) that will do it for us on another
878                  * thread.
879                  *
880                  * we also don't really care if this succeeds - the data is
881                  * already removed from the heap, so it is, for all intents and
882                  * purposes, hidden from the rest of DPDK even if some other
883                  * process (including this one) may have these pages mapped.
884                  *
885                  * notifications about deallocated memory happen during sync.
886                  */
887                 request_to_primary(&req);
888         }
889
890         RTE_LOG(DEBUG, EAL, "Heap on socket %d was shrunk by %zdMB\n",
891                 msl->socket_id, aligned_len >> 20ULL);
892
893         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
894 free_unlock:
895         rte_spinlock_unlock(&(heap->lock));
896         return ret;
897 }
898
899 int
900 malloc_heap_resize(struct malloc_elem *elem, size_t size)
901 {
902         int ret;
903
904         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
905                 return -1;
906
907         rte_spinlock_lock(&(elem->heap->lock));
908
909         ret = malloc_elem_resize(elem, size);
910
911         rte_spinlock_unlock(&(elem->heap->lock));
912
913         return ret;
914 }
915
916 /*
917  * Function to retrieve data for heap on given socket
918  */
919 int
920 malloc_heap_get_stats(struct malloc_heap *heap,
921                 struct rte_malloc_socket_stats *socket_stats)
922 {
923         size_t idx;
924         struct malloc_elem *elem;
925
926         rte_spinlock_lock(&heap->lock);
927
928         /* Initialise variables for heap */
929         socket_stats->free_count = 0;
930         socket_stats->heap_freesz_bytes = 0;
931         socket_stats->greatest_free_size = 0;
932
933         /* Iterate through free list */
934         for (idx = 0; idx < RTE_HEAP_NUM_FREELISTS; idx++) {
935                 for (elem = LIST_FIRST(&heap->free_head[idx]);
936                         !!elem; elem = LIST_NEXT(elem, free_list))
937                 {
938                         socket_stats->free_count++;
939                         socket_stats->heap_freesz_bytes += elem->size;
940                         if (elem->size > socket_stats->greatest_free_size)
941                                 socket_stats->greatest_free_size = elem->size;
942                 }
943         }
944         /* Get stats on overall heap and allocated memory on this heap */
945         socket_stats->heap_totalsz_bytes = heap->total_size;
946         socket_stats->heap_allocsz_bytes = (socket_stats->heap_totalsz_bytes -
947                         socket_stats->heap_freesz_bytes);
948         socket_stats->alloc_count = heap->alloc_count;
949
950         rte_spinlock_unlock(&heap->lock);
951         return 0;
952 }
953
954 /*
955  * Function to retrieve data for heap on given socket
956  */
957 void
958 malloc_heap_dump(struct malloc_heap *heap, FILE *f)
959 {
960         struct malloc_elem *elem;
961
962         rte_spinlock_lock(&heap->lock);
963
964         fprintf(f, "Heap size: 0x%zx\n", heap->total_size);
965         fprintf(f, "Heap alloc count: %u\n", heap->alloc_count);
966
967         elem = heap->first;
968         while (elem) {
969                 malloc_elem_dump(elem, f);
970                 elem = elem->next;
971         }
972
973         rte_spinlock_unlock(&heap->lock);
974 }
975
976 int
977 rte_eal_malloc_heap_init(void)
978 {
979         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
980
981         if (register_mp_requests()) {
982                 RTE_LOG(ERR, EAL, "Couldn't register malloc multiprocess actions\n");
983                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
984                 return -1;
985         }
986
987         /* unlock mem hotplug here. it's safe for primary as no requests can
988          * even come before primary itself is fully initialized, and secondaries
989          * do not need to initialize the heap.
990          */
991         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
992
993         /* secondary process does not need to initialize anything */
994         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
995                 return 0;
996
997         /* add all IOVA-contiguous areas to the heap */
998         return rte_memseg_contig_walk(malloc_add_seg, NULL);
999 }