|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Silicon Laboratories Inc. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + * |
| 6 | + * Shim basic sl_* pool functions to Zephyr k_mem_slab functions, |
| 7 | + * which again will get redirected to the Zephyr sys_heap. |
| 8 | + */ |
| 9 | + |
| 10 | +#include <stdlib.h> |
| 11 | + |
| 12 | +#include <zephyr/kernel.h> |
| 13 | + |
| 14 | +#include "sl_memory_manager.h" |
| 15 | +#include "sl_status.h" |
| 16 | + |
| 17 | +sl_status_t sl_memory_create_pool(size_t block_size, uint32_t block_count, |
| 18 | + sl_memory_pool_t *pool_handle) |
| 19 | +{ |
| 20 | + struct k_mem_slab *slab; |
| 21 | + char *slab_buffer; |
| 22 | + int ret; |
| 23 | + |
| 24 | + slab = malloc(sizeof(struct k_mem_slab)); |
| 25 | + if (slab == NULL) { |
| 26 | + return SL_STATUS_NO_MORE_RESOURCE; |
| 27 | + } |
| 28 | + |
| 29 | + slab_buffer = malloc(block_size * block_count); |
| 30 | + if (slab_buffer == NULL) { |
| 31 | + free(slab); |
| 32 | + return SL_STATUS_NO_MORE_RESOURCE; |
| 33 | + } |
| 34 | + |
| 35 | + ret = k_mem_slab_init(slab, slab_buffer, block_size, block_count); |
| 36 | + |
| 37 | + if (ret == -EINVAL) { |
| 38 | + free(slab); |
| 39 | + free(slab_buffer); |
| 40 | + return SL_STATUS_INVALID_PARAMETER; |
| 41 | + } else if (ret != 0) { |
| 42 | + free(slab); |
| 43 | + free(slab_buffer); |
| 44 | + return SL_STATUS_FAIL; |
| 45 | + } |
| 46 | + pool_handle->block_address = slab; |
| 47 | + return SL_STATUS_OK; |
| 48 | +} |
| 49 | + |
| 50 | +sl_status_t sl_memory_delete_pool(sl_memory_pool_t *pool_handle) |
| 51 | +{ |
| 52 | + struct k_mem_slab *slab; |
| 53 | + |
| 54 | + slab = pool_handle->block_address; |
| 55 | + free(slab->buffer); |
| 56 | + free(slab); |
| 57 | + return SL_STATUS_OK; |
| 58 | +} |
| 59 | + |
| 60 | +sl_status_t sl_memory_pool_alloc(sl_memory_pool_t *pool_handle, void **block) |
| 61 | +{ |
| 62 | + struct k_mem_slab *slab; |
| 63 | + int ret; |
| 64 | + |
| 65 | + slab = pool_handle->block_address; |
| 66 | + ret = k_mem_slab_alloc(slab, block, K_NO_WAIT); |
| 67 | + |
| 68 | + switch (ret) { |
| 69 | + case -ENOMEM: |
| 70 | + return SL_STATUS_NO_MORE_RESOURCE; |
| 71 | + case -EAGAIN: |
| 72 | + return SL_STATUS_WOULD_BLOCK; |
| 73 | + case -EINVAL: |
| 74 | + return SL_STATUS_INVALID_PARAMETER; |
| 75 | + case 0: |
| 76 | + return SL_STATUS_OK; |
| 77 | + default: |
| 78 | + return SL_STATUS_FAIL; |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +sl_status_t sl_memory_pool_free(sl_memory_pool_t *pool_handle, void *block) |
| 83 | +{ |
| 84 | + struct k_mem_slab *slab; |
| 85 | + |
| 86 | + slab = pool_handle->block_address; |
| 87 | + k_mem_slab_free(slab, block); |
| 88 | + return SL_STATUS_OK; |
| 89 | +} |
0 commit comments