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 #include <zephyr/logging/log.h>
14 LOG_MODULE_DECLARE(lvgl, CONFIG_LV_Z_LOG_LEVEL);
15 
16 #ifdef CONFIG_LV_Z_MEMORY_POOL_CUSTOM_SECTION
17 #define HEAP_MEM_ATTRIBUTES Z_GENERIC_SECTION(.lvgl_heap) __aligned(8)
18 #else
19 #define HEAP_MEM_ATTRIBUTES __aligned(8)
20 #endif /* CONFIG_LV_Z_MEMORY_POOL_CUSTOM_SECTION */
21 static char lvgl_heap_mem[CONFIG_LV_Z_MEM_POOL_SIZE] HEAP_MEM_ATTRIBUTES;
22 
23 static struct sys_heap lvgl_heap;
24 static struct k_spinlock lvgl_heap_lock;
25 
lvgl_malloc(size_t size)26 void *lvgl_malloc(size_t size)
27 {
28 	k_spinlock_key_t key;
29 	void *ret;
30 
31 	key = k_spin_lock(&lvgl_heap_lock);
32 	ret = sys_heap_alloc(&lvgl_heap, size);
33 	k_spin_unlock(&lvgl_heap_lock, key);
34 
35 	return ret;
36 }
37 
lvgl_realloc(void * ptr,size_t size)38 void *lvgl_realloc(void *ptr, size_t size)
39 {
40 	k_spinlock_key_t key;
41 	void *ret;
42 
43 	key = k_spin_lock(&lvgl_heap_lock);
44 	ret = sys_heap_realloc(&lvgl_heap, ptr, size);
45 	k_spin_unlock(&lvgl_heap_lock, key);
46 
47 	return ret;
48 }
49 
lvgl_free(void * ptr)50 void lvgl_free(void *ptr)
51 {
52 	k_spinlock_key_t key;
53 
54 	key = k_spin_lock(&lvgl_heap_lock);
55 	sys_heap_free(&lvgl_heap, ptr);
56 	k_spin_unlock(&lvgl_heap_lock, key);
57 }
58 
lvgl_print_heap_info(bool dump_chunks)59 void lvgl_print_heap_info(bool dump_chunks)
60 {
61 	k_spinlock_key_t key;
62 
63 	key = k_spin_lock(&lvgl_heap_lock);
64 	sys_heap_print_info(&lvgl_heap, dump_chunks);
65 	k_spin_unlock(&lvgl_heap_lock, key);
66 }
67 
lvgl_heap_stats(struct sys_memory_stats * stats)68 void lvgl_heap_stats(struct sys_memory_stats *stats)
69 {
70 #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS
71 	k_spinlock_key_t key;
72 
73 	key = k_spin_lock(&lvgl_heap_lock);
74 	sys_heap_runtime_stats_get(&lvgl_heap, stats);
75 	k_spin_unlock(&lvgl_heap_lock, key);
76 #else
77 	ARG_UNUSED(stats);
78 	LOG_WRN_ONCE("Enable CONFIG_SYS_HEAP_RUNTIME_STATS to use the mem monitor feature");
79 #endif /* CONFIG_SYS_HEAP_RUNTIME_STATS */
80 }
81 
lvgl_heap_init(void)82 void lvgl_heap_init(void)
83 {
84 	sys_heap_init(&lvgl_heap, &lvgl_heap_mem[0], CONFIG_LV_Z_MEM_POOL_SIZE);
85 }
86