1 /******************************************************************************
2 * Copyright (c) 2022 Telink Semiconductor (Shanghai) Co., Ltd. ("TELINK")
3 * All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 *****************************************************************************/
18 #include "mempool.h"
19 #include "utility.h"
20
mempool_init(mem_pool_t * pool,void * mem,int itemsize,int itemcount)21 mem_pool_t *mempool_init(mem_pool_t *pool, void *mem, int itemsize, int itemcount)
22 {
23 if (!pool || !mem) {
24 return (0);
25 }
26
27 pool->free_list = (mem_block_t *)mem;
28
29 u32 block_size = (u32)(MEMPOOL_ITEMSIZE_2_BLOCKSIZE(itemsize));
30 mem_block_t *tmp = (mem_block_t *)mem;
31 int i;
32 for (i = 0; i < itemcount - 1; ++i) {
33 tmp = tmp->next_block = (mem_block_t *)(((u32)tmp) + block_size);
34 }
35 tmp->next_block = 0;
36 return pool;
37 }
38
mempool_header(char * pd)39 mem_block_t *mempool_header(char *pd)
40 {
41 return (mem_block_t *)(pd - OFFSETOF(mem_block_t, data));
42 }
43
mempool_alloc(mem_pool_t * pool)44 void *mempool_alloc(mem_pool_t *pool)
45 {
46 if (!pool->free_list) {
47 return 0;
48 }
49
50 mem_block_t *tmp = pool->free_list;
51 pool->free_list = tmp->next_block;
52 return &tmp->data;
53 }
54
mempool_free(mem_pool_t * pool,void * p)55 void mempool_free(mem_pool_t *pool, void *p)
56 {
57 mem_block_t *tmp = mempool_header((char *)p);
58 tmp->next_block = pool->free_list;
59 pool->free_list = tmp;
60 }
61