malloc: fix potential null pointer dereference
[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         if (ms == NULL)
330                 return -1;
331         memset(ms, 0, sizeof(*ms) * n_segs);
332
333         elem = alloc_pages_on_heap(heap, pg_sz, elt_size, socket, flags, align,
334                         bound, contig, ms, n_segs);
335
336         if (elem == NULL)
337                 goto free_ms;
338
339         map_addr = ms[0]->addr;
340
341         /* notify user about changes in memory map */
342         eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC, map_addr, alloc_sz);
343
344         /* notify other processes that this has happened */
345         if (request_sync()) {
346                 /* we couldn't ensure all processes have mapped memory,
347                  * so free it back and notify everyone that it's been
348                  * freed back.
349                  *
350                  * technically, we could've avoided adding memory addresses to
351                  * the map, but that would've led to inconsistent behavior
352                  * between primary and secondary processes, as those get
353                  * callbacks during sync. therefore, force primary process to
354                  * do alloc-and-rollback syncs as well.
355                  */
356                 callback_triggered = true;
357                 goto free_elem;
358         }
359         heap->total_size += alloc_sz;
360
361         RTE_LOG(DEBUG, EAL, "Heap on socket %d was expanded by %zdMB\n",
362                 socket, alloc_sz >> 20ULL);
363
364         free(ms);
365
366         return 0;
367
368 free_elem:
369         if (callback_triggered)
370                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
371                                 map_addr, alloc_sz);
372
373         rollback_expand_heap(ms, n_segs, elem, map_addr, alloc_sz);
374
375         request_sync();
376 free_ms:
377         free(ms);
378
379         return -1;
380 }
381
382 static int
383 try_expand_heap_secondary(struct malloc_heap *heap, uint64_t pg_sz,
384                 size_t elt_size, int socket, unsigned int flags, size_t align,
385                 size_t bound, bool contig)
386 {
387         struct malloc_mp_req req;
388         int req_result;
389
390         memset(&req, 0, sizeof(req));
391
392         req.t = REQ_TYPE_ALLOC;
393         req.alloc_req.align = align;
394         req.alloc_req.bound = bound;
395         req.alloc_req.contig = contig;
396         req.alloc_req.flags = flags;
397         req.alloc_req.elt_size = elt_size;
398         req.alloc_req.page_sz = pg_sz;
399         req.alloc_req.socket = socket;
400         req.alloc_req.heap = heap; /* it's in shared memory */
401
402         req_result = request_to_primary(&req);
403
404         if (req_result != 0)
405                 return -1;
406
407         if (req.result != REQ_RESULT_SUCCESS)
408                 return -1;
409
410         return 0;
411 }
412
413 static int
414 try_expand_heap(struct malloc_heap *heap, uint64_t pg_sz, size_t elt_size,
415                 int socket, unsigned int flags, size_t align, size_t bound,
416                 bool contig)
417 {
418         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
419         int ret;
420
421         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
422
423         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
424                 ret = try_expand_heap_primary(heap, pg_sz, elt_size, socket,
425                                 flags, align, bound, contig);
426         } else {
427                 ret = try_expand_heap_secondary(heap, pg_sz, elt_size, socket,
428                                 flags, align, bound, contig);
429         }
430
431         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
432         return ret;
433 }
434
435 static int
436 compare_pagesz(const void *a, const void *b)
437 {
438         const struct rte_memseg_list * const*mpa = a;
439         const struct rte_memseg_list * const*mpb = b;
440         const struct rte_memseg_list *msla = *mpa;
441         const struct rte_memseg_list *mslb = *mpb;
442         uint64_t pg_sz_a = msla->page_sz;
443         uint64_t pg_sz_b = mslb->page_sz;
444
445         if (pg_sz_a < pg_sz_b)
446                 return -1;
447         if (pg_sz_a > pg_sz_b)
448                 return 1;
449         return 0;
450 }
451
452 static int
453 alloc_more_mem_on_socket(struct malloc_heap *heap, size_t size, int socket,
454                 unsigned int flags, size_t align, size_t bound, bool contig)
455 {
456         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
457         struct rte_memseg_list *requested_msls[RTE_MAX_MEMSEG_LISTS];
458         struct rte_memseg_list *other_msls[RTE_MAX_MEMSEG_LISTS];
459         uint64_t requested_pg_sz[RTE_MAX_MEMSEG_LISTS];
460         uint64_t other_pg_sz[RTE_MAX_MEMSEG_LISTS];
461         uint64_t prev_pg_sz;
462         int i, n_other_msls, n_other_pg_sz, n_requested_msls, n_requested_pg_sz;
463         bool size_hint = (flags & RTE_MEMZONE_SIZE_HINT_ONLY) > 0;
464         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
465         void *ret;
466
467         memset(requested_msls, 0, sizeof(requested_msls));
468         memset(other_msls, 0, sizeof(other_msls));
469         memset(requested_pg_sz, 0, sizeof(requested_pg_sz));
470         memset(other_pg_sz, 0, sizeof(other_pg_sz));
471
472         /*
473          * go through memseg list and take note of all the page sizes available,
474          * and if any of them were specifically requested by the user.
475          */
476         n_requested_msls = 0;
477         n_other_msls = 0;
478         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
479                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
480
481                 if (msl->socket_id != socket)
482                         continue;
483
484                 if (msl->base_va == NULL)
485                         continue;
486
487                 /* if pages of specific size were requested */
488                 if (size_flags != 0 && check_hugepage_sz(size_flags,
489                                 msl->page_sz))
490                         requested_msls[n_requested_msls++] = msl;
491                 else if (size_flags == 0 || size_hint)
492                         other_msls[n_other_msls++] = msl;
493         }
494
495         /* sort the lists, smallest first */
496         qsort(requested_msls, n_requested_msls, sizeof(requested_msls[0]),
497                         compare_pagesz);
498         qsort(other_msls, n_other_msls, sizeof(other_msls[0]),
499                         compare_pagesz);
500
501         /* now, extract page sizes we are supposed to try */
502         prev_pg_sz = 0;
503         n_requested_pg_sz = 0;
504         for (i = 0; i < n_requested_msls; i++) {
505                 uint64_t pg_sz = requested_msls[i]->page_sz;
506
507                 if (prev_pg_sz != pg_sz) {
508                         requested_pg_sz[n_requested_pg_sz++] = pg_sz;
509                         prev_pg_sz = pg_sz;
510                 }
511         }
512         prev_pg_sz = 0;
513         n_other_pg_sz = 0;
514         for (i = 0; i < n_other_msls; i++) {
515                 uint64_t pg_sz = other_msls[i]->page_sz;
516
517                 if (prev_pg_sz != pg_sz) {
518                         other_pg_sz[n_other_pg_sz++] = pg_sz;
519                         prev_pg_sz = pg_sz;
520                 }
521         }
522
523         /* finally, try allocating memory of specified page sizes, starting from
524          * the smallest sizes
525          */
526         for (i = 0; i < n_requested_pg_sz; i++) {
527                 uint64_t pg_sz = requested_pg_sz[i];
528
529                 /*
530                  * do not pass the size hint here, as user expects other page
531                  * sizes first, before resorting to best effort allocation.
532                  */
533                 if (!try_expand_heap(heap, pg_sz, size, socket, size_flags,
534                                 align, bound, contig))
535                         return 0;
536         }
537         if (n_other_pg_sz == 0)
538                 return -1;
539
540         /* now, check if we can reserve anything with size hint */
541         ret = find_suitable_element(heap, size, flags, align, bound, contig);
542         if (ret != NULL)
543                 return 0;
544
545         /*
546          * we still couldn't reserve memory, so try expanding heap with other
547          * page sizes, if there are any
548          */
549         for (i = 0; i < n_other_pg_sz; i++) {
550                 uint64_t pg_sz = other_pg_sz[i];
551
552                 if (!try_expand_heap(heap, pg_sz, size, socket, flags,
553                                 align, bound, contig))
554                         return 0;
555         }
556         return -1;
557 }
558
559 /* this will try lower page sizes first */
560 static void *
561 heap_alloc_on_socket(const char *type, size_t size, int socket,
562                 unsigned int flags, size_t align, size_t bound, bool contig)
563 {
564         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
565         struct malloc_heap *heap = &mcfg->malloc_heaps[socket];
566         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
567         void *ret;
568
569         rte_spinlock_lock(&(heap->lock));
570
571         align = align == 0 ? 1 : align;
572
573         /* for legacy mode, try once and with all flags */
574         if (internal_config.legacy_mem) {
575                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
576                 goto alloc_unlock;
577         }
578
579         /*
580          * we do not pass the size hint here, because even if allocation fails,
581          * we may still be able to allocate memory from appropriate page sizes,
582          * we just need to request more memory first.
583          */
584         ret = heap_alloc(heap, type, size, size_flags, align, bound, contig);
585         if (ret != NULL)
586                 goto alloc_unlock;
587
588         if (!alloc_more_mem_on_socket(heap, size, socket, flags, align, bound,
589                         contig)) {
590                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
591
592                 /* this should have succeeded */
593                 if (ret == NULL)
594                         RTE_LOG(ERR, EAL, "Error allocating from heap\n");
595         }
596 alloc_unlock:
597         rte_spinlock_unlock(&(heap->lock));
598         return ret;
599 }
600
601 void *
602 malloc_heap_alloc(const char *type, size_t size, int socket_arg,
603                 unsigned int flags, size_t align, size_t bound, bool contig)
604 {
605         int socket, i, cur_socket;
606         void *ret;
607
608         /* return NULL if size is 0 or alignment is not power-of-2 */
609         if (size == 0 || (align && !rte_is_power_of_2(align)))
610                 return NULL;
611
612         if (!rte_eal_has_hugepages())
613                 socket_arg = SOCKET_ID_ANY;
614
615         if (socket_arg == SOCKET_ID_ANY)
616                 socket = malloc_get_numa_socket();
617         else
618                 socket = socket_arg;
619
620         /* Check socket parameter */
621         if (socket >= RTE_MAX_NUMA_NODES)
622                 return NULL;
623
624         ret = heap_alloc_on_socket(type, size, socket, flags, align, bound,
625                         contig);
626         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
627                 return ret;
628
629         /* try other heaps */
630         for (i = 0; i < (int) rte_socket_count(); i++) {
631                 cur_socket = rte_socket_id_by_idx(i);
632                 if (cur_socket == socket)
633                         continue;
634                 ret = heap_alloc_on_socket(type, size, cur_socket, flags,
635                                 align, bound, contig);
636                 if (ret != NULL)
637                         return ret;
638         }
639         return NULL;
640 }
641
642 static void *
643 heap_alloc_biggest_on_socket(const char *type, int socket, unsigned int flags,
644                 size_t align, bool contig)
645 {
646         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
647         struct malloc_heap *heap = &mcfg->malloc_heaps[socket];
648         void *ret;
649
650         rte_spinlock_lock(&(heap->lock));
651
652         align = align == 0 ? 1 : align;
653
654         ret = heap_alloc_biggest(heap, type, flags, align, contig);
655
656         rte_spinlock_unlock(&(heap->lock));
657
658         return ret;
659 }
660
661 void *
662 malloc_heap_alloc_biggest(const char *type, int socket_arg, unsigned int flags,
663                 size_t align, bool contig)
664 {
665         int socket, i, cur_socket;
666         void *ret;
667
668         /* return NULL if align is not power-of-2 */
669         if ((align && !rte_is_power_of_2(align)))
670                 return NULL;
671
672         if (!rte_eal_has_hugepages())
673                 socket_arg = SOCKET_ID_ANY;
674
675         if (socket_arg == SOCKET_ID_ANY)
676                 socket = malloc_get_numa_socket();
677         else
678                 socket = socket_arg;
679
680         /* Check socket parameter */
681         if (socket >= RTE_MAX_NUMA_NODES)
682                 return NULL;
683
684         ret = heap_alloc_biggest_on_socket(type, socket, flags, align,
685                         contig);
686         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
687                 return ret;
688
689         /* try other heaps */
690         for (i = 0; i < (int) rte_socket_count(); i++) {
691                 cur_socket = rte_socket_id_by_idx(i);
692                 if (cur_socket == socket)
693                         continue;
694                 ret = heap_alloc_biggest_on_socket(type, cur_socket, flags,
695                                 align, contig);
696                 if (ret != NULL)
697                         return ret;
698         }
699         return NULL;
700 }
701
702 /* this function is exposed in malloc_mp.h */
703 int
704 malloc_heap_free_pages(void *aligned_start, size_t aligned_len)
705 {
706         int n_segs, seg_idx, max_seg_idx;
707         struct rte_memseg_list *msl;
708         size_t page_sz;
709
710         msl = rte_mem_virt2memseg_list(aligned_start);
711         if (msl == NULL)
712                 return -1;
713
714         page_sz = (size_t)msl->page_sz;
715         n_segs = aligned_len / page_sz;
716         seg_idx = RTE_PTR_DIFF(aligned_start, msl->base_va) / page_sz;
717         max_seg_idx = seg_idx + n_segs;
718
719         for (; seg_idx < max_seg_idx; seg_idx++) {
720                 struct rte_memseg *ms;
721
722                 ms = rte_fbarray_get(&msl->memseg_arr, seg_idx);
723                 eal_memalloc_free_seg(ms);
724         }
725         return 0;
726 }
727
728 int
729 malloc_heap_free(struct malloc_elem *elem)
730 {
731         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
732         struct malloc_heap *heap;
733         void *start, *aligned_start, *end, *aligned_end;
734         size_t len, aligned_len, page_sz;
735         struct rte_memseg_list *msl;
736         unsigned int i, n_segs, before_space, after_space;
737         int ret;
738
739         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
740                 return -1;
741
742         /* elem may be merged with previous element, so keep heap address */
743         heap = elem->heap;
744         msl = elem->msl;
745         page_sz = (size_t)msl->page_sz;
746
747         rte_spinlock_lock(&(heap->lock));
748
749         /* mark element as free */
750         elem->state = ELEM_FREE;
751
752         elem = malloc_elem_free(elem);
753
754         /* anything after this is a bonus */
755         ret = 0;
756
757         /* ...of which we can't avail if we are in legacy mode */
758         if (internal_config.legacy_mem)
759                 goto free_unlock;
760
761         /* check if we can free any memory back to the system */
762         if (elem->size < page_sz)
763                 goto free_unlock;
764
765         /* probably, but let's make sure, as we may not be using up full page */
766         start = elem;
767         len = elem->size;
768         aligned_start = RTE_PTR_ALIGN_CEIL(start, page_sz);
769         end = RTE_PTR_ADD(elem, len);
770         aligned_end = RTE_PTR_ALIGN_FLOOR(end, page_sz);
771
772         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
773
774         /* can't free anything */
775         if (aligned_len < page_sz)
776                 goto free_unlock;
777
778         /* we can free something. however, some of these pages may be marked as
779          * unfreeable, so also check that as well
780          */
781         n_segs = aligned_len / page_sz;
782         for (i = 0; i < n_segs; i++) {
783                 const struct rte_memseg *tmp =
784                                 rte_mem_virt2memseg(aligned_start, msl);
785
786                 if (tmp->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
787                         /* this is an unfreeable segment, so move start */
788                         aligned_start = RTE_PTR_ADD(tmp->addr, tmp->len);
789                 }
790         }
791
792         /* recalculate length and number of segments */
793         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
794         n_segs = aligned_len / page_sz;
795
796         /* check if we can still free some pages */
797         if (n_segs == 0)
798                 goto free_unlock;
799
800         /* We're not done yet. We also have to check if by freeing space we will
801          * be leaving free elements that are too small to store new elements.
802          * Check if we have enough space in the beginning and at the end, or if
803          * start/end are exactly page aligned.
804          */
805         before_space = RTE_PTR_DIFF(aligned_start, elem);
806         after_space = RTE_PTR_DIFF(end, aligned_end);
807         if (before_space != 0 &&
808                         before_space < MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
809                 /* There is not enough space before start, but we may be able to
810                  * move the start forward by one page.
811                  */
812                 if (n_segs == 1)
813                         goto free_unlock;
814
815                 /* move start */
816                 aligned_start = RTE_PTR_ADD(aligned_start, page_sz);
817                 aligned_len -= page_sz;
818                 n_segs--;
819         }
820         if (after_space != 0 && after_space <
821                         MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
822                 /* There is not enough space after end, but we may be able to
823                  * move the end backwards by one page.
824                  */
825                 if (n_segs == 1)
826                         goto free_unlock;
827
828                 /* move end */
829                 aligned_end = RTE_PTR_SUB(aligned_end, page_sz);
830                 aligned_len -= page_sz;
831                 n_segs--;
832         }
833
834         /* now we can finally free us some pages */
835
836         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
837
838         /*
839          * we allow secondary processes to clear the heap of this allocated
840          * memory because it is safe to do so, as even if notifications about
841          * unmapped pages don't make it to other processes, heap is shared
842          * across all processes, and will become empty of this memory anyway,
843          * and nothing can allocate it back unless primary process will be able
844          * to deliver allocation message to every single running process.
845          */
846
847         malloc_elem_free_list_remove(elem);
848
849         malloc_elem_hide_region(elem, (void *) aligned_start, aligned_len);
850
851         heap->total_size -= aligned_len;
852
853         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
854                 /* notify user about changes in memory map */
855                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
856                                 aligned_start, aligned_len);
857
858                 /* don't care if any of this fails */
859                 malloc_heap_free_pages(aligned_start, aligned_len);
860
861                 request_sync();
862         } else {
863                 struct malloc_mp_req req;
864
865                 memset(&req, 0, sizeof(req));
866
867                 req.t = REQ_TYPE_FREE;
868                 req.free_req.addr = aligned_start;
869                 req.free_req.len = aligned_len;
870
871                 /*
872                  * we request primary to deallocate pages, but we don't do it
873                  * in this thread. instead, we notify primary that we would like
874                  * to deallocate pages, and this process will receive another
875                  * request (in parallel) that will do it for us on another
876                  * thread.
877                  *
878                  * we also don't really care if this succeeds - the data is
879                  * already removed from the heap, so it is, for all intents and
880                  * purposes, hidden from the rest of DPDK even if some other
881                  * process (including this one) may have these pages mapped.
882                  *
883                  * notifications about deallocated memory happen during sync.
884                  */
885                 request_to_primary(&req);
886         }
887
888         RTE_LOG(DEBUG, EAL, "Heap on socket %d was shrunk by %zdMB\n",
889                 msl->socket_id, aligned_len >> 20ULL);
890
891         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
892 free_unlock:
893         rte_spinlock_unlock(&(heap->lock));
894         return ret;
895 }
896
897 int
898 malloc_heap_resize(struct malloc_elem *elem, size_t size)
899 {
900         int ret;
901
902         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
903                 return -1;
904
905         rte_spinlock_lock(&(elem->heap->lock));
906
907         ret = malloc_elem_resize(elem, size);
908
909         rte_spinlock_unlock(&(elem->heap->lock));
910
911         return ret;
912 }
913
914 /*
915  * Function to retrieve data for heap on given socket
916  */
917 int
918 malloc_heap_get_stats(struct malloc_heap *heap,
919                 struct rte_malloc_socket_stats *socket_stats)
920 {
921         size_t idx;
922         struct malloc_elem *elem;
923
924         rte_spinlock_lock(&heap->lock);
925
926         /* Initialise variables for heap */
927         socket_stats->free_count = 0;
928         socket_stats->heap_freesz_bytes = 0;
929         socket_stats->greatest_free_size = 0;
930
931         /* Iterate through free list */
932         for (idx = 0; idx < RTE_HEAP_NUM_FREELISTS; idx++) {
933                 for (elem = LIST_FIRST(&heap->free_head[idx]);
934                         !!elem; elem = LIST_NEXT(elem, free_list))
935                 {
936                         socket_stats->free_count++;
937                         socket_stats->heap_freesz_bytes += elem->size;
938                         if (elem->size > socket_stats->greatest_free_size)
939                                 socket_stats->greatest_free_size = elem->size;
940                 }
941         }
942         /* Get stats on overall heap and allocated memory on this heap */
943         socket_stats->heap_totalsz_bytes = heap->total_size;
944         socket_stats->heap_allocsz_bytes = (socket_stats->heap_totalsz_bytes -
945                         socket_stats->heap_freesz_bytes);
946         socket_stats->alloc_count = heap->alloc_count;
947
948         rte_spinlock_unlock(&heap->lock);
949         return 0;
950 }
951
952 /*
953  * Function to retrieve data for heap on given socket
954  */
955 void
956 malloc_heap_dump(struct malloc_heap *heap, FILE *f)
957 {
958         struct malloc_elem *elem;
959
960         rte_spinlock_lock(&heap->lock);
961
962         fprintf(f, "Heap size: 0x%zx\n", heap->total_size);
963         fprintf(f, "Heap alloc count: %u\n", heap->alloc_count);
964
965         elem = heap->first;
966         while (elem) {
967                 malloc_elem_dump(elem, f);
968                 elem = elem->next;
969         }
970
971         rte_spinlock_unlock(&heap->lock);
972 }
973
974 int
975 rte_eal_malloc_heap_init(void)
976 {
977         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
978
979         if (register_mp_requests()) {
980                 RTE_LOG(ERR, EAL, "Couldn't register malloc multiprocess actions\n");
981                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
982                 return -1;
983         }
984
985         /* unlock mem hotplug here. it's safe for primary as no requests can
986          * even come before primary itself is fully initialized, and secondaries
987          * do not need to initialize the heap.
988          */
989         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
990
991         /* secondary process does not need to initialize anything */
992         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
993                 return 0;
994
995         /* add all IOVA-contiguous areas to the heap */
996         return rte_memseg_contig_walk(malloc_add_seg, NULL);
997 }