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