af81961d275b33152eeb592e2eef0b6032c6c1ba
[dpdk.git] / lib / librte_eal / common / malloc_elem.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4 #include <inttypes.h>
5 #include <stdint.h>
6 #include <stddef.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <sys/queue.h>
11
12 #include <rte_memory.h>
13 #include <rte_eal.h>
14 #include <rte_launch.h>
15 #include <rte_per_lcore.h>
16 #include <rte_lcore.h>
17 #include <rte_debug.h>
18 #include <rte_common.h>
19 #include <rte_spinlock.h>
20
21 #include "eal_memalloc.h"
22 #include "malloc_elem.h"
23 #include "malloc_heap.h"
24
25 #define MIN_DATA_SIZE (RTE_CACHE_LINE_SIZE)
26
27 /*
28  * Initialize a general malloc_elem header structure
29  */
30 void
31 malloc_elem_init(struct malloc_elem *elem, struct malloc_heap *heap,
32                 struct rte_memseg_list *msl, size_t size)
33 {
34         elem->heap = heap;
35         elem->msl = msl;
36         elem->prev = NULL;
37         elem->next = NULL;
38         memset(&elem->free_list, 0, sizeof(elem->free_list));
39         elem->state = ELEM_FREE;
40         elem->size = size;
41         elem->pad = 0;
42         set_header(elem);
43         set_trailer(elem);
44 }
45
46 void
47 malloc_elem_insert(struct malloc_elem *elem)
48 {
49         struct malloc_elem *prev_elem, *next_elem;
50         struct malloc_heap *heap = elem->heap;
51
52         /* first and last elements must be both NULL or both non-NULL */
53         if ((heap->first == NULL) != (heap->last == NULL)) {
54                 RTE_LOG(ERR, EAL, "Heap is probably corrupt\n");
55                 return;
56         }
57
58         if (heap->first == NULL && heap->last == NULL) {
59                 /* if empty heap */
60                 heap->first = elem;
61                 heap->last = elem;
62                 prev_elem = NULL;
63                 next_elem = NULL;
64         } else if (elem < heap->first) {
65                 /* if lower than start */
66                 prev_elem = NULL;
67                 next_elem = heap->first;
68                 heap->first = elem;
69         } else if (elem > heap->last) {
70                 /* if higher than end */
71                 prev_elem = heap->last;
72                 next_elem = NULL;
73                 heap->last = elem;
74         } else {
75                 /* the new memory is somewhere inbetween start and end */
76                 uint64_t dist_from_start, dist_from_end;
77
78                 dist_from_end = RTE_PTR_DIFF(heap->last, elem);
79                 dist_from_start = RTE_PTR_DIFF(elem, heap->first);
80
81                 /* check which is closer, and find closest list entries */
82                 if (dist_from_start < dist_from_end) {
83                         prev_elem = heap->first;
84                         while (prev_elem->next < elem)
85                                 prev_elem = prev_elem->next;
86                         next_elem = prev_elem->next;
87                 } else {
88                         next_elem = heap->last;
89                         while (next_elem->prev > elem)
90                                 next_elem = next_elem->prev;
91                         prev_elem = next_elem->prev;
92                 }
93         }
94
95         /* insert new element */
96         elem->prev = prev_elem;
97         elem->next = next_elem;
98         if (prev_elem)
99                 prev_elem->next = elem;
100         if (next_elem)
101                 next_elem->prev = elem;
102 }
103
104 /*
105  * Attempt to find enough physically contiguous memory in this block to store
106  * our data. Assume that element has at least enough space to fit in the data,
107  * so we just check the page addresses.
108  */
109 static bool
110 elem_check_phys_contig(const struct rte_memseg_list *msl,
111                 void *start, size_t size)
112 {
113         return eal_memalloc_is_contig(msl, start, size);
114 }
115
116 /*
117  * calculate the starting point of where data of the requested size
118  * and alignment would fit in the current element. If the data doesn't
119  * fit, return NULL.
120  */
121 static void *
122 elem_start_pt(struct malloc_elem *elem, size_t size, unsigned align,
123                 size_t bound, bool contig)
124 {
125         size_t elem_size = elem->size;
126
127         /*
128          * we're allocating from the end, so adjust the size of element by
129          * alignment size.
130          */
131         while (elem_size >= size) {
132                 const size_t bmask = ~(bound - 1);
133                 uintptr_t end_pt = (uintptr_t)elem +
134                                 elem_size - MALLOC_ELEM_TRAILER_LEN;
135                 uintptr_t new_data_start = RTE_ALIGN_FLOOR((end_pt - size),
136                                 align);
137                 uintptr_t new_elem_start;
138
139                 /* check boundary */
140                 if ((new_data_start & bmask) != ((end_pt - 1) & bmask)) {
141                         end_pt = RTE_ALIGN_FLOOR(end_pt, bound);
142                         new_data_start = RTE_ALIGN_FLOOR((end_pt - size),
143                                         align);
144                         end_pt = new_data_start + size;
145
146                         if (((end_pt - 1) & bmask) != (new_data_start & bmask))
147                                 return NULL;
148                 }
149
150                 new_elem_start = new_data_start - MALLOC_ELEM_HEADER_LEN;
151
152                 /* if the new start point is before the exist start,
153                  * it won't fit
154                  */
155                 if (new_elem_start < (uintptr_t)elem)
156                         return NULL;
157
158                 if (contig) {
159                         size_t new_data_size = end_pt - new_data_start;
160
161                         /*
162                          * if physical contiguousness was requested and we
163                          * couldn't fit all data into one physically contiguous
164                          * block, try again with lower addresses.
165                          */
166                         if (!elem_check_phys_contig(elem->msl,
167                                         (void *)new_data_start,
168                                         new_data_size)) {
169                                 elem_size -= align;
170                                 continue;
171                         }
172                 }
173                 return (void *)new_elem_start;
174         }
175         return NULL;
176 }
177
178 /*
179  * use elem_start_pt to determine if we get meet the size and
180  * alignment request from the current element
181  */
182 int
183 malloc_elem_can_hold(struct malloc_elem *elem, size_t size,     unsigned align,
184                 size_t bound, bool contig)
185 {
186         return elem_start_pt(elem, size, align, bound, contig) != NULL;
187 }
188
189 /*
190  * split an existing element into two smaller elements at the given
191  * split_pt parameter.
192  */
193 static void
194 split_elem(struct malloc_elem *elem, struct malloc_elem *split_pt)
195 {
196         struct malloc_elem *next_elem = elem->next;
197         const size_t old_elem_size = (uintptr_t)split_pt - (uintptr_t)elem;
198         const size_t new_elem_size = elem->size - old_elem_size;
199
200         malloc_elem_init(split_pt, elem->heap, elem->msl, new_elem_size);
201         split_pt->prev = elem;
202         split_pt->next = next_elem;
203         if (next_elem)
204                 next_elem->prev = split_pt;
205         else
206                 elem->heap->last = split_pt;
207         elem->next = split_pt;
208         elem->size = old_elem_size;
209         set_trailer(elem);
210 }
211
212 /*
213  * our malloc heap is a doubly linked list, so doubly remove our element.
214  */
215 static void __rte_unused
216 remove_elem(struct malloc_elem *elem)
217 {
218         struct malloc_elem *next, *prev;
219         next = elem->next;
220         prev = elem->prev;
221
222         if (next)
223                 next->prev = prev;
224         else
225                 elem->heap->last = prev;
226         if (prev)
227                 prev->next = next;
228         else
229                 elem->heap->first = next;
230
231         elem->prev = NULL;
232         elem->next = NULL;
233 }
234
235 static int
236 next_elem_is_adjacent(struct malloc_elem *elem)
237 {
238         return elem->next == RTE_PTR_ADD(elem, elem->size);
239 }
240
241 static int
242 prev_elem_is_adjacent(struct malloc_elem *elem)
243 {
244         return elem == RTE_PTR_ADD(elem->prev, elem->prev->size);
245 }
246
247 /*
248  * Given an element size, compute its freelist index.
249  * We free an element into the freelist containing similarly-sized elements.
250  * We try to allocate elements starting with the freelist containing
251  * similarly-sized elements, and if necessary, we search freelists
252  * containing larger elements.
253  *
254  * Example element size ranges for a heap with five free lists:
255  *   heap->free_head[0] - (0   , 2^8]
256  *   heap->free_head[1] - (2^8 , 2^10]
257  *   heap->free_head[2] - (2^10 ,2^12]
258  *   heap->free_head[3] - (2^12, 2^14]
259  *   heap->free_head[4] - (2^14, MAX_SIZE]
260  */
261 size_t
262 malloc_elem_free_list_index(size_t size)
263 {
264 #define MALLOC_MINSIZE_LOG2   8
265 #define MALLOC_LOG2_INCREMENT 2
266
267         size_t log2;
268         size_t index;
269
270         if (size <= (1UL << MALLOC_MINSIZE_LOG2))
271                 return 0;
272
273         /* Find next power of 2 >= size. */
274         log2 = sizeof(size) * 8 - __builtin_clzl(size-1);
275
276         /* Compute freelist index, based on log2(size). */
277         index = (log2 - MALLOC_MINSIZE_LOG2 + MALLOC_LOG2_INCREMENT - 1) /
278                 MALLOC_LOG2_INCREMENT;
279
280         return index <= RTE_HEAP_NUM_FREELISTS-1?
281                 index: RTE_HEAP_NUM_FREELISTS-1;
282 }
283
284 /*
285  * Add the specified element to its heap's free list.
286  */
287 void
288 malloc_elem_free_list_insert(struct malloc_elem *elem)
289 {
290         size_t idx;
291
292         idx = malloc_elem_free_list_index(elem->size - MALLOC_ELEM_HEADER_LEN);
293         elem->state = ELEM_FREE;
294         LIST_INSERT_HEAD(&elem->heap->free_head[idx], elem, free_list);
295 }
296
297 /*
298  * Remove the specified element from its heap's free list.
299  */
300 void
301 malloc_elem_free_list_remove(struct malloc_elem *elem)
302 {
303         LIST_REMOVE(elem, free_list);
304 }
305
306 /*
307  * reserve a block of data in an existing malloc_elem. If the malloc_elem
308  * is much larger than the data block requested, we split the element in two.
309  * This function is only called from malloc_heap_alloc so parameter checking
310  * is not done here, as it's done there previously.
311  */
312 struct malloc_elem *
313 malloc_elem_alloc(struct malloc_elem *elem, size_t size, unsigned align,
314                 size_t bound, bool contig)
315 {
316         struct malloc_elem *new_elem = elem_start_pt(elem, size, align, bound,
317                         contig);
318         const size_t old_elem_size = (uintptr_t)new_elem - (uintptr_t)elem;
319         const size_t trailer_size = elem->size - old_elem_size - size -
320                 MALLOC_ELEM_OVERHEAD;
321
322         malloc_elem_free_list_remove(elem);
323
324         if (trailer_size > MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
325                 /* split it, too much free space after elem */
326                 struct malloc_elem *new_free_elem =
327                                 RTE_PTR_ADD(new_elem, size + MALLOC_ELEM_OVERHEAD);
328
329                 split_elem(elem, new_free_elem);
330                 malloc_elem_free_list_insert(new_free_elem);
331
332                 if (elem == elem->heap->last)
333                         elem->heap->last = new_free_elem;
334         }
335
336         if (old_elem_size < MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
337                 /* don't split it, pad the element instead */
338                 elem->state = ELEM_BUSY;
339                 elem->pad = old_elem_size;
340
341                 /* put a dummy header in padding, to point to real element header */
342                 if (elem->pad > 0) { /* pad will be at least 64-bytes, as everything
343                                      * is cache-line aligned */
344                         new_elem->pad = elem->pad;
345                         new_elem->state = ELEM_PAD;
346                         new_elem->size = elem->size - elem->pad;
347                         set_header(new_elem);
348                 }
349
350                 return new_elem;
351         }
352
353         /* we are going to split the element in two. The original element
354          * remains free, and the new element is the one allocated.
355          * Re-insert original element, in case its new size makes it
356          * belong on a different list.
357          */
358         split_elem(elem, new_elem);
359         new_elem->state = ELEM_BUSY;
360         malloc_elem_free_list_insert(elem);
361
362         return new_elem;
363 }
364
365 /*
366  * join two struct malloc_elem together. elem1 and elem2 must
367  * be contiguous in memory.
368  */
369 static inline void
370 join_elem(struct malloc_elem *elem1, struct malloc_elem *elem2)
371 {
372         struct malloc_elem *next = elem2->next;
373         elem1->size += elem2->size;
374         if (next)
375                 next->prev = elem1;
376         else
377                 elem1->heap->last = elem1;
378         elem1->next = next;
379 }
380
381 struct malloc_elem *
382 malloc_elem_join_adjacent_free(struct malloc_elem *elem)
383 {
384         /*
385          * check if next element exists, is adjacent and is free, if so join
386          * with it, need to remove from free list.
387          */
388         if (elem->next != NULL && elem->next->state == ELEM_FREE &&
389                         next_elem_is_adjacent(elem)) {
390                 void *erase;
391
392                 /* we will want to erase the trailer and header */
393                 erase = RTE_PTR_SUB(elem->next, MALLOC_ELEM_TRAILER_LEN);
394
395                 /* remove from free list, join to this one */
396                 malloc_elem_free_list_remove(elem->next);
397                 join_elem(elem, elem->next);
398
399                 /* erase header and trailer */
400                 memset(erase, 0, MALLOC_ELEM_OVERHEAD);
401         }
402
403         /*
404          * check if prev element exists, is adjacent and is free, if so join
405          * with it, need to remove from free list.
406          */
407         if (elem->prev != NULL && elem->prev->state == ELEM_FREE &&
408                         prev_elem_is_adjacent(elem)) {
409                 struct malloc_elem *new_elem;
410                 void *erase;
411
412                 /* we will want to erase trailer and header */
413                 erase = RTE_PTR_SUB(elem, MALLOC_ELEM_TRAILER_LEN);
414
415                 /* remove from free list, join to this one */
416                 malloc_elem_free_list_remove(elem->prev);
417
418                 new_elem = elem->prev;
419                 join_elem(new_elem, elem);
420
421                 /* erase header and trailer */
422                 memset(erase, 0, MALLOC_ELEM_OVERHEAD);
423
424                 elem = new_elem;
425         }
426
427         return elem;
428 }
429
430 /*
431  * free a malloc_elem block by adding it to the free list. If the
432  * blocks either immediately before or immediately after newly freed block
433  * are also free, the blocks are merged together.
434  */
435 struct malloc_elem *
436 malloc_elem_free(struct malloc_elem *elem)
437 {
438         void *ptr;
439         size_t data_len;
440
441         ptr = RTE_PTR_ADD(elem, sizeof(*elem));
442         data_len = elem->size - MALLOC_ELEM_OVERHEAD;
443
444         elem = malloc_elem_join_adjacent_free(elem);
445
446         malloc_elem_free_list_insert(elem);
447
448         /* decrease heap's count of allocated elements */
449         elem->heap->alloc_count--;
450
451         memset(ptr, 0, data_len);
452
453         return elem;
454 }
455
456 /* assume all checks were already done */
457 void
458 malloc_elem_hide_region(struct malloc_elem *elem, void *start, size_t len)
459 {
460         struct malloc_elem *hide_start, *hide_end, *prev, *next;
461         size_t len_before, len_after;
462
463         hide_start = start;
464         hide_end = RTE_PTR_ADD(start, len);
465
466         prev = elem->prev;
467         next = elem->next;
468
469         /* we cannot do anything with non-adjacent elements */
470         if (next && next_elem_is_adjacent(elem)) {
471                 len_after = RTE_PTR_DIFF(next, hide_end);
472                 if (len_after >= MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
473                         /* split after */
474                         split_elem(elem, hide_end);
475
476                         malloc_elem_free_list_insert(hide_end);
477                 } else if (len_after >= MALLOC_ELEM_HEADER_LEN) {
478                         /* shrink current element */
479                         elem->size -= len_after;
480                         memset(hide_end, 0, sizeof(*hide_end));
481
482                         /* copy next element's data to our pad */
483                         memcpy(hide_end, next, sizeof(*hide_end));
484
485                         /* pad next element */
486                         next->state = ELEM_PAD;
487                         next->pad = len_after;
488                         next->size -= len_after;
489
490                         /* next element busy, would've been merged otherwise */
491                         hide_end->pad = len_after;
492                         hide_end->size += len_after;
493
494                         /* adjust pointers to point to our new pad */
495                         if (next->next)
496                                 next->next->prev = hide_end;
497                         elem->next = hide_end;
498                 } else if (len_after > 0) {
499                         RTE_LOG(ERR, EAL, "Unaligned element, heap is probably corrupt\n");
500                         return;
501                 }
502         }
503
504         /* we cannot do anything with non-adjacent elements */
505         if (prev && prev_elem_is_adjacent(elem)) {
506                 len_before = RTE_PTR_DIFF(hide_start, elem);
507                 if (len_before >= MALLOC_ELEM_OVERHEAD + MIN_DATA_SIZE) {
508                         /* split before */
509                         split_elem(elem, hide_start);
510
511                         prev = elem;
512                         elem = hide_start;
513
514                         malloc_elem_free_list_insert(prev);
515                 } else if (len_before > 0) {
516                         /*
517                          * unlike with elements after current, here we don't
518                          * need to pad elements, but rather just increase the
519                          * size of previous element, copy the old header and set
520                          * up trailer.
521                          */
522                         void *trailer = RTE_PTR_ADD(prev,
523                                         prev->size - MALLOC_ELEM_TRAILER_LEN);
524
525                         memcpy(hide_start, elem, sizeof(*elem));
526                         hide_start->size = len;
527
528                         prev->size += len_before;
529                         set_trailer(prev);
530
531                         /* update pointers */
532                         prev->next = hide_start;
533                         if (next)
534                                 next->prev = hide_start;
535
536                         /* erase old trailer */
537                         memset(trailer, 0, MALLOC_ELEM_TRAILER_LEN);
538                         /* erase old header */
539                         memset(elem, 0, sizeof(*elem));
540
541                         elem = hide_start;
542                 }
543         }
544
545         remove_elem(elem);
546 }
547
548 /*
549  * attempt to resize a malloc_elem by expanding into any free space
550  * immediately after it in memory.
551  */
552 int
553 malloc_elem_resize(struct malloc_elem *elem, size_t size)
554 {
555         const size_t new_size = size + elem->pad + MALLOC_ELEM_OVERHEAD;
556
557         /* if we request a smaller size, then always return ok */
558         if (elem->size >= new_size)
559                 return 0;
560
561         /* check if there is a next element, it's free and adjacent */
562         if (!elem->next || elem->next->state != ELEM_FREE ||
563                         !next_elem_is_adjacent(elem))
564                 return -1;
565         if (elem->size + elem->next->size < new_size)
566                 return -1;
567
568         /* we now know the element fits, so remove from free list,
569          * join the two
570          */
571         malloc_elem_free_list_remove(elem->next);
572         join_elem(elem, elem->next);
573
574         if (elem->size - new_size >= MIN_DATA_SIZE + MALLOC_ELEM_OVERHEAD) {
575                 /* now we have a big block together. Lets cut it down a bit, by splitting */
576                 struct malloc_elem *split_pt = RTE_PTR_ADD(elem, new_size);
577                 split_pt = RTE_PTR_ALIGN_CEIL(split_pt, RTE_CACHE_LINE_SIZE);
578                 split_elem(elem, split_pt);
579                 malloc_elem_free_list_insert(split_pt);
580         }
581         return 0;
582 }
583
584 static inline const char *
585 elem_state_to_str(enum elem_state state)
586 {
587         switch (state) {
588         case ELEM_PAD:
589                 return "PAD";
590         case ELEM_BUSY:
591                 return "BUSY";
592         case ELEM_FREE:
593                 return "FREE";
594         }
595         return "ERROR";
596 }
597
598 void
599 malloc_elem_dump(const struct malloc_elem *elem, FILE *f)
600 {
601         fprintf(f, "Malloc element at %p (%s)\n", elem,
602                         elem_state_to_str(elem->state));
603         fprintf(f, "  len: 0x%zx pad: 0x%" PRIx32 "\n", elem->size, elem->pad);
604         fprintf(f, "  prev: %p next: %p\n", elem->prev, elem->next);
605 }