1 /*
2  * Copyright (c) 2015 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_INCLUDE_SYS_RING_BUFFER_H_
8 #define ZEPHYR_INCLUDE_SYS_RING_BUFFER_H_
9 
10 #include <zephyr/kernel.h>
11 #include <zephyr/sys/util.h>
12 #include <errno.h>
13 
14 #ifdef __cplusplus
15 extern "C" {
16 #endif
17 
18 /** @cond INTERNAL_HIDDEN */
19 /* The limit is used by algorithm for distinguishing between empty and full
20  * state.
21  */
22 #define RING_BUFFER_MAX_SIZE 0x80000000U
23 
24 #define RING_BUFFER_SIZE_ASSERT_MSG \
25 	"Size too big"
26 /** @endcond */
27 
28 /**
29  * @file
30  * @defgroup ring_buffer_apis Ring Buffer APIs
31  * @ingroup datastructure_apis
32  *
33  * @brief Simple ring buffer implementation.
34  *
35  * @{
36  */
37 
38 /**
39  * @brief A structure to represent a ring buffer
40  */
41 struct ring_buf {
42 	/** @cond INTERNAL_HIDDEN */
43 	uint8_t *buffer;
44 	int32_t put_head;
45 	int32_t put_tail;
46 	int32_t put_base;
47 	int32_t get_head;
48 	int32_t get_tail;
49 	int32_t get_base;
50 	uint32_t size;
51 	/** @endcond */
52 };
53 
54 /**
55  * @brief Function to force ring_buf internal states to given value
56  *
57  * Any value other than 0 makes sense only in validation testing context.
58  */
ring_buf_internal_reset(struct ring_buf * buf,int32_t value)59 static inline void ring_buf_internal_reset(struct ring_buf *buf, int32_t value)
60 {
61 	buf->put_head = buf->put_tail = buf->put_base = value;
62 	buf->get_head = buf->get_tail = buf->get_base = value;
63 }
64 
65 /**
66  * @brief Define and initialize a ring buffer for byte data.
67  *
68  * This macro establishes a ring buffer of an arbitrary size.
69  * The basic storage unit is a byte.
70  *
71  * The ring buffer can be accessed outside the module where it is defined
72  * using:
73  *
74  * @code extern struct ring_buf <name>; @endcode
75  *
76  * @param name  Name of the ring buffer.
77  * @param size8 Size of ring buffer (in bytes).
78  */
79 #define RING_BUF_DECLARE(name, size8) \
80 	BUILD_ASSERT(size8 < RING_BUFFER_MAX_SIZE,\
81 		RING_BUFFER_SIZE_ASSERT_MSG); \
82 	static uint8_t __noinit _ring_buffer_data_##name[size8]; \
83 	struct ring_buf name = { \
84 		.buffer = _ring_buffer_data_##name, \
85 		.size = size8 \
86 	}
87 
88 /**
89  * @brief Define and initialize an "item based" ring buffer.
90  *
91  * This macro establishes an "item based" ring buffer. Each data item is
92  * an array of 32-bit words (from zero to 1020 bytes in length), coupled
93  * with a 16-bit type identifier and an 8-bit integer value.
94  *
95  * The ring buffer can be accessed outside the module where it is defined
96  * using:
97  *
98  * @code extern struct ring_buf <name>; @endcode
99  *
100  * @param name Name of the ring buffer.
101  * @param size32 Size of ring buffer (in 32-bit words).
102  */
103 #define RING_BUF_ITEM_DECLARE(name, size32) \
104 	BUILD_ASSERT((size32) < RING_BUFFER_MAX_SIZE / 4,\
105 		RING_BUFFER_SIZE_ASSERT_MSG); \
106 	static uint32_t __noinit _ring_buffer_data_##name[size32]; \
107 	struct ring_buf name = { \
108 		.buffer = (uint8_t *) _ring_buffer_data_##name, \
109 		.size = 4 * (size32) \
110 	}
111 
112 /**
113  * @brief Define and initialize an "item based" ring buffer.
114  *
115  * This exists for backward compatibility reasons. @ref RING_BUF_ITEM_DECLARE
116  * should be used instead.
117  *
118  * @param name Name of the ring buffer.
119  * @param size32 Size of ring buffer (in 32-bit words).
120  */
121 #define RING_BUF_ITEM_DECLARE_SIZE(name, size32) \
122 	RING_BUF_ITEM_DECLARE(name, size32)
123 
124 /**
125  * @brief Define and initialize a power-of-2 sized "item based" ring buffer.
126  *
127  * This macro establishes an "item based" ring buffer by specifying its
128  * size using a power of 2. This exists mainly for backward compatibility
129  * reasons. @ref RING_BUF_ITEM_DECLARE should be used instead.
130  *
131  * @param name Name of the ring buffer.
132  * @param pow Ring buffer size exponent.
133  */
134 #define RING_BUF_ITEM_DECLARE_POW2(name, pow) \
135 	RING_BUF_ITEM_DECLARE(name, BIT(pow))
136 
137 /**
138  * @brief Compute the ring buffer size in 32-bit needed to store an element
139  *
140  * The argument can be a type or an expression.
141  * Note: rounds up if the size is not a multiple of 32 bits.
142  *
143  * @param expr Expression or type to compute the size of
144  */
145 #define RING_BUF_ITEM_SIZEOF(expr) DIV_ROUND_UP(sizeof(expr), sizeof(uint32_t))
146 
147 /**
148  * @brief Initialize a ring buffer for byte data.
149  *
150  * This routine initializes a ring buffer, prior to its first use. It is only
151  * used for ring buffers not defined using RING_BUF_DECLARE.
152  *
153  * @param buf Address of ring buffer.
154  * @param size Ring buffer size (in bytes).
155  * @param data Ring buffer data area (uint8_t data[size]).
156  */
ring_buf_init(struct ring_buf * buf,uint32_t size,uint8_t * data)157 static inline void ring_buf_init(struct ring_buf *buf,
158 				 uint32_t size,
159 				 uint8_t *data)
160 {
161 	__ASSERT(size < RING_BUFFER_MAX_SIZE, RING_BUFFER_SIZE_ASSERT_MSG);
162 
163 	buf->size = size;
164 	buf->buffer = data;
165 	ring_buf_internal_reset(buf, 0);
166 }
167 
168 /**
169  * @brief Initialize an "item based" ring buffer.
170  *
171  * This routine initializes a ring buffer, prior to its first use. It is only
172  * used for ring buffers not defined using RING_BUF_ITEM_DECLARE.
173  *
174  * Each data item is an array of 32-bit words (from zero to 1020 bytes in
175  * length), coupled with a 16-bit type identifier and an 8-bit integer value.
176  *
177  * Each data item is an array of 32-bit words (from zero to 1020 bytes in
178  * length), coupled with a 16-bit type identifier and an 8-bit integer value.
179  *
180  * @param buf Address of ring buffer.
181  * @param size Ring buffer size (in 32-bit words)
182  * @param data Ring buffer data area (uint32_t data[size]).
183  */
ring_buf_item_init(struct ring_buf * buf,uint32_t size,uint32_t * data)184 static inline void ring_buf_item_init(struct ring_buf *buf,
185 				      uint32_t size,
186 				      uint32_t *data)
187 {
188 	__ASSERT(size < RING_BUFFER_MAX_SIZE / 4, RING_BUFFER_SIZE_ASSERT_MSG);
189 	ring_buf_init(buf, 4 * size, (uint8_t *)data);
190 }
191 
192 /**
193  * @brief Determine if a ring buffer is empty.
194  *
195  * @param buf Address of ring buffer.
196  *
197  * @return true if the ring buffer is empty, or false if not.
198  */
ring_buf_is_empty(struct ring_buf * buf)199 static inline bool ring_buf_is_empty(struct ring_buf *buf)
200 {
201 	return buf->get_head == buf->put_tail;
202 }
203 
204 /**
205  * @brief Reset ring buffer state.
206  *
207  * @param buf Address of ring buffer.
208  */
ring_buf_reset(struct ring_buf * buf)209 static inline void ring_buf_reset(struct ring_buf *buf)
210 {
211 	ring_buf_internal_reset(buf, 0);
212 }
213 
214 /**
215  * @brief Determine free space in a ring buffer.
216  *
217  * @param buf Address of ring buffer.
218  *
219  * @return Ring buffer free space (in bytes).
220  */
ring_buf_space_get(struct ring_buf * buf)221 static inline uint32_t ring_buf_space_get(struct ring_buf *buf)
222 {
223 	return buf->size - (buf->put_head - buf->get_tail);
224 }
225 
226 /**
227  * @brief Determine free space in an "item based" ring buffer.
228  *
229  * @param buf Address of ring buffer.
230  *
231  * @return Ring buffer free space (in 32-bit words).
232  */
ring_buf_item_space_get(struct ring_buf * buf)233 static inline uint32_t ring_buf_item_space_get(struct ring_buf *buf)
234 {
235 	return ring_buf_space_get(buf) / 4;
236 }
237 
238 /**
239  * @brief Return ring buffer capacity.
240  *
241  * @param buf Address of ring buffer.
242  *
243  * @return Ring buffer capacity (in bytes).
244  */
ring_buf_capacity_get(struct ring_buf * buf)245 static inline uint32_t ring_buf_capacity_get(struct ring_buf *buf)
246 {
247 	return buf->size;
248 }
249 
250 /**
251  * @brief Determine used space in a ring buffer.
252  *
253  * @param buf Address of ring buffer.
254  *
255  * @return Ring buffer space used (in bytes).
256  */
ring_buf_size_get(struct ring_buf * buf)257 static inline uint32_t ring_buf_size_get(struct ring_buf *buf)
258 {
259 	return buf->put_tail - buf->get_head;
260 }
261 
262 /**
263  * @brief Allocate buffer for writing data to a ring buffer.
264  *
265  * With this routine, memory copying can be reduced since internal ring buffer
266  * can be used directly by the user. Once data is written to allocated area
267  * number of bytes written must be confirmed (see @ref ring_buf_put_finish).
268  *
269  * @warning
270  * Use cases involving multiple writers to the ring buffer must prevent
271  * concurrent write operations, either by preventing all writers from
272  * being preempted or by using a mutex to govern writes to the ring buffer.
273  *
274  * @warning
275  * Ring buffer instance should not mix byte access and item access
276  * (calls prefixed with ring_buf_item_).
277  *
278  * @param[in]  buf  Address of ring buffer.
279  * @param[out] data Pointer to the address. It is set to a location within
280  *		    ring buffer.
281  * @param[in]  size Requested allocation size (in bytes).
282  *
283  * @return Size of allocated buffer which can be smaller than requested if
284  *	   there is not enough free space or buffer wraps.
285  */
286 uint32_t ring_buf_put_claim(struct ring_buf *buf,
287 			    uint8_t **data,
288 			    uint32_t size);
289 
290 /**
291  * @brief Indicate number of bytes written to allocated buffers.
292  *
293  * The number of bytes must be equal to or lower than the sum corresponding
294  * to all preceding @ref ring_buf_put_claim invocations (or even 0). Surplus
295  * bytes will be returned to the available free buffer space.
296  *
297  * @warning
298  * Use cases involving multiple writers to the ring buffer must prevent
299  * concurrent write operations, either by preventing all writers from
300  * being preempted or by using a mutex to govern writes to the ring buffer.
301  *
302  * @warning
303  * Ring buffer instance should not mix byte access and item access
304  * (calls prefixed with ring_buf_item_).
305  *
306  * @param  buf  Address of ring buffer.
307  * @param  size Number of valid bytes in the allocated buffers.
308  *
309  * @retval 0 Successful operation.
310  * @retval -EINVAL Provided @a size exceeds free space in the ring buffer.
311  */
312 int ring_buf_put_finish(struct ring_buf *buf, uint32_t size);
313 
314 /**
315  * @brief Write (copy) data to a ring buffer.
316  *
317  * This routine writes data to a ring buffer @a buf.
318  *
319  * @warning
320  * Use cases involving multiple writers to the ring buffer must prevent
321  * concurrent write operations, either by preventing all writers from
322  * being preempted or by using a mutex to govern writes to the ring buffer.
323  *
324  * @warning
325  * Ring buffer instance should not mix byte access and item access
326  * (calls prefixed with ring_buf_item_).
327  *
328  * @param buf Address of ring buffer.
329  * @param data Address of data.
330  * @param size Data size (in bytes).
331  *
332  * @retval Number of bytes written.
333  */
334 uint32_t ring_buf_put(struct ring_buf *buf, const uint8_t *data, uint32_t size);
335 
336 /**
337  * @brief Get address of a valid data in a ring buffer.
338  *
339  * With this routine, memory copying can be reduced since internal ring buffer
340  * can be used directly by the user. Once data is processed it must be freed
341  * using @ref ring_buf_get_finish.
342  *
343  * @warning
344  * Use cases involving multiple reads of the ring buffer must prevent
345  * concurrent read operations, either by preventing all readers from
346  * being preempted or by using a mutex to govern reads to the ring buffer.
347  *
348  * @warning
349  * Ring buffer instance should not mix byte access and item access
350  * (calls prefixed with ring_buf_item_).
351  *
352  * @param[in]  buf  Address of ring buffer.
353  * @param[out] data Pointer to the address. It is set to a location within
354  *		    ring buffer.
355  * @param[in]  size Requested size (in bytes).
356  *
357  * @return Number of valid bytes in the provided buffer which can be smaller
358  *	   than requested if there is not enough free space or buffer wraps.
359  */
360 uint32_t ring_buf_get_claim(struct ring_buf *buf,
361 			    uint8_t **data,
362 			    uint32_t size);
363 
364 /**
365  * @brief Indicate number of bytes read from claimed buffer.
366  *
367  * The number of bytes must be equal or lower than the sum corresponding to
368  * all preceding @ref ring_buf_get_claim invocations (or even 0). Surplus
369  * bytes will remain available in the buffer.
370  *
371  * @warning
372  * Use cases involving multiple reads of the ring buffer must prevent
373  * concurrent read operations, either by preventing all readers from
374  * being preempted or by using a mutex to govern reads to the ring buffer.
375  *
376  * @warning
377  * Ring buffer instance should not mix byte access and  item mode
378  * (calls prefixed with ring_buf_item_).
379  *
380  * @param  buf  Address of ring buffer.
381  * @param  size Number of bytes that can be freed.
382  *
383  * @retval 0 Successful operation.
384  * @retval -EINVAL Provided @a size exceeds valid bytes in the ring buffer.
385  */
386 int ring_buf_get_finish(struct ring_buf *buf, uint32_t size);
387 
388 /**
389  * @brief Read data from a ring buffer.
390  *
391  * This routine reads data from a ring buffer @a buf.
392  *
393  * @warning
394  * Use cases involving multiple reads of the ring buffer must prevent
395  * concurrent read operations, either by preventing all readers from
396  * being preempted or by using a mutex to govern reads to the ring buffer.
397  *
398  * @warning
399  * Ring buffer instance should not mix byte access and  item mode
400  * (calls prefixed with ring_buf_item_).
401  *
402  * @param buf  Address of ring buffer.
403  * @param data Address of the output buffer. Can be NULL to discard data.
404  * @param size Data size (in bytes).
405  *
406  * @retval Number of bytes written to the output buffer.
407  */
408 uint32_t ring_buf_get(struct ring_buf *buf, uint8_t *data, uint32_t size);
409 
410 /**
411  * @brief Peek at data from a ring buffer.
412  *
413  * This routine reads data from a ring buffer @a buf without removal.
414  *
415  * @warning
416  * Use cases involving multiple reads of the ring buffer must prevent
417  * concurrent read operations, either by preventing all readers from
418  * being preempted or by using a mutex to govern reads to the ring buffer.
419  *
420  * @warning
421  * Ring buffer instance should not mix byte access and  item mode
422  * (calls prefixed with ring_buf_item_).
423  *
424  * @warning
425  * Multiple calls to peek will result in the same data being 'peeked'
426  * multiple times. To remove data, use either @ref ring_buf_get or
427  * @ref ring_buf_get_claim followed by @ref ring_buf_get_finish with a
428  * non-zero `size`.
429  *
430  * @param buf  Address of ring buffer.
431  * @param data Address of the output buffer. Cannot be NULL.
432  * @param size Data size (in bytes).
433  *
434  * @retval Number of bytes written to the output buffer.
435  */
436 uint32_t ring_buf_peek(struct ring_buf *buf, uint8_t *data, uint32_t size);
437 
438 /**
439  * @brief Write a data item to a ring buffer.
440  *
441  * This routine writes a data item to ring buffer @a buf. The data item
442  * is an array of 32-bit words (from zero to 1020 bytes in length),
443  * coupled with a 16-bit type identifier and an 8-bit integer value.
444  *
445  * @warning
446  * Use cases involving multiple writers to the ring buffer must prevent
447  * concurrent write operations, either by preventing all writers from
448  * being preempted or by using a mutex to govern writes to the ring buffer.
449  *
450  * @param buf Address of ring buffer.
451  * @param type Data item's type identifier (application specific).
452  * @param value Data item's integer value (application specific).
453  * @param data Address of data item.
454  * @param size32 Data item size (number of 32-bit words).
455  *
456  * @retval 0 Data item was written.
457  * @retval -EMSGSIZE Ring buffer has insufficient free space.
458  */
459 int ring_buf_item_put(struct ring_buf *buf, uint16_t type, uint8_t value,
460 		      uint32_t *data, uint8_t size32);
461 
462 /**
463  * @brief Read a data item from a ring buffer.
464  *
465  * This routine reads a data item from ring buffer @a buf. The data item
466  * is an array of 32-bit words (up to 1020 bytes in length),
467  * coupled with a 16-bit type identifier and an 8-bit integer value.
468  *
469  * @warning
470  * Use cases involving multiple reads of the ring buffer must prevent
471  * concurrent read operations, either by preventing all readers from
472  * being preempted or by using a mutex to govern reads to the ring buffer.
473  *
474  * @param buf Address of ring buffer.
475  * @param type Area to store the data item's type identifier.
476  * @param value Area to store the data item's integer value.
477  * @param data Area to store the data item. Can be NULL to discard data.
478  * @param size32 Size of the data item storage area (number of 32-bit chunks).
479  *
480  * @retval 0 Data item was fetched; @a size32 now contains the number of
481  *         32-bit words read into data area @a data.
482  * @retval -EAGAIN Ring buffer is empty.
483  * @retval -EMSGSIZE Data area @a data is too small; @a size32 now contains
484  *         the number of 32-bit words needed.
485  */
486 int ring_buf_item_get(struct ring_buf *buf, uint16_t *type, uint8_t *value,
487 		      uint32_t *data, uint8_t *size32);
488 
489 /**
490  * @}
491  */
492 
493 #ifdef __cplusplus
494 }
495 #endif
496 
497 #endif /* ZEPHYR_INCLUDE_SYS_RING_BUFFER_H_ */
498