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