363f306cc72d560ca15399ecbf320a133a33a574
[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 ((flags & RTE_MEMZONE_SIZE_HINT_ONLY) == 0 &&
196                                         !check_hugepage_sz(flags,
197                                                 elem->msl->page_sz))
198                                 continue;
199                         if (contig) {
200                                 cur_size =
201                                         malloc_elem_find_max_iova_contig(elem,
202                                                         align);
203                         } else {
204                                 void *data_start = RTE_PTR_ADD(elem,
205                                                 MALLOC_ELEM_HEADER_LEN);
206                                 void *data_end = RTE_PTR_ADD(elem, elem->size -
207                                                 MALLOC_ELEM_TRAILER_LEN);
208                                 void *aligned = RTE_PTR_ALIGN_CEIL(data_start,
209                                                 align);
210                                 /* check if aligned data start is beyond end */
211                                 if (aligned >= data_end)
212                                         continue;
213                                 cur_size = RTE_PTR_DIFF(data_end, aligned);
214                         }
215                         if (cur_size > max_size) {
216                                 max_size = cur_size;
217                                 max_elem = elem;
218                         }
219                 }
220         }
221
222         *size = max_size;
223         return max_elem;
224 }
225
226 /*
227  * Main function to allocate a block of memory from the heap.
228  * It locks the free list, scans it, and adds a new memseg if the
229  * scan fails. Once the new memseg is added, it re-scans and should return
230  * the new element after releasing the lock.
231  */
232 static void *
233 heap_alloc(struct malloc_heap *heap, const char *type __rte_unused, size_t size,
234                 unsigned int flags, size_t align, size_t bound, bool contig)
235 {
236         struct malloc_elem *elem;
237
238         size = RTE_CACHE_LINE_ROUNDUP(size);
239         align = RTE_CACHE_LINE_ROUNDUP(align);
240
241         elem = find_suitable_element(heap, size, flags, align, bound, contig);
242         if (elem != NULL) {
243                 elem = malloc_elem_alloc(elem, size, align, bound, contig);
244
245                 /* increase heap's count of allocated elements */
246                 heap->alloc_count++;
247         }
248
249         return elem == NULL ? NULL : (void *)(&elem[1]);
250 }
251
252 static void *
253 heap_alloc_biggest(struct malloc_heap *heap, const char *type __rte_unused,
254                 unsigned int flags, size_t align, bool contig)
255 {
256         struct malloc_elem *elem;
257         size_t size;
258
259         align = RTE_CACHE_LINE_ROUNDUP(align);
260
261         elem = find_biggest_element(heap, &size, flags, align, contig);
262         if (elem != NULL) {
263                 elem = malloc_elem_alloc(elem, size, align, 0, contig);
264
265                 /* increase heap's count of allocated elements */
266                 heap->alloc_count++;
267         }
268
269         return elem == NULL ? NULL : (void *)(&elem[1]);
270 }
271
272 /* this function is exposed in malloc_mp.h */
273 void
274 rollback_expand_heap(struct rte_memseg **ms, int n_segs,
275                 struct malloc_elem *elem, void *map_addr, size_t map_len)
276 {
277         if (elem != NULL) {
278                 malloc_elem_free_list_remove(elem);
279                 malloc_elem_hide_region(elem, map_addr, map_len);
280         }
281
282         eal_memalloc_free_seg_bulk(ms, n_segs);
283 }
284
285 /* this function is exposed in malloc_mp.h */
286 struct malloc_elem *
287 alloc_pages_on_heap(struct malloc_heap *heap, uint64_t pg_sz, size_t elt_size,
288                 int socket, unsigned int flags, size_t align, size_t bound,
289                 bool contig, struct rte_memseg **ms, int n_segs)
290 {
291         struct rte_memseg_list *msl;
292         struct malloc_elem *elem = NULL;
293         size_t alloc_sz;
294         int allocd_pages;
295         void *ret, *map_addr;
296
297         alloc_sz = (size_t)pg_sz * n_segs;
298
299         /* first, check if we're allowed to allocate this memory */
300         if (eal_memalloc_mem_alloc_validate(socket,
301                         heap->total_size + alloc_sz) < 0) {
302                 RTE_LOG(DEBUG, EAL, "User has disallowed allocation\n");
303                 return NULL;
304         }
305
306         allocd_pages = eal_memalloc_alloc_seg_bulk(ms, n_segs, pg_sz,
307                         socket, true);
308
309         /* make sure we've allocated our pages... */
310         if (allocd_pages < 0)
311                 return NULL;
312
313         map_addr = ms[0]->addr;
314         msl = rte_mem_virt2memseg_list(map_addr);
315
316         /* check if we wanted contiguous memory but didn't get it */
317         if (contig && !eal_memalloc_is_contig(msl, map_addr, alloc_sz)) {
318                 RTE_LOG(DEBUG, EAL, "%s(): couldn't allocate physically contiguous space\n",
319                                 __func__);
320                 goto fail;
321         }
322
323         /* add newly minted memsegs to malloc heap */
324         elem = malloc_heap_add_memory(heap, msl, map_addr, alloc_sz);
325
326         /* try once more, as now we have allocated new memory */
327         ret = find_suitable_element(heap, elt_size, flags, align, bound,
328                         contig);
329
330         if (ret == NULL)
331                 goto fail;
332
333         return elem;
334
335 fail:
336         rollback_expand_heap(ms, n_segs, elem, map_addr, alloc_sz);
337         return NULL;
338 }
339
340 static int
341 try_expand_heap_primary(struct malloc_heap *heap, uint64_t pg_sz,
342                 size_t elt_size, int socket, unsigned int flags, size_t align,
343                 size_t bound, bool contig)
344 {
345         struct malloc_elem *elem;
346         struct rte_memseg **ms;
347         void *map_addr;
348         size_t alloc_sz;
349         int n_segs;
350         bool callback_triggered = false;
351
352         alloc_sz = RTE_ALIGN_CEIL(align + elt_size +
353                         MALLOC_ELEM_TRAILER_LEN, pg_sz);
354         n_segs = alloc_sz / pg_sz;
355
356         /* we can't know in advance how many pages we'll need, so we malloc */
357         ms = malloc(sizeof(*ms) * n_segs);
358         if (ms == NULL)
359                 return -1;
360         memset(ms, 0, sizeof(*ms) * n_segs);
361
362         elem = alloc_pages_on_heap(heap, pg_sz, elt_size, socket, flags, align,
363                         bound, contig, ms, n_segs);
364
365         if (elem == NULL)
366                 goto free_ms;
367
368         map_addr = ms[0]->addr;
369
370         /* notify user about changes in memory map */
371         eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC, map_addr, alloc_sz);
372
373         /* notify other processes that this has happened */
374         if (request_sync()) {
375                 /* we couldn't ensure all processes have mapped memory,
376                  * so free it back and notify everyone that it's been
377                  * freed back.
378                  *
379                  * technically, we could've avoided adding memory addresses to
380                  * the map, but that would've led to inconsistent behavior
381                  * between primary and secondary processes, as those get
382                  * callbacks during sync. therefore, force primary process to
383                  * do alloc-and-rollback syncs as well.
384                  */
385                 callback_triggered = true;
386                 goto free_elem;
387         }
388         heap->total_size += alloc_sz;
389
390         RTE_LOG(DEBUG, EAL, "Heap on socket %d was expanded by %zdMB\n",
391                 socket, alloc_sz >> 20ULL);
392
393         free(ms);
394
395         return 0;
396
397 free_elem:
398         if (callback_triggered)
399                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
400                                 map_addr, alloc_sz);
401
402         rollback_expand_heap(ms, n_segs, elem, map_addr, alloc_sz);
403
404         request_sync();
405 free_ms:
406         free(ms);
407
408         return -1;
409 }
410
411 static int
412 try_expand_heap_secondary(struct malloc_heap *heap, uint64_t pg_sz,
413                 size_t elt_size, int socket, unsigned int flags, size_t align,
414                 size_t bound, bool contig)
415 {
416         struct malloc_mp_req req;
417         int req_result;
418
419         memset(&req, 0, sizeof(req));
420
421         req.t = REQ_TYPE_ALLOC;
422         req.alloc_req.align = align;
423         req.alloc_req.bound = bound;
424         req.alloc_req.contig = contig;
425         req.alloc_req.flags = flags;
426         req.alloc_req.elt_size = elt_size;
427         req.alloc_req.page_sz = pg_sz;
428         req.alloc_req.socket = socket;
429         req.alloc_req.heap = heap; /* it's in shared memory */
430
431         req_result = request_to_primary(&req);
432
433         if (req_result != 0)
434                 return -1;
435
436         if (req.result != REQ_RESULT_SUCCESS)
437                 return -1;
438
439         return 0;
440 }
441
442 static int
443 try_expand_heap(struct malloc_heap *heap, uint64_t pg_sz, size_t elt_size,
444                 int socket, unsigned int flags, size_t align, size_t bound,
445                 bool contig)
446 {
447         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
448         int ret;
449
450         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
451
452         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
453                 ret = try_expand_heap_primary(heap, pg_sz, elt_size, socket,
454                                 flags, align, bound, contig);
455         } else {
456                 ret = try_expand_heap_secondary(heap, pg_sz, elt_size, socket,
457                                 flags, align, bound, contig);
458         }
459
460         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
461         return ret;
462 }
463
464 static int
465 compare_pagesz(const void *a, const void *b)
466 {
467         const struct rte_memseg_list * const*mpa = a;
468         const struct rte_memseg_list * const*mpb = b;
469         const struct rte_memseg_list *msla = *mpa;
470         const struct rte_memseg_list *mslb = *mpb;
471         uint64_t pg_sz_a = msla->page_sz;
472         uint64_t pg_sz_b = mslb->page_sz;
473
474         if (pg_sz_a < pg_sz_b)
475                 return -1;
476         if (pg_sz_a > pg_sz_b)
477                 return 1;
478         return 0;
479 }
480
481 static int
482 alloc_more_mem_on_socket(struct malloc_heap *heap, size_t size, int socket,
483                 unsigned int flags, size_t align, size_t bound, bool contig)
484 {
485         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
486         struct rte_memseg_list *requested_msls[RTE_MAX_MEMSEG_LISTS];
487         struct rte_memseg_list *other_msls[RTE_MAX_MEMSEG_LISTS];
488         uint64_t requested_pg_sz[RTE_MAX_MEMSEG_LISTS];
489         uint64_t other_pg_sz[RTE_MAX_MEMSEG_LISTS];
490         uint64_t prev_pg_sz;
491         int i, n_other_msls, n_other_pg_sz, n_requested_msls, n_requested_pg_sz;
492         bool size_hint = (flags & RTE_MEMZONE_SIZE_HINT_ONLY) > 0;
493         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
494         void *ret;
495
496         memset(requested_msls, 0, sizeof(requested_msls));
497         memset(other_msls, 0, sizeof(other_msls));
498         memset(requested_pg_sz, 0, sizeof(requested_pg_sz));
499         memset(other_pg_sz, 0, sizeof(other_pg_sz));
500
501         /*
502          * go through memseg list and take note of all the page sizes available,
503          * and if any of them were specifically requested by the user.
504          */
505         n_requested_msls = 0;
506         n_other_msls = 0;
507         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
508                 struct rte_memseg_list *msl = &mcfg->memsegs[i];
509
510                 if (msl->socket_id != socket)
511                         continue;
512
513                 if (msl->base_va == NULL)
514                         continue;
515
516                 /* if pages of specific size were requested */
517                 if (size_flags != 0 && check_hugepage_sz(size_flags,
518                                 msl->page_sz))
519                         requested_msls[n_requested_msls++] = msl;
520                 else if (size_flags == 0 || size_hint)
521                         other_msls[n_other_msls++] = msl;
522         }
523
524         /* sort the lists, smallest first */
525         qsort(requested_msls, n_requested_msls, sizeof(requested_msls[0]),
526                         compare_pagesz);
527         qsort(other_msls, n_other_msls, sizeof(other_msls[0]),
528                         compare_pagesz);
529
530         /* now, extract page sizes we are supposed to try */
531         prev_pg_sz = 0;
532         n_requested_pg_sz = 0;
533         for (i = 0; i < n_requested_msls; i++) {
534                 uint64_t pg_sz = requested_msls[i]->page_sz;
535
536                 if (prev_pg_sz != pg_sz) {
537                         requested_pg_sz[n_requested_pg_sz++] = pg_sz;
538                         prev_pg_sz = pg_sz;
539                 }
540         }
541         prev_pg_sz = 0;
542         n_other_pg_sz = 0;
543         for (i = 0; i < n_other_msls; i++) {
544                 uint64_t pg_sz = other_msls[i]->page_sz;
545
546                 if (prev_pg_sz != pg_sz) {
547                         other_pg_sz[n_other_pg_sz++] = pg_sz;
548                         prev_pg_sz = pg_sz;
549                 }
550         }
551
552         /* finally, try allocating memory of specified page sizes, starting from
553          * the smallest sizes
554          */
555         for (i = 0; i < n_requested_pg_sz; i++) {
556                 uint64_t pg_sz = requested_pg_sz[i];
557
558                 /*
559                  * do not pass the size hint here, as user expects other page
560                  * sizes first, before resorting to best effort allocation.
561                  */
562                 if (!try_expand_heap(heap, pg_sz, size, socket, size_flags,
563                                 align, bound, contig))
564                         return 0;
565         }
566         if (n_other_pg_sz == 0)
567                 return -1;
568
569         /* now, check if we can reserve anything with size hint */
570         ret = find_suitable_element(heap, size, flags, align, bound, contig);
571         if (ret != NULL)
572                 return 0;
573
574         /*
575          * we still couldn't reserve memory, so try expanding heap with other
576          * page sizes, if there are any
577          */
578         for (i = 0; i < n_other_pg_sz; i++) {
579                 uint64_t pg_sz = other_pg_sz[i];
580
581                 if (!try_expand_heap(heap, pg_sz, size, socket, flags,
582                                 align, bound, contig))
583                         return 0;
584         }
585         return -1;
586 }
587
588 /* this will try lower page sizes first */
589 static void *
590 malloc_heap_alloc_on_heap_id(const char *type, size_t size,
591                 unsigned int heap_id, unsigned int flags, size_t align,
592                 size_t bound, bool contig)
593 {
594         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
595         struct malloc_heap *heap = &mcfg->malloc_heaps[heap_id];
596         unsigned int size_flags = flags & ~RTE_MEMZONE_SIZE_HINT_ONLY;
597         int socket_id;
598         void *ret;
599
600         rte_spinlock_lock(&(heap->lock));
601
602         align = align == 0 ? 1 : align;
603
604         /* for legacy mode, try once and with all flags */
605         if (internal_config.legacy_mem) {
606                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
607                 goto alloc_unlock;
608         }
609
610         /*
611          * we do not pass the size hint here, because even if allocation fails,
612          * we may still be able to allocate memory from appropriate page sizes,
613          * we just need to request more memory first.
614          */
615
616         socket_id = rte_socket_id_by_idx(heap_id);
617         /*
618          * if socket ID is negative, we cannot find a socket ID for this heap -
619          * which means it's an external heap. those can have unexpected page
620          * sizes, so if the user asked to allocate from there - assume user
621          * knows what they're doing, and allow allocating from there with any
622          * page size flags.
623          */
624         if (socket_id < 0)
625                 size_flags |= RTE_MEMZONE_SIZE_HINT_ONLY;
626
627         ret = heap_alloc(heap, type, size, size_flags, align, bound, contig);
628         if (ret != NULL)
629                 goto alloc_unlock;
630
631         /* if socket ID is invalid, this is an external heap */
632         if (socket_id < 0)
633                 goto alloc_unlock;
634
635         if (!alloc_more_mem_on_socket(heap, size, socket_id, flags, align,
636                         bound, contig)) {
637                 ret = heap_alloc(heap, type, size, flags, align, bound, contig);
638
639                 /* this should have succeeded */
640                 if (ret == NULL)
641                         RTE_LOG(ERR, EAL, "Error allocating from heap\n");
642         }
643 alloc_unlock:
644         rte_spinlock_unlock(&(heap->lock));
645         return ret;
646 }
647
648 void *
649 malloc_heap_alloc(const char *type, size_t size, int socket_arg,
650                 unsigned int flags, size_t align, size_t bound, bool contig)
651 {
652         int socket, heap_id, i;
653         void *ret;
654
655         /* return NULL if size is 0 or alignment is not power-of-2 */
656         if (size == 0 || (align && !rte_is_power_of_2(align)))
657                 return NULL;
658
659         if (!rte_eal_has_hugepages() && socket_arg < RTE_MAX_NUMA_NODES)
660                 socket_arg = SOCKET_ID_ANY;
661
662         if (socket_arg == SOCKET_ID_ANY)
663                 socket = malloc_get_numa_socket();
664         else
665                 socket = socket_arg;
666
667         /* turn socket ID into heap ID */
668         heap_id = malloc_socket_to_heap_id(socket);
669         /* if heap id is negative, socket ID was invalid */
670         if (heap_id < 0)
671                 return NULL;
672
673         ret = malloc_heap_alloc_on_heap_id(type, size, heap_id, flags, align,
674                         bound, contig);
675         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
676                 return ret;
677
678         /* try other heaps. we are only iterating through native DPDK sockets,
679          * so external heaps won't be included.
680          */
681         for (i = 0; i < (int) rte_socket_count(); i++) {
682                 if (i == heap_id)
683                         continue;
684                 ret = malloc_heap_alloc_on_heap_id(type, size, i, flags, align,
685                                 bound, contig);
686                 if (ret != NULL)
687                         return ret;
688         }
689         return NULL;
690 }
691
692 static void *
693 heap_alloc_biggest_on_heap_id(const char *type, unsigned int heap_id,
694                 unsigned int flags, size_t align, bool contig)
695 {
696         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
697         struct malloc_heap *heap = &mcfg->malloc_heaps[heap_id];
698         void *ret;
699
700         rte_spinlock_lock(&(heap->lock));
701
702         align = align == 0 ? 1 : align;
703
704         ret = heap_alloc_biggest(heap, type, flags, align, contig);
705
706         rte_spinlock_unlock(&(heap->lock));
707
708         return ret;
709 }
710
711 void *
712 malloc_heap_alloc_biggest(const char *type, int socket_arg, unsigned int flags,
713                 size_t align, bool contig)
714 {
715         int socket, i, cur_socket, heap_id;
716         void *ret;
717
718         /* return NULL if align is not power-of-2 */
719         if ((align && !rte_is_power_of_2(align)))
720                 return NULL;
721
722         if (!rte_eal_has_hugepages())
723                 socket_arg = SOCKET_ID_ANY;
724
725         if (socket_arg == SOCKET_ID_ANY)
726                 socket = malloc_get_numa_socket();
727         else
728                 socket = socket_arg;
729
730         /* turn socket ID into heap ID */
731         heap_id = malloc_socket_to_heap_id(socket);
732         /* if heap id is negative, socket ID was invalid */
733         if (heap_id < 0)
734                 return NULL;
735
736         ret = heap_alloc_biggest_on_heap_id(type, heap_id, flags, align,
737                         contig);
738         if (ret != NULL || socket_arg != SOCKET_ID_ANY)
739                 return ret;
740
741         /* try other heaps */
742         for (i = 0; i < (int) rte_socket_count(); i++) {
743                 cur_socket = rte_socket_id_by_idx(i);
744                 if (cur_socket == socket)
745                         continue;
746                 ret = heap_alloc_biggest_on_heap_id(type, i, flags, align,
747                                 contig);
748                 if (ret != NULL)
749                         return ret;
750         }
751         return NULL;
752 }
753
754 /* this function is exposed in malloc_mp.h */
755 int
756 malloc_heap_free_pages(void *aligned_start, size_t aligned_len)
757 {
758         int n_segs, seg_idx, max_seg_idx;
759         struct rte_memseg_list *msl;
760         size_t page_sz;
761
762         msl = rte_mem_virt2memseg_list(aligned_start);
763         if (msl == NULL)
764                 return -1;
765
766         page_sz = (size_t)msl->page_sz;
767         n_segs = aligned_len / page_sz;
768         seg_idx = RTE_PTR_DIFF(aligned_start, msl->base_va) / page_sz;
769         max_seg_idx = seg_idx + n_segs;
770
771         for (; seg_idx < max_seg_idx; seg_idx++) {
772                 struct rte_memseg *ms;
773
774                 ms = rte_fbarray_get(&msl->memseg_arr, seg_idx);
775                 eal_memalloc_free_seg(ms);
776         }
777         return 0;
778 }
779
780 int
781 malloc_heap_free(struct malloc_elem *elem)
782 {
783         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
784         struct malloc_heap *heap;
785         void *start, *aligned_start, *end, *aligned_end;
786         size_t len, aligned_len, page_sz;
787         struct rte_memseg_list *msl;
788         unsigned int i, n_segs, before_space, after_space;
789         int ret;
790
791         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
792                 return -1;
793
794         /* elem may be merged with previous element, so keep heap address */
795         heap = elem->heap;
796         msl = elem->msl;
797         page_sz = (size_t)msl->page_sz;
798
799         rte_spinlock_lock(&(heap->lock));
800
801         /* mark element as free */
802         elem->state = ELEM_FREE;
803
804         elem = malloc_elem_free(elem);
805
806         /* anything after this is a bonus */
807         ret = 0;
808
809         /* ...of which we can't avail if we are in legacy mode, or if this is an
810          * externally allocated segment.
811          */
812         if (internal_config.legacy_mem || (msl->external > 0))
813                 goto free_unlock;
814
815         /* check if we can free any memory back to the system */
816         if (elem->size < page_sz)
817                 goto free_unlock;
818
819         /* probably, but let's make sure, as we may not be using up full page */
820         start = elem;
821         len = elem->size;
822         aligned_start = RTE_PTR_ALIGN_CEIL(start, page_sz);
823         end = RTE_PTR_ADD(elem, len);
824         aligned_end = RTE_PTR_ALIGN_FLOOR(end, page_sz);
825
826         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
827
828         /* can't free anything */
829         if (aligned_len < page_sz)
830                 goto free_unlock;
831
832         /* we can free something. however, some of these pages may be marked as
833          * unfreeable, so also check that as well
834          */
835         n_segs = aligned_len / page_sz;
836         for (i = 0; i < n_segs; i++) {
837                 const struct rte_memseg *tmp =
838                                 rte_mem_virt2memseg(aligned_start, msl);
839
840                 if (tmp->flags & RTE_MEMSEG_FLAG_DO_NOT_FREE) {
841                         /* this is an unfreeable segment, so move start */
842                         aligned_start = RTE_PTR_ADD(tmp->addr, tmp->len);
843                 }
844         }
845
846         /* recalculate length and number of segments */
847         aligned_len = RTE_PTR_DIFF(aligned_end, aligned_start);
848         n_segs = aligned_len / page_sz;
849
850         /* check if we can still free some pages */
851         if (n_segs == 0)
852                 goto free_unlock;
853
854         /* We're not done yet. We also have to check if by freeing space we will
855          * be leaving free elements that are too small to store new elements.
856          * Check if we have enough space in the beginning and at the end, or if
857          * start/end are exactly page aligned.
858          */
859         before_space = RTE_PTR_DIFF(aligned_start, elem);
860         after_space = RTE_PTR_DIFF(end, aligned_end);
861         if (before_space != 0 &&
862                         before_space < MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
863                 /* There is not enough space before start, but we may be able to
864                  * move the start forward by one page.
865                  */
866                 if (n_segs == 1)
867                         goto free_unlock;
868
869                 /* move start */
870                 aligned_start = RTE_PTR_ADD(aligned_start, page_sz);
871                 aligned_len -= page_sz;
872                 n_segs--;
873         }
874         if (after_space != 0 && after_space <
875                         MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
876                 /* There is not enough space after end, but we may be able to
877                  * move the end backwards by one page.
878                  */
879                 if (n_segs == 1)
880                         goto free_unlock;
881
882                 /* move end */
883                 aligned_end = RTE_PTR_SUB(aligned_end, page_sz);
884                 aligned_len -= page_sz;
885                 n_segs--;
886         }
887
888         /* now we can finally free us some pages */
889
890         rte_rwlock_write_lock(&mcfg->memory_hotplug_lock);
891
892         /*
893          * we allow secondary processes to clear the heap of this allocated
894          * memory because it is safe to do so, as even if notifications about
895          * unmapped pages don't make it to other processes, heap is shared
896          * across all processes, and will become empty of this memory anyway,
897          * and nothing can allocate it back unless primary process will be able
898          * to deliver allocation message to every single running process.
899          */
900
901         malloc_elem_free_list_remove(elem);
902
903         malloc_elem_hide_region(elem, (void *) aligned_start, aligned_len);
904
905         heap->total_size -= aligned_len;
906
907         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
908                 /* notify user about changes in memory map */
909                 eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE,
910                                 aligned_start, aligned_len);
911
912                 /* don't care if any of this fails */
913                 malloc_heap_free_pages(aligned_start, aligned_len);
914
915                 request_sync();
916         } else {
917                 struct malloc_mp_req req;
918
919                 memset(&req, 0, sizeof(req));
920
921                 req.t = REQ_TYPE_FREE;
922                 req.free_req.addr = aligned_start;
923                 req.free_req.len = aligned_len;
924
925                 /*
926                  * we request primary to deallocate pages, but we don't do it
927                  * in this thread. instead, we notify primary that we would like
928                  * to deallocate pages, and this process will receive another
929                  * request (in parallel) that will do it for us on another
930                  * thread.
931                  *
932                  * we also don't really care if this succeeds - the data is
933                  * already removed from the heap, so it is, for all intents and
934                  * purposes, hidden from the rest of DPDK even if some other
935                  * process (including this one) may have these pages mapped.
936                  *
937                  * notifications about deallocated memory happen during sync.
938                  */
939                 request_to_primary(&req);
940         }
941
942         RTE_LOG(DEBUG, EAL, "Heap on socket %d was shrunk by %zdMB\n",
943                 msl->socket_id, aligned_len >> 20ULL);
944
945         rte_rwlock_write_unlock(&mcfg->memory_hotplug_lock);
946 free_unlock:
947         rte_spinlock_unlock(&(heap->lock));
948         return ret;
949 }
950
951 int
952 malloc_heap_resize(struct malloc_elem *elem, size_t size)
953 {
954         int ret;
955
956         if (!malloc_elem_cookies_ok(elem) || elem->state != ELEM_BUSY)
957                 return -1;
958
959         rte_spinlock_lock(&(elem->heap->lock));
960
961         ret = malloc_elem_resize(elem, size);
962
963         rte_spinlock_unlock(&(elem->heap->lock));
964
965         return ret;
966 }
967
968 /*
969  * Function to retrieve data for a given heap
970  */
971 int
972 malloc_heap_get_stats(struct malloc_heap *heap,
973                 struct rte_malloc_socket_stats *socket_stats)
974 {
975         size_t idx;
976         struct malloc_elem *elem;
977
978         rte_spinlock_lock(&heap->lock);
979
980         /* Initialise variables for heap */
981         socket_stats->free_count = 0;
982         socket_stats->heap_freesz_bytes = 0;
983         socket_stats->greatest_free_size = 0;
984
985         /* Iterate through free list */
986         for (idx = 0; idx < RTE_HEAP_NUM_FREELISTS; idx++) {
987                 for (elem = LIST_FIRST(&heap->free_head[idx]);
988                         !!elem; elem = LIST_NEXT(elem, free_list))
989                 {
990                         socket_stats->free_count++;
991                         socket_stats->heap_freesz_bytes += elem->size;
992                         if (elem->size > socket_stats->greatest_free_size)
993                                 socket_stats->greatest_free_size = elem->size;
994                 }
995         }
996         /* Get stats on overall heap and allocated memory on this heap */
997         socket_stats->heap_totalsz_bytes = heap->total_size;
998         socket_stats->heap_allocsz_bytes = (socket_stats->heap_totalsz_bytes -
999                         socket_stats->heap_freesz_bytes);
1000         socket_stats->alloc_count = heap->alloc_count;
1001
1002         rte_spinlock_unlock(&heap->lock);
1003         return 0;
1004 }
1005
1006 /*
1007  * Function to retrieve data for a given heap
1008  */
1009 void
1010 malloc_heap_dump(struct malloc_heap *heap, FILE *f)
1011 {
1012         struct malloc_elem *elem;
1013
1014         rte_spinlock_lock(&heap->lock);
1015
1016         fprintf(f, "Heap size: 0x%zx\n", heap->total_size);
1017         fprintf(f, "Heap alloc count: %u\n", heap->alloc_count);
1018
1019         elem = heap->first;
1020         while (elem) {
1021                 malloc_elem_dump(elem, f);
1022                 elem = elem->next;
1023         }
1024
1025         rte_spinlock_unlock(&heap->lock);
1026 }
1027
1028 static int
1029 destroy_seg(struct malloc_elem *elem, size_t len)
1030 {
1031         struct malloc_heap *heap = elem->heap;
1032         struct rte_memseg_list *msl;
1033
1034         msl = elem->msl;
1035
1036         /* notify all subscribers that a memory area is going to be removed */
1037         eal_memalloc_mem_event_notify(RTE_MEM_EVENT_FREE, elem, len);
1038
1039         /* this element can be removed */
1040         malloc_elem_free_list_remove(elem);
1041         malloc_elem_hide_region(elem, elem, len);
1042
1043         heap->total_size -= len;
1044
1045         memset(elem, 0, sizeof(*elem));
1046
1047         /* destroy the fbarray backing this memory */
1048         if (rte_fbarray_destroy(&msl->memseg_arr) < 0)
1049                 return -1;
1050
1051         /* reset the memseg list */
1052         memset(msl, 0, sizeof(*msl));
1053
1054         return 0;
1055 }
1056
1057 int
1058 malloc_heap_add_external_memory(struct malloc_heap *heap, void *va_addr,
1059                 rte_iova_t iova_addrs[], unsigned int n_pages, size_t page_sz)
1060 {
1061         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1062         char fbarray_name[RTE_FBARRAY_NAME_LEN];
1063         struct rte_memseg_list *msl = NULL;
1064         struct rte_fbarray *arr;
1065         size_t seg_len = n_pages * page_sz;
1066         unsigned int i;
1067
1068         /* first, find a free memseg list */
1069         for (i = 0; i < RTE_MAX_MEMSEG_LISTS; i++) {
1070                 struct rte_memseg_list *tmp = &mcfg->memsegs[i];
1071                 if (tmp->base_va == NULL) {
1072                         msl = tmp;
1073                         break;
1074                 }
1075         }
1076         if (msl == NULL) {
1077                 RTE_LOG(ERR, EAL, "Couldn't find empty memseg list\n");
1078                 rte_errno = ENOSPC;
1079                 return -1;
1080         }
1081
1082         snprintf(fbarray_name, sizeof(fbarray_name) - 1, "%s_%p",
1083                         heap->name, va_addr);
1084
1085         /* create the backing fbarray */
1086         if (rte_fbarray_init(&msl->memseg_arr, fbarray_name, n_pages,
1087                         sizeof(struct rte_memseg)) < 0) {
1088                 RTE_LOG(ERR, EAL, "Couldn't create fbarray backing the memseg list\n");
1089                 return -1;
1090         }
1091         arr = &msl->memseg_arr;
1092
1093         /* fbarray created, fill it up */
1094         for (i = 0; i < n_pages; i++) {
1095                 struct rte_memseg *ms;
1096
1097                 rte_fbarray_set_used(arr, i);
1098                 ms = rte_fbarray_get(arr, i);
1099                 ms->addr = RTE_PTR_ADD(va_addr, i * page_sz);
1100                 ms->iova = iova_addrs == NULL ? RTE_BAD_IOVA : iova_addrs[i];
1101                 ms->hugepage_sz = page_sz;
1102                 ms->len = page_sz;
1103                 ms->nchannel = rte_memory_get_nchannel();
1104                 ms->nrank = rte_memory_get_nrank();
1105                 ms->socket_id = heap->socket_id;
1106         }
1107
1108         /* set up the memseg list */
1109         msl->base_va = va_addr;
1110         msl->page_sz = page_sz;
1111         msl->socket_id = heap->socket_id;
1112         msl->len = seg_len;
1113         msl->version = 0;
1114         msl->external = 1;
1115
1116         /* erase contents of new memory */
1117         memset(va_addr, 0, seg_len);
1118
1119         /* now, add newly minted memory to the malloc heap */
1120         malloc_heap_add_memory(heap, msl, va_addr, seg_len);
1121
1122         heap->total_size += seg_len;
1123
1124         /* all done! */
1125         RTE_LOG(DEBUG, EAL, "Added segment for heap %s starting at %p\n",
1126                         heap->name, va_addr);
1127
1128         /* notify all subscribers that a new memory area has been added */
1129         eal_memalloc_mem_event_notify(RTE_MEM_EVENT_ALLOC,
1130                         va_addr, seg_len);
1131
1132         return 0;
1133 }
1134
1135 int
1136 malloc_heap_remove_external_memory(struct malloc_heap *heap, void *va_addr,
1137                 size_t len)
1138 {
1139         struct malloc_elem *elem = heap->first;
1140
1141         /* find element with specified va address */
1142         while (elem != NULL && elem != va_addr) {
1143                 elem = elem->next;
1144                 /* stop if we've blown past our VA */
1145                 if (elem > (struct malloc_elem *)va_addr) {
1146                         rte_errno = ENOENT;
1147                         return -1;
1148                 }
1149         }
1150         /* check if element was found */
1151         if (elem == NULL || elem->msl->len != len) {
1152                 rte_errno = ENOENT;
1153                 return -1;
1154         }
1155         /* if element's size is not equal to segment len, segment is busy */
1156         if (elem->state == ELEM_BUSY || elem->size != len) {
1157                 rte_errno = EBUSY;
1158                 return -1;
1159         }
1160         return destroy_seg(elem, len);
1161 }
1162
1163 int
1164 malloc_heap_create(struct malloc_heap *heap, const char *heap_name)
1165 {
1166         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1167         uint32_t next_socket_id = mcfg->next_socket_id;
1168
1169         /* prevent overflow. did you really create 2 billion heaps??? */
1170         if (next_socket_id > INT32_MAX) {
1171                 RTE_LOG(ERR, EAL, "Cannot assign new socket ID's\n");
1172                 rte_errno = ENOSPC;
1173                 return -1;
1174         }
1175
1176         /* initialize empty heap */
1177         heap->alloc_count = 0;
1178         heap->first = NULL;
1179         heap->last = NULL;
1180         LIST_INIT(heap->free_head);
1181         rte_spinlock_init(&heap->lock);
1182         heap->total_size = 0;
1183         heap->socket_id = next_socket_id;
1184
1185         /* we hold a global mem hotplug writelock, so it's safe to increment */
1186         mcfg->next_socket_id++;
1187
1188         /* set up name */
1189         strlcpy(heap->name, heap_name, RTE_HEAP_NAME_MAX_LEN);
1190         return 0;
1191 }
1192
1193 int
1194 malloc_heap_destroy(struct malloc_heap *heap)
1195 {
1196         if (heap->alloc_count != 0) {
1197                 RTE_LOG(ERR, EAL, "Heap is still in use\n");
1198                 rte_errno = EBUSY;
1199                 return -1;
1200         }
1201         if (heap->first != NULL || heap->last != NULL) {
1202                 RTE_LOG(ERR, EAL, "Heap still contains memory segments\n");
1203                 rte_errno = EBUSY;
1204                 return -1;
1205         }
1206         if (heap->total_size != 0)
1207                 RTE_LOG(ERR, EAL, "Total size not zero, heap is likely corrupt\n");
1208
1209         /* after this, the lock will be dropped */
1210         memset(heap, 0, sizeof(*heap));
1211
1212         return 0;
1213 }
1214
1215 int
1216 rte_eal_malloc_heap_init(void)
1217 {
1218         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
1219         unsigned int i;
1220
1221         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
1222                 /* assign min socket ID to external heaps */
1223                 mcfg->next_socket_id = EXTERNAL_HEAP_MIN_SOCKET_ID;
1224
1225                 /* assign names to default DPDK heaps */
1226                 for (i = 0; i < rte_socket_count(); i++) {
1227                         struct malloc_heap *heap = &mcfg->malloc_heaps[i];
1228                         char heap_name[RTE_HEAP_NAME_MAX_LEN];
1229                         int socket_id = rte_socket_id_by_idx(i);
1230
1231                         snprintf(heap_name, sizeof(heap_name) - 1,
1232                                         "socket_%i", socket_id);
1233                         strlcpy(heap->name, heap_name, RTE_HEAP_NAME_MAX_LEN);
1234                         heap->socket_id = socket_id;
1235                 }
1236         }
1237
1238
1239         if (register_mp_requests()) {
1240                 RTE_LOG(ERR, EAL, "Couldn't register malloc multiprocess actions\n");
1241                 rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
1242                 return -1;
1243         }
1244
1245         /* unlock mem hotplug here. it's safe for primary as no requests can
1246          * even come before primary itself is fully initialized, and secondaries
1247          * do not need to initialize the heap.
1248          */
1249         rte_rwlock_read_unlock(&mcfg->memory_hotplug_lock);
1250
1251         /* secondary process does not need to initialize anything */
1252         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
1253                 return 0;
1254
1255         /* add all IOVA-contiguous areas to the heap */
1256         return rte_memseg_contig_walk(malloc_add_seg, NULL);
1257 }