1 /*
2  * Copyright (c) 2021 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #ifndef ZEPHYR_SUBSYS_LOGGING_LOG_CACHE_H_
7 #define ZEPHYR_SUBSYS_LOGGING_LOG_CACHE_H_
8 
9 #include <zephyr/sys/slist.h>
10 
11 #ifdef __cplusplus
12 extern "C" {
13 #endif
14 
15 struct log_cache_entry {
16 	sys_snode_t node;
17 	uintptr_t id;
18 	uint8_t data[];
19 };
20 
21 typedef bool (*log_cache_cmp_func_t)(uintptr_t id0, uintptr_t id1);
22 
23 struct log_cache_config {
24 	void *buf;
25 	size_t buf_len;
26 	size_t item_size;
27 	log_cache_cmp_func_t cmp;
28 };
29 
30 struct log_cache {
31 	sys_slist_t active;
32 	sys_slist_t idle;
33 	log_cache_cmp_func_t cmp;
34 	uint32_t hit;
35 	uint32_t miss;
36 	size_t item_size;
37 };
38 
39 int log_cache_init(struct log_cache *cache, const struct log_cache_config *config);
40 
41 /** @brief Get cached entry or buffer to fill new data for caching.
42  *
43  * @param[in] cache Cache object.
44  * @param[in] id Identication.
45  * @param[out] data Location.
46  *
47  * @retval true if entry with given @p id was found and @p data contains pointer to it.
48  * @retval false if entry was not found and @p data points to the empty location.
49  */
50 bool log_cache_get(struct log_cache *cache, uintptr_t id, uint8_t **data);
51 
52 /** @brief Put new entry into cache.
53  *
54  * @param cache Cache object.
55  * @param data Buffer filled with new data. It must point to the location returned by
56  *	       @ref log_cache_get.
57  */
58 void log_cache_put(struct log_cache *cache, uint8_t *data);
59 
60 /** @brief Release entry.
61  *
62  * Release entry that was allocated by @ref log_cache_get when requested id was
63  * not found in the cache. Releasing puts entry in idle list.
64  *
65  * @param cache Cache object.
66  * @param data It must point to the location returned by @ref log_cache_get.
67  */
68 void log_cache_release(struct log_cache *cache, uint8_t *data);
69 
70 /** @brief Get hit count.
71  *
72  * @param cache Cache object.
73  *
74  * @return Number of hits.
75  */
log_cache_get_hit(struct log_cache * cache)76 static inline uint32_t log_cache_get_hit(struct log_cache *cache)
77 {
78 	return cache->hit;
79 }
80 
81 /** @brief Get miss count.
82  *
83  * @param cache Cache object.
84  *
85  * @return Number of misses.
86  */
log_cache_get_miss(struct log_cache * cache)87 static inline uint32_t log_cache_get_miss(struct log_cache *cache)
88 {
89 	return cache->miss;
90 }
91 
92 #ifdef __cplusplus
93 }
94 #endif
95 
96 #endif /* ZEPHYR_SUBSYS_LOGGING_LOG_CACHE_H_ */
97