1 /*
2  * Copyright (c) 2017 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/ztest.h>
8 #include <zephyr/kernel.h>
9 #include <cmsis_os.h>
10 
11 struct mem_block {
12 	int member1;
13 	int member2;
14 };
15 
16 #define MAX_BLOCKS 10
17 
18 osPoolDef(MemPool, MAX_BLOCKS, struct mem_block);
19 
20 /**
21  * @brief Test memory pool allocation and free
22  *
23  * @see osPoolCreate(), osPoolAlloc(), osPoolFree(),
24  * osPoolCAlloc(), memcmp()
25  */
ZTEST(cmsis_mempool,test_mempool)26 ZTEST(cmsis_mempool, test_mempool)
27 {
28 	int i;
29 	osPoolId mempool_id;
30 	struct mem_block *addr_list[MAX_BLOCKS + 1];
31 	osStatus status_list[MAX_BLOCKS];
32 	static struct mem_block zeroblock;
33 
34 	mempool_id = osPoolCreate(osPool(MemPool));
35 	zassert_true(mempool_id != NULL, "mempool creation failed");
36 
37 	for (i = 0; i < MAX_BLOCKS; i++) {
38 		addr_list[i] = (struct mem_block *)osPoolAlloc(mempool_id);
39 		zassert_true(addr_list[i] != NULL, "mempool allocation failed");
40 	}
41 
42 	/* All blocks in mempool are allocated, any more allocation
43 	 * without free should fail
44 	 */
45 	addr_list[i] = (struct mem_block *)osPoolAlloc(mempool_id);
46 	zassert_true(addr_list[i] == NULL, "allocation happened."
47 			" Something's wrong!");
48 
49 	for (i = 0; i < MAX_BLOCKS; i++) {
50 		status_list[i] = osPoolFree(mempool_id, addr_list[i]);
51 		zassert_true(status_list[i] == osOK, "mempool free failed");
52 	}
53 
54 	for (i = 0; i < MAX_BLOCKS; i++) {
55 		addr_list[i] = (struct mem_block *)osPoolCAlloc(mempool_id);
56 		zassert_true(addr_list[i] != NULL, "mempool allocation failed");
57 		zassert_true(memcmp(addr_list[i], &zeroblock,
58 					sizeof(struct mem_block)) == 0,
59 			     "osPoolCAlloc didn't set mempool to 0");
60 	}
61 
62 	for (i = 0; i < MAX_BLOCKS; i++) {
63 		status_list[i] = osPoolFree(mempool_id, addr_list[i]);
64 		zassert_true(status_list[i] == osOK, "mempool free failed");
65 	}
66 }
67 ZTEST_SUITE(cmsis_mempool, NULL, NULL, NULL, NULL, NULL);
68