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