77#include <kernel.h>
88#include <string.h>
99#include <sys/math_extras.h>
10+ #include <sys/util.h>
1011
11- void * z_heap_malloc (struct k_heap * heap , size_t size )
12+ static void * z_heap_aligned_alloc (struct k_heap * heap , size_t align , size_t size )
1213{
14+ uint8_t * mem ;
15+ struct k_heap * * heap_ref ;
16+ size_t excess = MAX (sizeof (struct k_heap * ), align );
17+
1318 /*
14- * get a block large enough to hold an initial (hidden) heap
19+ * get a block large enough to hold an initial (aligned and hidden) heap
1520 * pointer, as well as the space the caller requested
1621 */
17- if (size_add_overflow (size , sizeof (struct k_heap * ),
18- & size )) {
22+ if (size_add_overflow (size , excess , & size )) {
1923 return NULL ;
2024 }
2125
22- struct k_heap * * blk = k_heap_alloc (heap , size , K_NO_WAIT );
23-
24- if (blk == NULL ) {
26+ mem = k_heap_aligned_alloc (heap , align , size , K_NO_WAIT );
27+ if (mem == NULL ) {
2528 return NULL ;
2629 }
2730
28- blk [0 ] = heap ;
31+ /* create (void *) values in the excess equal to (void *) -1 */
32+ memset (mem , 0xff , excess );
33+ heap_ref = (struct k_heap * * )mem ;
34+ * heap_ref = heap ;
2935
3036 /* return address of the user area part of the block to the caller */
31- return (char * )& blk [1 ];
37+ return mem + excess ;
38+ }
39+
40+ static void * z_heap_malloc (struct k_heap * heap , size_t size )
41+ {
42+ return z_heap_aligned_alloc (heap , sizeof (void * ), size );
3243}
3344
3445void k_free (void * ptr )
3546{
47+ struct k_heap * * heap_ref ;
48+
3649 if (ptr != NULL ) {
37- struct k_heap * * blk = & ((struct k_heap * * )ptr )[-1 ];
38- struct k_heap * heap = * blk ;
50+ for (heap_ref = & ((struct k_heap * * )ptr )[-1 ];
51+ * heap_ref == (struct k_heap * )-1 ; -- heap_ref ) {
52+ /* no-op */
53+ }
3954
40- k_heap_free (heap , blk );
55+ ptr = (uint8_t * )heap_ref ;
56+ k_heap_free (* heap_ref , ptr );
4157 }
4258}
4359
@@ -46,9 +62,16 @@ void k_free(void *ptr)
4662K_HEAP_DEFINE (_system_heap , CONFIG_HEAP_MEM_POOL_SIZE );
4763#define _SYSTEM_HEAP (&_system_heap)
4864
49- void * k_malloc ( size_t size )
65+ void * k_aligned_alloc ( size_t align , size_t size )
5066{
51- return z_heap_malloc (_SYSTEM_HEAP , size );
67+ __ASSERT (align / sizeof (void * ) >= 1
68+ && (align % sizeof (void * )) == 0 ,
69+ "align must be a multiple of sizeof(void *)" );
70+
71+ __ASSERT ((align & (align - 1 )) == 0 ,
72+ "align must be a power of 2" );
73+
74+ return z_heap_aligned_alloc (_SYSTEM_HEAP , align , size );
5275}
5376
5477void * k_calloc (size_t nmemb , size_t size )
0 commit comments