1 /* memslab.c */
2 
3 /*
4  * Copyright (c) 2020, Nordic Semiconductor ASA
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include "syskernel.h"
10 
11 #define MEM_SLAB_BLOCK_SIZE  (8)
12 #define MEM_SLAB_BLOCK_CNT   (NUMBER_OF_LOOPS)
13 #define MEM_SLAB_BLOCK_ALIGN (4)
14 
15 K_MEM_SLAB_DEFINE_STATIC(my_slab,
16 		  MEM_SLAB_BLOCK_SIZE,
17 		  MEM_SLAB_BLOCK_CNT,
18 		  MEM_SLAB_BLOCK_ALIGN);
19 
20 /* Array contains pointers to allocated regions. */
21 static void *slab_array[MEM_SLAB_BLOCK_CNT];
22 
23 /**
24  *
25  * @brief Memslab allocation test function.
26  *		  This test allocates available memory space.
27  *
28  * @param no_of_loops  Amount of loops to run.
29  * @param test_repeats Amount of test repeats per loop.
30  *
31  * @return NUmber of done loops.
32  */
mem_slab_alloc_test(int no_of_loops)33 static int mem_slab_alloc_test(int no_of_loops)
34 {
35 	int i;
36 
37 	for (i = 0; i < no_of_loops; i++) {
38 		if (k_mem_slab_alloc(&my_slab, &slab_array[i], K_NO_WAIT)
39 		    != 0) {
40 			return i;
41 		}
42 	}
43 
44 	return i;
45 }
46 
47 /**
48  *
49  * @brief Memslab free test function.
50  *		  This test frees memory previously allocated in
51  *		  @ref mem_slab_alloc_test.
52  *
53  * @param no_of_loops  Amount of loops to run.
54  * @param test_repeats Amount of test repeats per loop.
55  *
56  * @return NUmber of done loops.
57  */
mem_slab_free_test(int no_of_loops)58 static int mem_slab_free_test(int no_of_loops)
59 {
60 	int i;
61 
62 	for (i = 0; i < no_of_loops; i++) {
63 		k_mem_slab_free(&my_slab, slab_array[i]);
64 	}
65 
66 	return i;
67 }
68 
mem_slab_test(void)69 int mem_slab_test(void)
70 {
71 	uint32_t t;
72 	int i = 0;
73 	int return_value = 0;
74 
75 	/* Test k_mem_slab_alloc. */
76 	fprintf(output_file, sz_test_case_fmt,
77 		"Memslab #1");
78 	fprintf(output_file, sz_description,
79 		"\n\tk_mem_slab_alloc");
80 	printf(sz_test_start_fmt);
81 
82 	t = BENCH_START();
83 	i = mem_slab_alloc_test(number_of_loops);
84 	t = TIME_STAMP_DELTA_GET(t);
85 
86 	return_value += check_result(i, t);
87 
88 	/* Test k_mem_slab_free. */
89 	fprintf(output_file, sz_test_case_fmt,
90 		"Memslab #2");
91 	fprintf(output_file, sz_description,
92 		"\n\tk_mem_slab_free");
93 	printf(sz_test_start_fmt);
94 
95 	t = BENCH_START();
96 	i = mem_slab_free_test(number_of_loops);
97 	t = TIME_STAMP_DELTA_GET(t);
98 
99 	/* Check if all slabs were freed. */
100 	if (k_mem_slab_num_used_get(&my_slab) != 0) {
101 		i = 0;
102 	}
103 
104 	return_value += check_result(i, t);
105 
106 	return return_value;
107 }
108