1 /*
2  * Copyright (c) 2018 Jan Van Winkel <jan.van_winkel@dxplore.eu>
3  * Copyright (c) 2020 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include "lvgl_mem.h"
9 #include <zephyr/kernel.h>
10 #include <zephyr/init.h>
11 #include <zephyr/sys/sys_heap.h>
12 
13 
14 #define HEAP_BYTES (CONFIG_LV_Z_MEM_POOL_MAX_SIZE * \
15 		    CONFIG_LV_Z_MEM_POOL_NUMBER_BLOCKS)
16 
17 static char lvgl_heap_mem[HEAP_BYTES] __aligned(8);
18 static struct sys_heap lvgl_heap;
19 static struct k_spinlock lvgl_heap_lock;
20 
lvgl_malloc(size_t size)21 void *lvgl_malloc(size_t size)
22 {
23 	k_spinlock_key_t key;
24 	void *ret;
25 
26 	key = k_spin_lock(&lvgl_heap_lock);
27 	ret = sys_heap_alloc(&lvgl_heap, size);
28 	k_spin_unlock(&lvgl_heap_lock, key);
29 
30 	return ret;
31 }
32 
lvgl_realloc(void * ptr,size_t size)33 void *lvgl_realloc(void *ptr, size_t size)
34 {
35 	k_spinlock_key_t key;
36 	void *ret;
37 
38 	key = k_spin_lock(&lvgl_heap_lock);
39 	ret = sys_heap_realloc(&lvgl_heap, ptr, size);
40 	k_spin_unlock(&lvgl_heap_lock, key);
41 
42 	return ret;
43 }
44 
lvgl_free(void * ptr)45 void lvgl_free(void *ptr)
46 {
47 	k_spinlock_key_t key;
48 
49 	key = k_spin_lock(&lvgl_heap_lock);
50 	sys_heap_free(&lvgl_heap, ptr);
51 	k_spin_unlock(&lvgl_heap_lock, key);
52 }
53 
lvgl_heap_init(void)54 static int lvgl_heap_init(void)
55 {
56 	sys_heap_init(&lvgl_heap, &lvgl_heap_mem[0], HEAP_BYTES);
57 	return 0;
58 }
59 
60 SYS_INIT(lvgl_heap_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
61