1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdlib.h>
8 #include <string.h>
9 #include "freertos/FreeRTOS.h"
10 #include "freertos/task.h"
11 #include "freertos/semphr.h"
12 #include "freertos/ringbuf.h"
13 
14 //32-bit alignment macros
15 #define rbALIGN_MASK (0x03)
16 #define rbALIGN_SIZE( xSize )       ( ( xSize + rbALIGN_MASK ) & ~rbALIGN_MASK )
17 #define rbCHECK_ALIGNED( pvPtr )    ( ( ( UBaseType_t ) ( pvPtr ) & rbALIGN_MASK ) == 0 )
18 
19 //Ring buffer flags
20 #define rbALLOW_SPLIT_FLAG          ( ( UBaseType_t ) 1 )   //The ring buffer allows items to be split
21 #define rbBYTE_BUFFER_FLAG          ( ( UBaseType_t ) 2 )   //The ring buffer is a byte buffer
22 #define rbBUFFER_FULL_FLAG          ( ( UBaseType_t ) 4 )   //The ring buffer is currently full (write pointer == free pointer)
23 #define rbBUFFER_STATIC_FLAG        ( ( UBaseType_t ) 8 )   //The ring buffer is statically allocated
24 
25 //Item flags
26 #define rbITEM_FREE_FLAG            ( ( UBaseType_t ) 1 )   //Item has been retrieved and returned by application, free to overwrite
27 #define rbITEM_DUMMY_DATA_FLAG      ( ( UBaseType_t ) 2 )   //Data from here to end of the ring buffer is dummy data. Restart reading at start of head of the buffer
28 #define rbITEM_SPLIT_FLAG           ( ( UBaseType_t ) 4 )   //Valid for RINGBUF_TYPE_ALLOWSPLIT, indicating that rest of the data is wrapped around
29 #define rbITEM_WRITTEN_FLAG         ( ( UBaseType_t ) 8 )   //Item has been written to by the application, thus can be read
30 
31 //Static allocation related
32 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
33 #define rbGET_TX_SEM_HANDLE( pxRingbuffer ) ( (SemaphoreHandle_t) &(pxRingbuffer->xTransSemStatic) )
34 #define rbGET_RX_SEM_HANDLE( pxRingbuffer ) ( (SemaphoreHandle_t) &(pxRingbuffer->xRecvSemStatic) )
35 #else
36 #define rbGET_TX_SEM_HANDLE( pxRingbuffer ) ( pxRingbuffer->xTransSemHandle )
37 #define rbGET_RX_SEM_HANDLE( pxRingbuffer ) ( pxRingbuffer->xRecvSemHandle )
38 #endif
39 
40 typedef struct {
41     //This size of this structure must be 32-bit aligned
42     size_t xItemLen;
43     UBaseType_t uxItemFlags;
44 } ItemHeader_t;
45 
46 #define rbHEADER_SIZE     sizeof(ItemHeader_t)
47 typedef struct RingbufferDefinition Ringbuffer_t;
48 typedef BaseType_t (*CheckItemFitsFunction_t)(Ringbuffer_t *pxRingbuffer, size_t xItemSize);
49 typedef void (*CopyItemFunction_t)(Ringbuffer_t *pxRingbuffer, const uint8_t *pcItem, size_t xItemSize);
50 typedef BaseType_t (*CheckItemAvailFunction_t) (Ringbuffer_t *pxRingbuffer);
51 typedef void *(*GetItemFunction_t)(Ringbuffer_t *pxRingbuffer, BaseType_t *pxIsSplit, size_t xMaxSize, size_t *pxItemSize);
52 typedef void (*ReturnItemFunction_t)(Ringbuffer_t *pxRingbuffer, uint8_t *pvItem);
53 typedef size_t (*GetCurMaxSizeFunction_t)(Ringbuffer_t *pxRingbuffer);
54 
55 typedef struct RingbufferDefinition {
56     size_t xSize;                               //Size of the data storage
57     size_t xMaxItemSize;                        //Maximum item size
58     UBaseType_t uxRingbufferFlags;              //Flags to indicate the type and status of ring buffer
59 
60     CheckItemFitsFunction_t xCheckItemFits;     //Function to check if item can currently fit in ring buffer
61     CopyItemFunction_t vCopyItem;               //Function to copy item to ring buffer
62     GetItemFunction_t pvGetItem;                //Function to get item from ring buffer
63     ReturnItemFunction_t vReturnItem;           //Function to return item to ring buffer
64     GetCurMaxSizeFunction_t xGetCurMaxSize;     //Function to get current free size
65 
66     uint8_t *pucAcquire;                        //Acquire Pointer. Points to where the next item should be acquired.
67     uint8_t *pucWrite;                          //Write Pointer. Points to where the next item should be written
68     uint8_t *pucRead;                           //Read Pointer. Points to where the next item should be read from
69     uint8_t *pucFree;                           //Free Pointer. Points to the last item that has yet to be returned to the ring buffer
70     uint8_t *pucHead;                           //Pointer to the start of the ring buffer storage area
71     uint8_t *pucTail;                           //Pointer to the end of the ring buffer storage area
72 
73     BaseType_t xItemsWaiting;                   //Number of items/bytes(for byte buffers) currently in ring buffer that have not yet been read
74     /*
75      * TransSem: Binary semaphore used to indicate to a blocked transmitting tasks
76      *           that more free space has become available or that the block has
77      *           timed out.
78      *
79      * RecvSem: Binary semaphore used to indicate to a blocked receiving task that
80      *          new data/item has been written to the ring buffer.
81      *
82      * Note - When static allocation is enabled, the two semaphores are always
83      *        statically stored in the ring buffer's control structure
84      *        regardless of whether the ring buffer is allocated dynamically or
85      *        statically. When static allocation is disabled, the two semaphores
86      *        are allocated dynamically and their handles stored instead, thus
87      *        making the ring buffer's control structure slightly smaller when
88      *        static allocation is disabled.
89      */
90 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
91     StaticSemaphore_t xTransSemStatic;
92     StaticSemaphore_t xRecvSemStatic;
93 #else
94     SemaphoreHandle_t xTransSemHandle;
95     SemaphoreHandle_t xRecvSemHandle;
96 #endif
97     portMUX_TYPE mux;                           //Spinlock required for SMP
98 } Ringbuffer_t;
99 
100 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
101 #if __GNUC_PREREQ(4, 6)
102 _Static_assert(sizeof(StaticRingbuffer_t) == sizeof(Ringbuffer_t), "StaticRingbuffer_t != Ringbuffer_t");
103 #endif
104 #endif
105 /*
106 Remark: A counting semaphore for items_buffered_sem would be more logical, but counting semaphores in
107 FreeRTOS need a maximum count, and allocate more memory the larger the maximum count is. Here, we
108 would need to set the maximum to the maximum amount of times a null-byte unit first in the buffer,
109 which is quite high and so would waste a fair amount of memory.
110 */
111 
112 /* --------------------------- Static Declarations -------------------------- */
113 /*
114  * WARNING: All of the following static functions (except generic functions)
115  * ARE NOT THREAD SAFE. Therefore they should only be called within a critical
116  * section (using spin locks)
117  */
118 
119 
120 //Initialize a ring buffer after space has been allocated for it
121 static void prvInitializeNewRingbuffer(size_t xBufferSize,
122                                        RingbufferType_t xBufferType,
123                                        Ringbuffer_t *pxNewRingbuffer,
124                                        uint8_t *pucRingbufferStorage);
125 
126 //Calculate current amount of free space (in bytes) in the ring buffer
127 static size_t prvGetFreeSize(Ringbuffer_t *pxRingbuffer);
128 
129 //Checks if an item/data is currently available for retrieval
130 static BaseType_t prvCheckItemAvail(Ringbuffer_t *pxRingbuffer);
131 
132 //Checks if an item will currently fit in a no-split/allow-split ring buffer
133 static BaseType_t prvCheckItemFitsDefault( Ringbuffer_t *pxRingbuffer, size_t xItemSize);
134 
135 //Checks if an item will currently fit in a byte buffer
136 static BaseType_t prvCheckItemFitsByteBuffer( Ringbuffer_t *pxRingbuffer, size_t xItemSize);
137 
138 /*
139 Copies an item to a no-split ring buffer
140 Entry:
141     - Must have already guaranteed there is sufficient space for item by calling prvCheckItemFitsDefault()
142 Exit:
143     - New item copied into ring buffer
144     - pucAcquire and pucWrite updated.
145     - Dummy item added if necessary
146 */
147 static void prvCopyItemNoSplit(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize);
148 
149 /*
150 Copies an item to a allow-split ring buffer
151 Entry:
152     - Must have already guaranteed there is sufficient space for item by calling prvCheckItemFitsDefault()
153 Exit:
154     - New item copied into ring buffer
155     - pucAcquire and pucWrite updated
156     - Item may be split
157 */
158 static void prvCopyItemAllowSplit(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize);
159 
160 //Copies an item to a byte buffer. Only call this function  after calling prvCheckItemFitsByteBuffer()
161 static void prvCopyItemByteBuf(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize);
162 
163 //Retrieve item from no-split/allow-split ring buffer. *pxIsSplit is set to pdTRUE if the retrieved item is split
164 /*
165 Entry:
166     - Must have already guaranteed that there is an item available for retrieval by calling prvCheckItemAvail()
167     - Guaranteed that pucREAD points to a valid item (i.e., not a dummy item)
168 Exit:
169     - Item is returned. Only first half returned if split
170     - pucREAD updated to point to next valid item to read, or equals to pucWrite if there are no more valid items to read
171     - pucREAD update must skip over dummy items
172 */
173 static void *prvGetItemDefault(Ringbuffer_t *pxRingbuffer,
174                                BaseType_t *pxIsSplit,
175                                size_t xUnusedParam,
176                                size_t *pxItemSize);
177 
178 //Retrieve data from byte buffer. If xMaxSize is 0, all continuous data is retrieved
179 static void *prvGetItemByteBuf(Ringbuffer_t *pxRingbuffer,
180                                BaseType_t *pxUnusedParam,
181                                size_t xMaxSize,
182                                size_t *pxItemSize);
183 
184 /*
185 Return an item to a split/no-split ring buffer
186 Exit:
187     - Item is marked free rbITEM_FREE_FLAG
188     - pucFree is progressed as far as possible, skipping over already freed items or dummy items
189 */
190 static void prvReturnItemDefault(Ringbuffer_t *pxRingbuffer, uint8_t *pucItem);
191 
192 //Return data to a byte buffer
193 static void prvReturnItemByteBuf(Ringbuffer_t *pxRingbuffer, uint8_t *pucItem);
194 
195 //Get the maximum size an item that can currently have if sent to a no-split ring buffer
196 static size_t prvGetCurMaxSizeNoSplit(Ringbuffer_t *pxRingbuffer);
197 
198 //Get the maximum size an item that can currently have if sent to a allow-split ring buffer
199 static size_t prvGetCurMaxSizeAllowSplit(Ringbuffer_t *pxRingbuffer);
200 
201 //Get the maximum size an item that can currently have if sent to a byte buffer
202 static size_t prvGetCurMaxSizeByteBuf(Ringbuffer_t *pxRingbuffer);
203 
204 /**
205  * Generic function used to retrieve an item/data from ring buffers. If called on
206  * an allow-split buffer, and pvItem2 and xItemSize2 are not NULL, both parts of
207  * a split item will be retrieved. xMaxSize will only take effect if called on
208  * byte buffers.
209  */
210 static BaseType_t prvReceiveGeneric(Ringbuffer_t *pxRingbuffer,
211                                     void **pvItem1,
212                                     void **pvItem2,
213                                     size_t *xItemSize1,
214                                     size_t *xItemSize2,
215                                     size_t xMaxSize,
216                                     TickType_t xTicksToWait);
217 
218 //Generic function used to retrieve an item/data from ring buffers in an ISR
219 static BaseType_t prvReceiveGenericFromISR(Ringbuffer_t *pxRingbuffer,
220                                            void **pvItem1,
221                                            void **pvItem2,
222                                            size_t *xItemSize1,
223                                            size_t *xItemSize2,
224                                            size_t xMaxSize);
225 
226 /* --------------------------- Static Definitions --------------------------- */
227 
prvInitializeNewRingbuffer(size_t xBufferSize,RingbufferType_t xBufferType,Ringbuffer_t * pxNewRingbuffer,uint8_t * pucRingbufferStorage)228 static void prvInitializeNewRingbuffer(size_t xBufferSize,
229                                        RingbufferType_t xBufferType,
230                                        Ringbuffer_t *pxNewRingbuffer,
231                                        uint8_t *pucRingbufferStorage)
232 {
233     //Initialize values
234     pxNewRingbuffer->xSize = xBufferSize;
235     pxNewRingbuffer->pucHead = pucRingbufferStorage;
236     pxNewRingbuffer->pucTail = pucRingbufferStorage + xBufferSize;
237     pxNewRingbuffer->pucFree = pucRingbufferStorage;
238     pxNewRingbuffer->pucRead = pucRingbufferStorage;
239     pxNewRingbuffer->pucWrite = pucRingbufferStorage;
240     pxNewRingbuffer->pucAcquire = pucRingbufferStorage;
241     pxNewRingbuffer->xItemsWaiting = 0;
242     pxNewRingbuffer->uxRingbufferFlags = 0;
243 
244     //Initialize type dependent values and function pointers
245     if (xBufferType == RINGBUF_TYPE_NOSPLIT) {
246         pxNewRingbuffer->xCheckItemFits = prvCheckItemFitsDefault;
247         pxNewRingbuffer->vCopyItem = prvCopyItemNoSplit;
248         pxNewRingbuffer->pvGetItem = prvGetItemDefault;
249         pxNewRingbuffer->vReturnItem = prvReturnItemDefault;
250         /*
251          * Worst case scenario is when the read/write/acquire/free pointers are all
252          * pointing to the halfway point of the buffer.
253          */
254         pxNewRingbuffer->xMaxItemSize = rbALIGN_SIZE(pxNewRingbuffer->xSize / 2) - rbHEADER_SIZE;
255         pxNewRingbuffer->xGetCurMaxSize = prvGetCurMaxSizeNoSplit;
256     } else if (xBufferType == RINGBUF_TYPE_ALLOWSPLIT) {
257         pxNewRingbuffer->uxRingbufferFlags |= rbALLOW_SPLIT_FLAG;
258         pxNewRingbuffer->xCheckItemFits = prvCheckItemFitsDefault;
259         pxNewRingbuffer->vCopyItem = prvCopyItemAllowSplit;
260         pxNewRingbuffer->pvGetItem = prvGetItemDefault;
261         pxNewRingbuffer->vReturnItem = prvReturnItemDefault;
262         //Worst case an item is split into two, incurring two headers of overhead
263         pxNewRingbuffer->xMaxItemSize = pxNewRingbuffer->xSize - (sizeof(ItemHeader_t) * 2);
264         pxNewRingbuffer->xGetCurMaxSize = prvGetCurMaxSizeAllowSplit;
265     } else { //Byte Buffer
266         pxNewRingbuffer->uxRingbufferFlags |= rbBYTE_BUFFER_FLAG;
267         pxNewRingbuffer->xCheckItemFits = prvCheckItemFitsByteBuffer;
268         pxNewRingbuffer->vCopyItem = prvCopyItemByteBuf;
269         pxNewRingbuffer->pvGetItem = prvGetItemByteBuf;
270         pxNewRingbuffer->vReturnItem = prvReturnItemByteBuf;
271         //Byte buffers do not incur any overhead
272         pxNewRingbuffer->xMaxItemSize = pxNewRingbuffer->xSize;
273         pxNewRingbuffer->xGetCurMaxSize = prvGetCurMaxSizeByteBuf;
274     }
275     xSemaphoreGive(rbGET_TX_SEM_HANDLE(pxNewRingbuffer));
276     portMUX_INITIALIZE(&pxNewRingbuffer->mux);
277 }
278 
prvGetFreeSize(Ringbuffer_t * pxRingbuffer)279 static size_t prvGetFreeSize(Ringbuffer_t *pxRingbuffer)
280 {
281     size_t xReturn;
282     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
283         xReturn =  0;
284     } else {
285         BaseType_t xFreeSize = pxRingbuffer->pucFree - pxRingbuffer->pucAcquire;
286         //Check if xFreeSize has underflowed
287         if (xFreeSize <= 0) {
288             xFreeSize += pxRingbuffer->xSize;
289         }
290         xReturn = xFreeSize;
291     }
292     configASSERT(xReturn <= pxRingbuffer->xSize);
293     return xReturn;
294 }
295 
prvCheckItemFitsDefault(Ringbuffer_t * pxRingbuffer,size_t xItemSize)296 static BaseType_t prvCheckItemFitsDefault( Ringbuffer_t *pxRingbuffer, size_t xItemSize)
297 {
298     //Check arguments and buffer state
299     configASSERT(rbCHECK_ALIGNED(pxRingbuffer->pucAcquire));              //pucAcquire is always aligned in no-split/allow-split ring buffers
300     configASSERT(pxRingbuffer->pucAcquire >= pxRingbuffer->pucHead && pxRingbuffer->pucAcquire < pxRingbuffer->pucTail);    //Check write pointer is within bounds
301 
302     size_t xTotalItemSize = rbALIGN_SIZE(xItemSize) + rbHEADER_SIZE;    //Rounded up aligned item size with header
303     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucFree) {
304         //Buffer is either complete empty or completely full
305         return (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) ? pdFALSE : pdTRUE;
306     }
307     if (pxRingbuffer->pucFree > pxRingbuffer->pucAcquire) {
308         //Free space does not wrap around
309         return (xTotalItemSize <= pxRingbuffer->pucFree - pxRingbuffer->pucAcquire) ? pdTRUE : pdFALSE;
310     }
311     //Free space wraps around
312     if (xTotalItemSize <= pxRingbuffer->pucTail - pxRingbuffer->pucAcquire) {
313         return pdTRUE;      //Item fits without wrapping around
314     }
315     //Check if item fits by wrapping
316     if (pxRingbuffer->uxRingbufferFlags & rbALLOW_SPLIT_FLAG) {
317         //Allow split wrapping incurs an extra header
318         return (xTotalItemSize + rbHEADER_SIZE <= pxRingbuffer->xSize - (pxRingbuffer->pucAcquire - pxRingbuffer->pucFree)) ? pdTRUE : pdFALSE;
319     } else {
320         return (xTotalItemSize <= pxRingbuffer->pucFree - pxRingbuffer->pucHead) ? pdTRUE : pdFALSE;
321     }
322 }
323 
prvCheckItemFitsByteBuffer(Ringbuffer_t * pxRingbuffer,size_t xItemSize)324 static BaseType_t prvCheckItemFitsByteBuffer( Ringbuffer_t *pxRingbuffer, size_t xItemSize)
325 {
326     //Check arguments and buffer state
327     configASSERT(pxRingbuffer->pucAcquire >= pxRingbuffer->pucHead && pxRingbuffer->pucAcquire < pxRingbuffer->pucTail);    //Check acquire pointer is within bounds
328 
329     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucFree) {
330         //Buffer is either complete empty or completely full
331         return (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) ? pdFALSE : pdTRUE;
332     }
333     if (pxRingbuffer->pucFree > pxRingbuffer->pucAcquire) {
334         //Free space does not wrap around
335         return (xItemSize <= pxRingbuffer->pucFree - pxRingbuffer->pucAcquire) ? pdTRUE : pdFALSE;
336     }
337     //Free space wraps around
338     return (xItemSize <= pxRingbuffer->xSize - (pxRingbuffer->pucAcquire - pxRingbuffer->pucFree)) ? pdTRUE : pdFALSE;
339 }
340 
prvAcquireItemNoSplit(Ringbuffer_t * pxRingbuffer,size_t xItemSize)341 static uint8_t* prvAcquireItemNoSplit(Ringbuffer_t *pxRingbuffer, size_t xItemSize)
342 {
343     //Check arguments and buffer state
344     size_t xAlignedItemSize = rbALIGN_SIZE(xItemSize);                  //Rounded up aligned item size
345     size_t xRemLen = pxRingbuffer->pucTail - pxRingbuffer->pucAcquire;    //Length from pucAcquire until end of buffer
346     configASSERT(rbCHECK_ALIGNED(pxRingbuffer->pucAcquire));              //pucAcquire is always aligned in no-split ring buffers
347     configASSERT(pxRingbuffer->pucAcquire >= pxRingbuffer->pucHead && pxRingbuffer->pucAcquire < pxRingbuffer->pucTail);    //Check write pointer is within bounds
348     configASSERT(xRemLen >= rbHEADER_SIZE);                             //Remaining length must be able to at least fit an item header
349 
350     //If remaining length can't fit item, set as dummy data and wrap around
351     if (xRemLen < xAlignedItemSize + rbHEADER_SIZE) {
352         ItemHeader_t *pxDummy = (ItemHeader_t *)pxRingbuffer->pucAcquire;
353         pxDummy->uxItemFlags = rbITEM_DUMMY_DATA_FLAG;      //Set remaining length as dummy data
354         pxDummy->xItemLen = 0;                              //Dummy data should have no length
355         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;     //Reset acquire pointer to wrap around
356     }
357 
358     //Item should be guaranteed to fit at this point. Set item header and copy data
359     ItemHeader_t *pxHeader = (ItemHeader_t *)pxRingbuffer->pucAcquire;
360     pxHeader->xItemLen = xItemSize;
361     pxHeader->uxItemFlags = 0;
362 
363     //hold the buffer address without touching pucWrite
364     uint8_t* item_address = pxRingbuffer->pucAcquire + rbHEADER_SIZE;
365     pxRingbuffer->pucAcquire += rbHEADER_SIZE + xAlignedItemSize;    //Advance pucAcquire past header and the item to next aligned address
366 
367     //After the allocation, add some padding after the buffer and correct the flags
368     //If current remaining length can't fit a header, wrap around write pointer
369     if (pxRingbuffer->pucTail - pxRingbuffer->pucAcquire < rbHEADER_SIZE) {
370         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;   //Wrap around pucAcquire
371     }
372     //Check if buffer is full
373     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucFree) {
374         //Mark the buffer as full to distinguish with an empty buffer
375         pxRingbuffer->uxRingbufferFlags |= rbBUFFER_FULL_FLAG;
376     }
377     return item_address;
378 }
379 
prvSendItemDoneNoSplit(Ringbuffer_t * pxRingbuffer,uint8_t * pucItem)380 static void prvSendItemDoneNoSplit(Ringbuffer_t *pxRingbuffer, uint8_t* pucItem)
381 {
382     //Check arguments and buffer state
383     configASSERT(rbCHECK_ALIGNED(pucItem));
384     configASSERT(pucItem >= pxRingbuffer->pucHead);
385     configASSERT(pucItem <= pxRingbuffer->pucTail);     //Inclusive of pucTail in the case of zero length item at the very end
386 
387     //Get and check header of the item
388     ItemHeader_t *pxCurHeader = (ItemHeader_t *)(pucItem - rbHEADER_SIZE);
389     configASSERT(pxCurHeader->xItemLen <= pxRingbuffer->xMaxItemSize);
390     configASSERT((pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG) == 0); //Dummy items should never have been written
391     configASSERT((pxCurHeader->uxItemFlags & rbITEM_WRITTEN_FLAG) == 0);       //Indicates item has already been written before
392     pxCurHeader->uxItemFlags &= ~rbITEM_SPLIT_FLAG;                         //Clear wrap flag if set (not strictly necessary)
393     pxCurHeader->uxItemFlags |= rbITEM_WRITTEN_FLAG;                           //Mark as written
394 
395     pxRingbuffer->xItemsWaiting++;
396 
397     /*
398      * Items might not be written in the order they were acquired. Move the
399      * write pointer up to the next item that has not been marked as written (by
400      * written flag) or up till the acquire pointer. When advancing the write
401      * pointer, items that have already been written or items with dummy data
402      * should be skipped over
403      */
404     pxCurHeader = (ItemHeader_t *)pxRingbuffer->pucWrite;
405     //Skip over Items that have already been written or are dummy items
406     while (((pxCurHeader->uxItemFlags & rbITEM_WRITTEN_FLAG) || (pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG)) && pxRingbuffer->pucWrite != pxRingbuffer->pucAcquire) {
407         if (pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG) {
408             pxCurHeader->uxItemFlags |= rbITEM_WRITTEN_FLAG;   //Mark as freed (not strictly necessary but adds redundancy)
409             pxRingbuffer->pucWrite = pxRingbuffer->pucHead;    //Wrap around due to dummy data
410         } else {
411             //Item with data that has already been written, advance write pointer past this item
412             size_t xAlignedItemSize = rbALIGN_SIZE(pxCurHeader->xItemLen);
413             pxRingbuffer->pucWrite += xAlignedItemSize + rbHEADER_SIZE;
414             //Redundancy check to ensure write pointer has not overshot buffer bounds
415             configASSERT(pxRingbuffer->pucWrite <= pxRingbuffer->pucHead + pxRingbuffer->xSize);
416         }
417         //Check if pucWrite requires wrap around
418         if ((pxRingbuffer->pucTail - pxRingbuffer->pucWrite) < rbHEADER_SIZE) {
419             pxRingbuffer->pucWrite = pxRingbuffer->pucHead;
420         }
421         pxCurHeader = (ItemHeader_t *)pxRingbuffer->pucWrite;      //Update header to point to item
422     }
423 }
424 
prvCopyItemNoSplit(Ringbuffer_t * pxRingbuffer,const uint8_t * pucItem,size_t xItemSize)425 static void prvCopyItemNoSplit(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize)
426 {
427     uint8_t* item_addr = prvAcquireItemNoSplit(pxRingbuffer, xItemSize);
428     memcpy(item_addr, pucItem, xItemSize);
429     prvSendItemDoneNoSplit(pxRingbuffer, item_addr);
430 }
431 
prvCopyItemAllowSplit(Ringbuffer_t * pxRingbuffer,const uint8_t * pucItem,size_t xItemSize)432 static void prvCopyItemAllowSplit(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize)
433 {
434     //Check arguments and buffer state
435     size_t xAlignedItemSize = rbALIGN_SIZE(xItemSize);                  //Rounded up aligned item size
436     size_t xRemLen = pxRingbuffer->pucTail - pxRingbuffer->pucAcquire;    //Length from pucAcquire until end of buffer
437     configASSERT(rbCHECK_ALIGNED(pxRingbuffer->pucAcquire));              //pucAcquire is always aligned in split ring buffers
438     configASSERT(pxRingbuffer->pucAcquire >= pxRingbuffer->pucHead && pxRingbuffer->pucAcquire < pxRingbuffer->pucTail);    //Check write pointer is within bounds
439     configASSERT(xRemLen >= rbHEADER_SIZE);                             //Remaining length must be able to at least fit an item header
440 
441     //Split item if necessary
442     if (xRemLen < xAlignedItemSize + rbHEADER_SIZE) {
443         //Write first part of the item
444         ItemHeader_t *pxFirstHeader = (ItemHeader_t *)pxRingbuffer->pucAcquire;
445         pxFirstHeader->uxItemFlags = 0;
446         pxFirstHeader->xItemLen = xRemLen - rbHEADER_SIZE;  //Fill remaining length with first part
447         pxRingbuffer->pucAcquire += rbHEADER_SIZE;            //Advance pucAcquire past header
448         xRemLen -= rbHEADER_SIZE;
449         if (xRemLen > 0) {
450             memcpy(pxRingbuffer->pucAcquire, pucItem, xRemLen);
451             pxRingbuffer->xItemsWaiting++;
452             //Update item arguments to account for data already copied
453             pucItem += xRemLen;
454             xItemSize -= xRemLen;
455             xAlignedItemSize -= xRemLen;
456             pxFirstHeader->uxItemFlags |= rbITEM_SPLIT_FLAG;        //There must be more data
457         } else {
458             //Remaining length was only large enough to fit header
459             pxFirstHeader->uxItemFlags |= rbITEM_DUMMY_DATA_FLAG;   //Item will completely be stored in 2nd part
460         }
461         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;             //Reset acquire pointer to start of buffer
462     }
463 
464     //Item (whole or second part) should be guaranteed to fit at this point
465     ItemHeader_t *pxSecondHeader = (ItemHeader_t *)pxRingbuffer->pucAcquire;
466     pxSecondHeader->xItemLen = xItemSize;
467     pxSecondHeader->uxItemFlags = 0;
468     pxRingbuffer->pucAcquire += rbHEADER_SIZE;     //Advance acquire pointer past header
469     memcpy(pxRingbuffer->pucAcquire, pucItem, xItemSize);
470     pxRingbuffer->xItemsWaiting++;
471     pxRingbuffer->pucAcquire += xAlignedItemSize;  //Advance pucAcquire past item to next aligned address
472 
473     //If current remaining length can't fit a header, wrap around write pointer
474     if (pxRingbuffer->pucTail - pxRingbuffer->pucAcquire < rbHEADER_SIZE) {
475         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;   //Wrap around pucAcquire
476     }
477     //Check if buffer is full
478     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucFree) {
479         //Mark the buffer as full to distinguish with an empty buffer
480         pxRingbuffer->uxRingbufferFlags |= rbBUFFER_FULL_FLAG;
481     }
482 
483     //currently the Split mode is not supported, pucWrite tracks the pucAcquire
484     pxRingbuffer->pucWrite = pxRingbuffer->pucAcquire;
485 }
486 
prvCopyItemByteBuf(Ringbuffer_t * pxRingbuffer,const uint8_t * pucItem,size_t xItemSize)487 static void prvCopyItemByteBuf(Ringbuffer_t *pxRingbuffer, const uint8_t *pucItem, size_t xItemSize)
488 {
489     //Check arguments and buffer state
490     configASSERT(pxRingbuffer->pucAcquire >= pxRingbuffer->pucHead && pxRingbuffer->pucAcquire < pxRingbuffer->pucTail);    //Check acquire pointer is within bounds
491 
492     size_t xRemLen = pxRingbuffer->pucTail - pxRingbuffer->pucAcquire;    //Length from pucAcquire until end of buffer
493     if (xRemLen < xItemSize) {
494         //Copy as much as possible into remaining length
495         memcpy(pxRingbuffer->pucAcquire, pucItem, xRemLen);
496         pxRingbuffer->xItemsWaiting += xRemLen;
497         //Update item arguments to account for data already written
498         pucItem += xRemLen;
499         xItemSize -= xRemLen;
500         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;     //Reset acquire pointer to start of buffer
501     }
502     //Copy all or remaining portion of the item
503     memcpy(pxRingbuffer->pucAcquire, pucItem, xItemSize);
504     pxRingbuffer->xItemsWaiting += xItemSize;
505     pxRingbuffer->pucAcquire += xItemSize;
506 
507     //Wrap around pucAcquire if it reaches the end
508     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucTail) {
509         pxRingbuffer->pucAcquire = pxRingbuffer->pucHead;
510     }
511     //Check if buffer is full
512     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucFree) {
513         pxRingbuffer->uxRingbufferFlags |= rbBUFFER_FULL_FLAG;      //Mark the buffer as full to avoid confusion with an empty buffer
514     }
515 
516     //Currently, acquiring memory is not supported in byte mode. pucWrite tracks the pucAcquire.
517     pxRingbuffer->pucWrite = pxRingbuffer->pucAcquire;
518 }
519 
prvCheckItemAvail(Ringbuffer_t * pxRingbuffer)520 static BaseType_t prvCheckItemAvail(Ringbuffer_t *pxRingbuffer)
521 {
522     if ((pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) && pxRingbuffer->pucRead != pxRingbuffer->pucFree) {
523         return pdFALSE;     //Byte buffers do not allow multiple retrievals before return
524     }
525     if ((pxRingbuffer->xItemsWaiting > 0) && ((pxRingbuffer->pucRead != pxRingbuffer->pucWrite) || (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG))) {
526         return pdTRUE;      //Items/data available for retrieval
527     } else {
528         return pdFALSE;     //No items/data available for retrieval
529     }
530 }
531 
prvGetItemDefault(Ringbuffer_t * pxRingbuffer,BaseType_t * pxIsSplit,size_t xUnusedParam,size_t * pxItemSize)532 static void *prvGetItemDefault(Ringbuffer_t *pxRingbuffer,
533                                BaseType_t *pxIsSplit,
534                                size_t xUnusedParam,
535                                size_t *pxItemSize)
536 {
537     //Check arguments and buffer state
538     ItemHeader_t *pxHeader = (ItemHeader_t *)pxRingbuffer->pucRead;
539     configASSERT(pxIsSplit != NULL);
540     configASSERT((pxRingbuffer->xItemsWaiting > 0) && ((pxRingbuffer->pucRead != pxRingbuffer->pucWrite) || (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG)));   //Check there are items to be read
541     configASSERT(rbCHECK_ALIGNED(pxRingbuffer->pucRead));           //pucRead is always aligned in split ring buffers
542     configASSERT(pxRingbuffer->pucRead >= pxRingbuffer->pucHead && pxRingbuffer->pucRead < pxRingbuffer->pucTail);      //Check read pointer is within bounds
543     configASSERT((pxHeader->xItemLen <= pxRingbuffer->xMaxItemSize) || (pxHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG));
544 
545     uint8_t *pcReturn;
546     //Wrap around if dummy data (dummy data indicates wrap around in no-split buffers)
547     if (pxHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG) {
548         pxRingbuffer->pucRead = pxRingbuffer->pucHead;
549         //Check for errors with the next item
550         pxHeader = (ItemHeader_t *)pxRingbuffer->pucRead;
551         configASSERT(pxHeader->xItemLen <= pxRingbuffer->xMaxItemSize);
552     }
553     pcReturn = pxRingbuffer->pucRead + rbHEADER_SIZE;    //Get pointer to part of item containing data (point past the header)
554     if (pxHeader->xItemLen == 0) {
555         //Inclusive of pucTail for special case where item of zero length just fits at the end of the buffer
556         configASSERT(pcReturn >= pxRingbuffer->pucHead && pcReturn <= pxRingbuffer->pucTail);
557     } else {
558         //Exclusive of pucTail if length is larger than zero, pcReturn should never point to pucTail
559         configASSERT(pcReturn >= pxRingbuffer->pucHead && pcReturn < pxRingbuffer->pucTail);
560     }
561     *pxItemSize = pxHeader->xItemLen;   //Get length of item
562     pxRingbuffer->xItemsWaiting --;     //Update item count
563     *pxIsSplit = (pxHeader->uxItemFlags & rbITEM_SPLIT_FLAG) ? pdTRUE : pdFALSE;
564 
565     pxRingbuffer->pucRead += rbHEADER_SIZE + rbALIGN_SIZE(pxHeader->xItemLen);   //Update pucRead
566     //Check if pucRead requires wrap around
567     if ((pxRingbuffer->pucTail - pxRingbuffer->pucRead) < rbHEADER_SIZE) {
568         pxRingbuffer->pucRead = pxRingbuffer->pucHead;
569     }
570     return (void *)pcReturn;
571 }
572 
prvGetItemByteBuf(Ringbuffer_t * pxRingbuffer,BaseType_t * pxUnusedParam,size_t xMaxSize,size_t * pxItemSize)573 static void *prvGetItemByteBuf(Ringbuffer_t *pxRingbuffer,
574                                BaseType_t *pxUnusedParam,
575                                size_t xMaxSize,
576                                size_t *pxItemSize)
577 {
578     //Check arguments and buffer state
579     configASSERT((pxRingbuffer->xItemsWaiting > 0) && ((pxRingbuffer->pucRead != pxRingbuffer->pucWrite) || (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG)));   //Check there are items to be read
580     configASSERT(pxRingbuffer->pucRead >= pxRingbuffer->pucHead && pxRingbuffer->pucRead < pxRingbuffer->pucTail);    //Check read pointer is within bounds
581     configASSERT(pxRingbuffer->pucRead == pxRingbuffer->pucFree);
582 
583     uint8_t *ret = pxRingbuffer->pucRead;
584     if ((pxRingbuffer->pucRead > pxRingbuffer->pucWrite) || (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG)) {     //Available data wraps around
585         //Return contiguous piece from read pointer until buffer tail, or xMaxSize
586         if (xMaxSize == 0 || pxRingbuffer->pucTail - pxRingbuffer->pucRead <= xMaxSize) {
587             //All contiguous data from read pointer to tail
588             *pxItemSize = pxRingbuffer->pucTail - pxRingbuffer->pucRead;
589             pxRingbuffer->xItemsWaiting -= pxRingbuffer->pucTail - pxRingbuffer->pucRead;
590             pxRingbuffer->pucRead = pxRingbuffer->pucHead;  //Wrap around read pointer
591         } else {
592             //Return xMaxSize amount of data
593             *pxItemSize = xMaxSize;
594             pxRingbuffer->xItemsWaiting -= xMaxSize;
595             pxRingbuffer->pucRead += xMaxSize;  //Advance read pointer past retrieved data
596         }
597     } else {    //Available data is contiguous between read and write pointer
598         if (xMaxSize == 0 || pxRingbuffer->pucWrite - pxRingbuffer->pucRead <= xMaxSize) {
599             //Return all contiguous data from read to write pointer
600             *pxItemSize = pxRingbuffer->pucWrite - pxRingbuffer->pucRead;
601             pxRingbuffer->xItemsWaiting -= pxRingbuffer->pucWrite - pxRingbuffer->pucRead;
602             pxRingbuffer->pucRead = pxRingbuffer->pucWrite;
603         } else {
604             //Return xMaxSize data from read pointer
605             *pxItemSize = xMaxSize;
606             pxRingbuffer->xItemsWaiting -= xMaxSize;
607             pxRingbuffer->pucRead += xMaxSize;  //Advance read pointer past retrieved data
608 
609         }
610     }
611     return (void *)ret;
612 }
613 
prvReturnItemDefault(Ringbuffer_t * pxRingbuffer,uint8_t * pucItem)614 static void prvReturnItemDefault(Ringbuffer_t *pxRingbuffer, uint8_t *pucItem)
615 {
616     //Check arguments and buffer state
617     configASSERT(rbCHECK_ALIGNED(pucItem));
618     configASSERT(pucItem >= pxRingbuffer->pucHead);
619     configASSERT(pucItem <= pxRingbuffer->pucTail);     //Inclusive of pucTail in the case of zero length item at the very end
620 
621     //Get and check header of the item
622     ItemHeader_t *pxCurHeader = (ItemHeader_t *)(pucItem - rbHEADER_SIZE);
623     configASSERT(pxCurHeader->xItemLen <= pxRingbuffer->xMaxItemSize);
624     configASSERT((pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG) == 0); //Dummy items should never have been read
625     configASSERT((pxCurHeader->uxItemFlags & rbITEM_FREE_FLAG) == 0);       //Indicates item has already been returned before
626     pxCurHeader->uxItemFlags &= ~rbITEM_SPLIT_FLAG;                         //Clear wrap flag if set (not strictly necessary)
627     pxCurHeader->uxItemFlags |= rbITEM_FREE_FLAG;                           //Mark as free
628 
629     /*
630      * Items might not be returned in the order they were retrieved. Move the free pointer
631      * up to the next item that has not been marked as free (by free flag) or up
632      * till the read pointer. When advancing the free pointer, items that have already been
633      * freed or items with dummy data should be skipped over
634      */
635     pxCurHeader = (ItemHeader_t *)pxRingbuffer->pucFree;
636     //Skip over Items that have already been freed or are dummy items
637     while (((pxCurHeader->uxItemFlags & rbITEM_FREE_FLAG) || (pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG)) && pxRingbuffer->pucFree != pxRingbuffer->pucRead) {
638         if (pxCurHeader->uxItemFlags & rbITEM_DUMMY_DATA_FLAG) {
639             pxCurHeader->uxItemFlags |= rbITEM_FREE_FLAG;   //Mark as freed (not strictly necessary but adds redundancy)
640             pxRingbuffer->pucFree = pxRingbuffer->pucHead;    //Wrap around due to dummy data
641         } else {
642             //Item with data that has already been freed, advance free pointer past this item
643             size_t xAlignedItemSize = rbALIGN_SIZE(pxCurHeader->xItemLen);
644             pxRingbuffer->pucFree += xAlignedItemSize + rbHEADER_SIZE;
645             //Redundancy check to ensure free pointer has not overshot buffer bounds
646             configASSERT(pxRingbuffer->pucFree <= pxRingbuffer->pucHead + pxRingbuffer->xSize);
647         }
648         //Check if pucFree requires wrap around
649         if ((pxRingbuffer->pucTail - pxRingbuffer->pucFree) < rbHEADER_SIZE) {
650             pxRingbuffer->pucFree = pxRingbuffer->pucHead;
651         }
652         pxCurHeader = (ItemHeader_t *)pxRingbuffer->pucFree;      //Update header to point to item
653     }
654 
655     //Check if the buffer full flag should be reset
656     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
657         if (pxRingbuffer->pucFree != pxRingbuffer->pucAcquire) {
658             pxRingbuffer->uxRingbufferFlags &= ~rbBUFFER_FULL_FLAG;
659         } else if (pxRingbuffer->pucFree == pxRingbuffer->pucAcquire && pxRingbuffer->pucFree == pxRingbuffer->pucRead) {
660             //Special case where a full buffer is completely freed in one go
661             pxRingbuffer->uxRingbufferFlags &= ~rbBUFFER_FULL_FLAG;
662         }
663     }
664 }
665 
prvReturnItemByteBuf(Ringbuffer_t * pxRingbuffer,uint8_t * pucItem)666 static void prvReturnItemByteBuf(Ringbuffer_t *pxRingbuffer, uint8_t *pucItem)
667 {
668     //Check pointer points to address inside buffer
669     configASSERT((uint8_t *)pucItem >= pxRingbuffer->pucHead);
670     configASSERT((uint8_t *)pucItem < pxRingbuffer->pucTail);
671     //Free the read memory. Simply moves free pointer to read pointer as byte buffers do not allow multiple outstanding reads
672     pxRingbuffer->pucFree = pxRingbuffer->pucRead;
673     //If buffer was full before, reset full flag as free pointer has moved
674     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
675         pxRingbuffer->uxRingbufferFlags &= ~rbBUFFER_FULL_FLAG;
676     }
677 }
678 
prvGetCurMaxSizeNoSplit(Ringbuffer_t * pxRingbuffer)679 static size_t prvGetCurMaxSizeNoSplit(Ringbuffer_t *pxRingbuffer)
680 {
681     BaseType_t xFreeSize;
682     //Check if buffer is full
683     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
684         return 0;
685     }
686     if (pxRingbuffer->pucAcquire < pxRingbuffer->pucFree) {
687         //Free space is contiguous between pucAcquire and pucFree
688         xFreeSize = pxRingbuffer->pucFree - pxRingbuffer->pucAcquire;
689     } else {
690         //Free space wraps around (or overlapped at pucHead), select largest
691         //contiguous free space as no-split items require contiguous space
692         size_t xSize1 = pxRingbuffer->pucTail - pxRingbuffer->pucAcquire;
693         size_t xSize2 = pxRingbuffer->pucFree - pxRingbuffer->pucHead;
694         xFreeSize = (xSize1 > xSize2) ? xSize1 : xSize2;
695     }
696 
697     //No-split ring buffer items need space for a header
698     xFreeSize -= rbHEADER_SIZE;
699 
700     //Check for xFreeSize < 0 before checking xFreeSize > pxRingbuffer->xMaxItemSize
701     //to avoid incorrect comparison operation when xFreeSize is negative
702     if (xFreeSize < 0) {
703         //Occurs when free space is less than header size
704         xFreeSize = 0;
705     } else if (xFreeSize > pxRingbuffer->xMaxItemSize) {
706         //Limit free size to be within bounds
707         xFreeSize = pxRingbuffer->xMaxItemSize;
708     }
709     return xFreeSize;
710 }
711 
prvGetCurMaxSizeAllowSplit(Ringbuffer_t * pxRingbuffer)712 static size_t prvGetCurMaxSizeAllowSplit(Ringbuffer_t *pxRingbuffer)
713 {
714     BaseType_t xFreeSize;
715     //Check if buffer is full
716     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
717         return 0;
718     }
719     if (pxRingbuffer->pucAcquire == pxRingbuffer->pucHead && pxRingbuffer->pucFree == pxRingbuffer->pucHead) {
720         //Check for special case where pucAcquire and pucFree are both at pucHead
721         xFreeSize = pxRingbuffer->xSize - rbHEADER_SIZE;
722     } else if (pxRingbuffer->pucAcquire < pxRingbuffer->pucFree) {
723         //Free space is contiguous between pucAcquire and pucFree, requires single header
724         xFreeSize = (pxRingbuffer->pucFree - pxRingbuffer->pucAcquire) - rbHEADER_SIZE;
725     } else {
726         //Free space wraps around, requires two headers
727         xFreeSize = (pxRingbuffer->pucFree - pxRingbuffer->pucHead) +
728                     (pxRingbuffer->pucTail - pxRingbuffer->pucAcquire) -
729                     (rbHEADER_SIZE * 2);
730     }
731 
732     //Check for xFreeSize < 0 before checking xFreeSize > pxRingbuffer->xMaxItemSize
733     //to avoid incorrect comparison operation when xFreeSize is negative
734     if (xFreeSize < 0) {
735         xFreeSize = 0;
736     } else if (xFreeSize > pxRingbuffer->xMaxItemSize) {
737         //Limit free size to be within bounds
738         xFreeSize = pxRingbuffer->xMaxItemSize;
739     }
740     return xFreeSize;
741 }
742 
prvGetCurMaxSizeByteBuf(Ringbuffer_t * pxRingbuffer)743 static size_t prvGetCurMaxSizeByteBuf(Ringbuffer_t *pxRingbuffer)
744 {
745     BaseType_t xFreeSize;
746     //Check if buffer is full
747     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_FULL_FLAG) {
748         return 0;
749     }
750 
751     /*
752      * Return whatever space is available depending on relative positions of the free
753      * pointer and Acquire pointer. There is no overhead of headers in this mode
754      */
755     xFreeSize = pxRingbuffer->pucFree - pxRingbuffer->pucAcquire;
756     if (xFreeSize <= 0) {
757         xFreeSize += pxRingbuffer->xSize;
758     }
759     return xFreeSize;
760 }
761 
prvReceiveGeneric(Ringbuffer_t * pxRingbuffer,void ** pvItem1,void ** pvItem2,size_t * xItemSize1,size_t * xItemSize2,size_t xMaxSize,TickType_t xTicksToWait)762 static BaseType_t prvReceiveGeneric(Ringbuffer_t *pxRingbuffer,
763                                     void **pvItem1,
764                                     void **pvItem2,
765                                     size_t *xItemSize1,
766                                     size_t *xItemSize2,
767                                     size_t xMaxSize,
768                                     TickType_t xTicksToWait)
769 {
770     BaseType_t xReturn = pdFALSE;
771     BaseType_t xReturnSemaphore = pdFALSE;
772     TickType_t xTicksEnd = xTaskGetTickCount() + xTicksToWait;
773     TickType_t xTicksRemaining = xTicksToWait;
774     while (xTicksRemaining <= xTicksToWait) {   //xTicksToWait will underflow once xTaskGetTickCount() > ticks_end
775         //Block until more free space becomes available or timeout
776         if (xSemaphoreTake(rbGET_RX_SEM_HANDLE(pxRingbuffer), xTicksRemaining) != pdTRUE) {
777             xReturn = pdFALSE;     //Timed out attempting to get semaphore
778             break;
779         }
780 
781         //Semaphore obtained, check if item can be retrieved
782         portENTER_CRITICAL(&pxRingbuffer->mux);
783         if (prvCheckItemAvail(pxRingbuffer) == pdTRUE) {
784             //Item is available for retrieval
785             BaseType_t xIsSplit;
786             if (pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) {
787                 //Second argument (pxIsSplit) is unused for byte buffers
788                 *pvItem1 = pxRingbuffer->pvGetItem(pxRingbuffer, NULL, xMaxSize, xItemSize1);
789             } else {
790                 //Third argument (xMaxSize) is unused for no-split/allow-split buffers
791                 *pvItem1 = pxRingbuffer->pvGetItem(pxRingbuffer, &xIsSplit, 0, xItemSize1);
792             }
793             //Check for item split if configured to do so
794             if ((pxRingbuffer->uxRingbufferFlags & rbALLOW_SPLIT_FLAG) && (pvItem2 != NULL) && (xItemSize2 != NULL)) {
795                 if (xIsSplit == pdTRUE) {
796                     *pvItem2 = pxRingbuffer->pvGetItem(pxRingbuffer, &xIsSplit, 0, xItemSize2);
797                     configASSERT(*pvItem2 < *pvItem1);  //Check wrap around has occurred
798                     configASSERT(xIsSplit == pdFALSE);  //Second part should not have wrapped flag
799                 } else {
800                     *pvItem2 = NULL;
801                 }
802             }
803             xReturn = pdTRUE;
804             if (pxRingbuffer->xItemsWaiting > 0) {
805                 xReturnSemaphore = pdTRUE;
806             }
807             portEXIT_CRITICAL(&pxRingbuffer->mux);
808             break;
809         }
810         //No item available for retrieval, adjust ticks and take the semaphore again
811         if (xTicksToWait != portMAX_DELAY) {
812             xTicksRemaining = xTicksEnd - xTaskGetTickCount();
813         }
814         portEXIT_CRITICAL(&pxRingbuffer->mux);
815         /*
816          * Gap between critical section and re-acquiring of the semaphore. If
817          * semaphore is given now, priority inversion might occur (see docs)
818          */
819     }
820 
821     if (xReturnSemaphore == pdTRUE) {
822         xSemaphoreGive(rbGET_RX_SEM_HANDLE(pxRingbuffer));  //Give semaphore back so other tasks can retrieve
823     }
824     return xReturn;
825 }
826 
prvReceiveGenericFromISR(Ringbuffer_t * pxRingbuffer,void ** pvItem1,void ** pvItem2,size_t * xItemSize1,size_t * xItemSize2,size_t xMaxSize)827 static BaseType_t prvReceiveGenericFromISR(Ringbuffer_t *pxRingbuffer,
828                                            void **pvItem1,
829                                            void **pvItem2,
830                                            size_t *xItemSize1,
831                                            size_t *xItemSize2,
832                                            size_t xMaxSize)
833 {
834     BaseType_t xReturn = pdFALSE;
835     BaseType_t xReturnSemaphore = pdFALSE;
836 
837     portENTER_CRITICAL_ISR(&pxRingbuffer->mux);
838     if(prvCheckItemAvail(pxRingbuffer) == pdTRUE) {
839         BaseType_t xIsSplit;
840         if (pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) {
841             //Second argument (pxIsSplit) is unused for byte buffers
842             *pvItem1 = pxRingbuffer->pvGetItem(pxRingbuffer, NULL, xMaxSize, xItemSize1);
843         } else {
844             //Third argument (xMaxSize) is unused for no-split/allow-split buffers
845             *pvItem1 = pxRingbuffer->pvGetItem(pxRingbuffer, &xIsSplit, 0, xItemSize1);
846         }
847         //Check for item split if configured to do so
848         if ((pxRingbuffer->uxRingbufferFlags & rbALLOW_SPLIT_FLAG) && pvItem2 != NULL && xItemSize2 != NULL) {
849             if (xIsSplit == pdTRUE) {
850                 *pvItem2 = pxRingbuffer->pvGetItem(pxRingbuffer, &xIsSplit, 0, xItemSize2);
851                 configASSERT(*pvItem2 < *pvItem1);  //Check wrap around has occurred
852                 configASSERT(xIsSplit == pdFALSE);  //Second part should not have wrapped flag
853             } else {
854                 *pvItem2 = NULL;
855             }
856         }
857         xReturn = pdTRUE;
858         if (pxRingbuffer->xItemsWaiting > 0) {
859             xReturnSemaphore = pdTRUE;
860         }
861     }
862     portEXIT_CRITICAL_ISR(&pxRingbuffer->mux);
863 
864     if (xReturnSemaphore == pdTRUE) {
865         xSemaphoreGiveFromISR(rbGET_RX_SEM_HANDLE(pxRingbuffer), NULL);  //Give semaphore back so other tasks can retrieve
866     }
867     return xReturn;
868 }
869 
870 /* --------------------------- Public Definitions --------------------------- */
871 
xRingbufferCreate(size_t xBufferSize,RingbufferType_t xBufferType)872 RingbufHandle_t xRingbufferCreate(size_t xBufferSize, RingbufferType_t xBufferType)
873 {
874     configASSERT(xBufferSize > 0);
875     configASSERT(xBufferType < RINGBUF_TYPE_MAX);
876 
877     //Allocate memory
878     if (xBufferType != RINGBUF_TYPE_BYTEBUF) {
879         xBufferSize = rbALIGN_SIZE(xBufferSize);    //xBufferSize is rounded up for no-split/allow-split buffers
880     }
881     Ringbuffer_t *pxNewRingbuffer = calloc(1, sizeof(Ringbuffer_t));
882     uint8_t *pucRingbufferStorage = malloc(xBufferSize);
883     if (pxNewRingbuffer == NULL || pucRingbufferStorage == NULL) {
884         goto err;
885     }
886 
887     //Initialize Semaphores
888 #if ( configSUPPORT_STATIC_ALLOCATION == 1)
889     //We don't use the handles for static semaphores, and xSemaphoreCreateBinaryStatic will never fail thus no need to check static case
890     xSemaphoreCreateBinaryStatic(&(pxNewRingbuffer->xTransSemStatic));
891     xSemaphoreCreateBinaryStatic(&(pxNewRingbuffer->xRecvSemStatic));
892 #else
893     pxNewRingbuffer->xTransSemHandle = xSemaphoreCreateBinary();
894     pxNewRingbuffer->xRecvSemHandle = xSemaphoreCreateBinary();
895     if (pxNewRingbuffer->xTransSemHandle == NULL || pxNewRingbuffer->xRecvSemHandle == NULL) {
896         if (pxNewRingbuffer->xTransSemHandle != NULL) {
897             vSemaphoreDelete(pxNewRingbuffer->xTransSemHandle);
898         }
899         if (pxNewRingbuffer->xRecvSemHandle != NULL) {
900             vSemaphoreDelete(pxNewRingbuffer->xRecvSemHandle);
901         }
902         goto err;
903     }
904 #endif
905 
906     prvInitializeNewRingbuffer(xBufferSize, xBufferType, pxNewRingbuffer, pucRingbufferStorage);
907     return (RingbufHandle_t)pxNewRingbuffer;
908 
909 err:
910     //An error has occurred, Free memory and return NULL
911     free(pxNewRingbuffer);
912     free(pucRingbufferStorage);
913     return NULL;
914 }
915 
xRingbufferCreateNoSplit(size_t xItemSize,size_t xItemNum)916 RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum)
917 {
918     return xRingbufferCreate((rbALIGN_SIZE(xItemSize) + rbHEADER_SIZE) * xItemNum, RINGBUF_TYPE_NOSPLIT);
919 }
920 
921 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
xRingbufferCreateStatic(size_t xBufferSize,RingbufferType_t xBufferType,uint8_t * pucRingbufferStorage,StaticRingbuffer_t * pxStaticRingbuffer)922 RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize,
923                                         RingbufferType_t xBufferType,
924                                         uint8_t *pucRingbufferStorage,
925                                         StaticRingbuffer_t *pxStaticRingbuffer)
926 {
927     //Check arguments
928     configASSERT(xBufferSize > 0);
929     configASSERT(xBufferType < RINGBUF_TYPE_MAX);
930     configASSERT(pucRingbufferStorage != NULL && pxStaticRingbuffer != NULL);
931     if (xBufferType != RINGBUF_TYPE_BYTEBUF) {
932         //No-split/allow-split buffer sizes must be 32-bit aligned
933         configASSERT(rbCHECK_ALIGNED(xBufferSize));
934     }
935 
936     Ringbuffer_t *pxNewRingbuffer = (Ringbuffer_t *)pxStaticRingbuffer;
937     xSemaphoreCreateBinaryStatic(&(pxNewRingbuffer->xTransSemStatic));
938     xSemaphoreCreateBinaryStatic(&(pxNewRingbuffer->xRecvSemStatic));
939     prvInitializeNewRingbuffer(xBufferSize, xBufferType, pxNewRingbuffer, pucRingbufferStorage);
940     pxNewRingbuffer->uxRingbufferFlags |= rbBUFFER_STATIC_FLAG;
941     return (RingbufHandle_t)pxNewRingbuffer;
942 }
943 #endif
944 
xRingbufferSendAcquire(RingbufHandle_t xRingbuffer,void ** ppvItem,size_t xItemSize,TickType_t xTicksToWait)945 BaseType_t xRingbufferSendAcquire(RingbufHandle_t xRingbuffer, void **ppvItem, size_t xItemSize, TickType_t xTicksToWait)
946 {
947     //Check arguments
948     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
949     configASSERT(pxRingbuffer);
950     configASSERT(ppvItem != NULL || xItemSize == 0);
951     //currently only supported in NoSplit buffers
952     configASSERT((pxRingbuffer->uxRingbufferFlags & (rbBYTE_BUFFER_FLAG | rbALLOW_SPLIT_FLAG)) == 0);
953 
954     *ppvItem = NULL;
955     if (xItemSize > pxRingbuffer->xMaxItemSize) {
956         return pdFALSE;     //Data will never ever fit in the queue.
957     }
958     if ((pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) && xItemSize == 0) {
959         return pdTRUE;      //Sending 0 bytes to byte buffer has no effect
960     }
961 
962     //Attempt to send an item
963     BaseType_t xReturn = pdFALSE;
964     BaseType_t xReturnSemaphore = pdFALSE;
965     TickType_t xTicksEnd = xTaskGetTickCount() + xTicksToWait;
966     TickType_t xTicksRemaining = xTicksToWait;
967     while (xTicksRemaining <= xTicksToWait) {   //xTicksToWait will underflow once xTaskGetTickCount() > ticks_end
968         //Block until more free space becomes available or timeout
969         if (xSemaphoreTake(rbGET_TX_SEM_HANDLE(pxRingbuffer), xTicksRemaining) != pdTRUE) {
970             xReturn = pdFALSE;
971             break;
972         }
973 
974         //Semaphore obtained, check if item can fit
975         portENTER_CRITICAL(&pxRingbuffer->mux);
976         if(pxRingbuffer->xCheckItemFits(pxRingbuffer, xItemSize) == pdTRUE) {
977             //Item will fit, copy item
978             *ppvItem = prvAcquireItemNoSplit(pxRingbuffer, xItemSize);
979             xReturn = pdTRUE;
980             //Check if the free semaphore should be returned to allow other tasks to send
981             if (prvGetFreeSize(pxRingbuffer) > 0) {
982                 xReturnSemaphore = pdTRUE;
983             }
984             portEXIT_CRITICAL(&pxRingbuffer->mux);
985             break;
986         }
987         //Item doesn't fit, adjust ticks and take the semaphore again
988         if (xTicksToWait != portMAX_DELAY) {
989             xTicksRemaining = xTicksEnd - xTaskGetTickCount();
990         }
991         portEXIT_CRITICAL(&pxRingbuffer->mux);
992         /*
993          * Gap between critical section and re-acquiring of the semaphore. If
994          * semaphore is given now, priority inversion might occur (see docs)
995          */
996     }
997 
998     if (xReturnSemaphore == pdTRUE) {
999         xSemaphoreGive(rbGET_TX_SEM_HANDLE(pxRingbuffer));  //Give back semaphore so other tasks can acquire
1000     }
1001     return xReturn;
1002 }
1003 
xRingbufferSendComplete(RingbufHandle_t xRingbuffer,void * pvItem)1004 BaseType_t xRingbufferSendComplete(RingbufHandle_t xRingbuffer, void *pvItem)
1005 {
1006     //Check arguments
1007     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1008     configASSERT(pxRingbuffer);
1009     configASSERT(pvItem != NULL);
1010     configASSERT((pxRingbuffer->uxRingbufferFlags & (rbBYTE_BUFFER_FLAG | rbALLOW_SPLIT_FLAG)) == 0);
1011 
1012     portENTER_CRITICAL(&pxRingbuffer->mux);
1013     prvSendItemDoneNoSplit(pxRingbuffer, pvItem);
1014     portEXIT_CRITICAL(&pxRingbuffer->mux);
1015 
1016     xSemaphoreGive(rbGET_RX_SEM_HANDLE(pxRingbuffer));
1017     return pdTRUE;
1018 }
1019 
xRingbufferSend(RingbufHandle_t xRingbuffer,const void * pvItem,size_t xItemSize,TickType_t xTicksToWait)1020 BaseType_t xRingbufferSend(RingbufHandle_t xRingbuffer,
1021                            const void *pvItem,
1022                            size_t xItemSize,
1023                            TickType_t xTicksToWait)
1024 {
1025     //Check arguments
1026     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1027     configASSERT(pxRingbuffer);
1028     configASSERT(pvItem != NULL || xItemSize == 0);
1029     if (xItemSize > pxRingbuffer->xMaxItemSize) {
1030         return pdFALSE;     //Data will never ever fit in the queue.
1031     }
1032     if ((pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) && xItemSize == 0) {
1033         return pdTRUE;      //Sending 0 bytes to byte buffer has no effect
1034     }
1035 
1036     //Attempt to send an item
1037     BaseType_t xReturn = pdFALSE;
1038     BaseType_t xReturnSemaphore = pdFALSE;
1039     TickType_t xTicksEnd = xTaskGetTickCount() + xTicksToWait;
1040     TickType_t xTicksRemaining = xTicksToWait;
1041     while (xTicksRemaining <= xTicksToWait) {   //xTicksToWait will underflow once xTaskGetTickCount() > ticks_end
1042         //Block until more free space becomes available or timeout
1043         if (xSemaphoreTake(rbGET_TX_SEM_HANDLE(pxRingbuffer), xTicksRemaining) != pdTRUE) {
1044             xReturn = pdFALSE;
1045             break;
1046         }
1047         //Semaphore obtained, check if item can fit
1048         portENTER_CRITICAL(&pxRingbuffer->mux);
1049         if(pxRingbuffer->xCheckItemFits(pxRingbuffer, xItemSize) == pdTRUE) {
1050             //Item will fit, copy item
1051             pxRingbuffer->vCopyItem(pxRingbuffer, pvItem, xItemSize);
1052             xReturn = pdTRUE;
1053             //Check if the free semaphore should be returned to allow other tasks to send
1054             if (prvGetFreeSize(pxRingbuffer) > 0) {
1055                 xReturnSemaphore = pdTRUE;
1056             }
1057             portEXIT_CRITICAL(&pxRingbuffer->mux);
1058             break;
1059         }
1060         //Item doesn't fit, adjust ticks and take the semaphore again
1061         if (xTicksToWait != portMAX_DELAY) {
1062             xTicksRemaining = xTicksEnd - xTaskGetTickCount();
1063         }
1064         portEXIT_CRITICAL(&pxRingbuffer->mux);
1065         /*
1066          * Gap between critical section and re-acquiring of the semaphore. If
1067          * semaphore is given now, priority inversion might occur (see docs)
1068          */
1069     }
1070 
1071     if (xReturnSemaphore == pdTRUE) {
1072         xSemaphoreGive(rbGET_TX_SEM_HANDLE(pxRingbuffer));  //Give back semaphore so other tasks can send
1073     }
1074     if (xReturn == pdTRUE) {
1075         //Indicate item was successfully sent
1076         xSemaphoreGive(rbGET_RX_SEM_HANDLE(pxRingbuffer));
1077     }
1078     return xReturn;
1079 }
1080 
xRingbufferSendFromISR(RingbufHandle_t xRingbuffer,const void * pvItem,size_t xItemSize,BaseType_t * pxHigherPriorityTaskWoken)1081 BaseType_t xRingbufferSendFromISR(RingbufHandle_t xRingbuffer,
1082                                   const void *pvItem,
1083                                   size_t xItemSize,
1084                                   BaseType_t *pxHigherPriorityTaskWoken)
1085 {
1086     //Check arguments
1087     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1088     configASSERT(pxRingbuffer);
1089     configASSERT(pvItem != NULL || xItemSize == 0);
1090     if (xItemSize > pxRingbuffer->xMaxItemSize) {
1091         return pdFALSE;     //Data will never ever fit in the queue.
1092     }
1093     if ((pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG) && xItemSize == 0) {
1094         return pdTRUE;      //Sending 0 bytes to byte buffer has no effect
1095     }
1096 
1097     //Attempt to send an item
1098     BaseType_t xReturn;
1099     BaseType_t xReturnSemaphore = pdFALSE;
1100     portENTER_CRITICAL_ISR(&pxRingbuffer->mux);
1101     if (pxRingbuffer->xCheckItemFits(xRingbuffer, xItemSize) == pdTRUE) {
1102         pxRingbuffer->vCopyItem(xRingbuffer, pvItem, xItemSize);
1103         xReturn = pdTRUE;
1104         //Check if the free semaphore should be returned to allow other tasks to send
1105         if (prvGetFreeSize(pxRingbuffer) > 0) {
1106             xReturnSemaphore = pdTRUE;
1107         }
1108     } else {
1109         xReturn = pdFALSE;
1110     }
1111     portEXIT_CRITICAL_ISR(&pxRingbuffer->mux);
1112 
1113     if (xReturnSemaphore == pdTRUE) {
1114         xSemaphoreGiveFromISR(rbGET_TX_SEM_HANDLE(pxRingbuffer), pxHigherPriorityTaskWoken);  //Give back semaphore so other tasks can send
1115     }
1116     if (xReturn == pdTRUE) {
1117         //Indicate item was successfully sent
1118         xSemaphoreGiveFromISR(rbGET_RX_SEM_HANDLE(pxRingbuffer), pxHigherPriorityTaskWoken);
1119     }
1120     return xReturn;
1121 }
1122 
xRingbufferReceive(RingbufHandle_t xRingbuffer,size_t * pxItemSize,TickType_t xTicksToWait)1123 void *xRingbufferReceive(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait)
1124 {
1125     //Check arguments
1126     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1127     configASSERT(pxRingbuffer);
1128 
1129     //Attempt to retrieve an item
1130     void *pvTempItem;
1131     size_t xTempSize;
1132     if (prvReceiveGeneric(pxRingbuffer, &pvTempItem, NULL, &xTempSize, NULL, 0, xTicksToWait) == pdTRUE) {
1133         if (pxItemSize != NULL) {
1134             *pxItemSize = xTempSize;
1135         }
1136         return pvTempItem;
1137     } else {
1138         return NULL;
1139     }
1140 }
1141 
xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer,size_t * pxItemSize)1142 void *xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize)
1143 {
1144     //Check arguments
1145     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1146     configASSERT(pxRingbuffer);
1147 
1148     //Attempt to retrieve an item
1149     void *pvTempItem;
1150     size_t xTempSize;
1151     if (prvReceiveGenericFromISR(pxRingbuffer, &pvTempItem, NULL, &xTempSize, NULL, 0) == pdTRUE) {
1152         if (pxItemSize != NULL) {
1153             *pxItemSize = xTempSize;
1154         }
1155         return pvTempItem;
1156     } else {
1157         return NULL;
1158     }
1159 }
1160 
xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer,void ** ppvHeadItem,void ** ppvTailItem,size_t * pxHeadItemSize,size_t * pxTailItemSize,TickType_t xTicksToWait)1161 BaseType_t xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer,
1162                                    void **ppvHeadItem,
1163                                    void **ppvTailItem,
1164                                    size_t *pxHeadItemSize,
1165                                    size_t *pxTailItemSize,
1166                                    TickType_t xTicksToWait)
1167 {
1168     //Check arguments
1169     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1170     configASSERT(pxRingbuffer);
1171     configASSERT(pxRingbuffer->uxRingbufferFlags & rbALLOW_SPLIT_FLAG);
1172     configASSERT(ppvHeadItem != NULL && ppvTailItem != NULL);
1173 
1174     //Attempt to retrieve multiple items
1175     void *pvTempHeadItem, *pvTempTailItem;
1176     size_t xTempHeadSize, xTempTailSize;
1177     if (prvReceiveGeneric(pxRingbuffer, &pvTempHeadItem, &pvTempTailItem, &xTempHeadSize, &xTempTailSize, 0, xTicksToWait) == pdTRUE) {
1178         //At least one item was retrieved
1179         *ppvHeadItem = pvTempHeadItem;
1180         if(pxHeadItemSize != NULL){
1181             *pxHeadItemSize = xTempHeadSize;
1182         }
1183         //Check to see if a second item was also retrieved
1184         if (pvTempTailItem != NULL) {
1185             *ppvTailItem = pvTempTailItem;
1186             if (pxTailItemSize != NULL) {
1187                 *pxTailItemSize = xTempTailSize;
1188             }
1189         } else {
1190             *ppvTailItem = NULL;
1191         }
1192         return pdTRUE;
1193     } else {
1194         //No items retrieved
1195         *ppvHeadItem = NULL;
1196         *ppvTailItem = NULL;
1197         return pdFALSE;
1198     }
1199 }
1200 
xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer,void ** ppvHeadItem,void ** ppvTailItem,size_t * pxHeadItemSize,size_t * pxTailItemSize)1201 BaseType_t xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer,
1202                                           void **ppvHeadItem,
1203                                           void **ppvTailItem,
1204                                           size_t *pxHeadItemSize,
1205                                           size_t *pxTailItemSize)
1206 {
1207     //Check arguments
1208     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1209     configASSERT(pxRingbuffer);
1210     configASSERT(pxRingbuffer->uxRingbufferFlags & rbALLOW_SPLIT_FLAG);
1211     configASSERT(ppvHeadItem != NULL && ppvTailItem != NULL);
1212 
1213     //Attempt to retrieve multiple items
1214     void *pvTempHeadItem = NULL, *pvTempTailItem = NULL;
1215     size_t xTempHeadSize, xTempTailSize;
1216     if (prvReceiveGenericFromISR(pxRingbuffer, &pvTempHeadItem, &pvTempTailItem, &xTempHeadSize, &xTempTailSize, 0) == pdTRUE) {
1217         //At least one item was received
1218         *ppvHeadItem = pvTempHeadItem;
1219         if (pxHeadItemSize != NULL) {
1220             *pxHeadItemSize = xTempHeadSize;
1221         }
1222         //Check to see if a second item was also retrieved
1223         if (pvTempTailItem != NULL) {
1224             *ppvTailItem = pvTempTailItem;
1225             if (pxTailItemSize != NULL) {
1226                 *pxTailItemSize = xTempTailSize;
1227             }
1228         } else {
1229             *ppvTailItem = NULL;
1230         }
1231         return pdTRUE;
1232     } else {
1233         *ppvHeadItem = NULL;
1234         *ppvTailItem = NULL;
1235         return pdFALSE;
1236     }
1237 }
1238 
xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer,size_t * pxItemSize,TickType_t xTicksToWait,size_t xMaxSize)1239 void *xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer,
1240                              size_t *pxItemSize,
1241                              TickType_t xTicksToWait,
1242                              size_t xMaxSize)
1243 {
1244     //Check arguments
1245     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1246     configASSERT(pxRingbuffer);
1247     configASSERT(pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG);    //This function should only be called for byte buffers
1248     if (xMaxSize == 0) {
1249         return NULL;
1250     }
1251 
1252     //Attempt to retrieve up to xMaxSize bytes
1253     void *pvTempItem;
1254     size_t xTempSize;
1255     if (prvReceiveGeneric(pxRingbuffer, &pvTempItem, NULL, &xTempSize, NULL, xMaxSize, xTicksToWait) == pdTRUE) {
1256         if (pxItemSize != NULL) {
1257             *pxItemSize = xTempSize;
1258         }
1259         return pvTempItem;
1260     } else {
1261         return NULL;
1262     }
1263 }
1264 
xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer,size_t * pxItemSize,size_t xMaxSize)1265 void *xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize, size_t xMaxSize)
1266 {
1267     //Check arguments
1268     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1269     configASSERT(pxRingbuffer);
1270     configASSERT(pxRingbuffer->uxRingbufferFlags & rbBYTE_BUFFER_FLAG);    //This function should only be called for byte buffers
1271     if (xMaxSize == 0) {
1272         return NULL;
1273     }
1274 
1275     //Attempt to retrieve up to xMaxSize bytes
1276     void *pvTempItem;
1277     size_t xTempSize;
1278     if (prvReceiveGenericFromISR(pxRingbuffer, &pvTempItem, NULL, &xTempSize, NULL, xMaxSize) == pdTRUE) {
1279         if (pxItemSize != NULL) {
1280             *pxItemSize = xTempSize;
1281         }
1282         return pvTempItem;
1283     } else {
1284         return NULL;
1285     }
1286 }
1287 
vRingbufferReturnItem(RingbufHandle_t xRingbuffer,void * pvItem)1288 void vRingbufferReturnItem(RingbufHandle_t xRingbuffer, void *pvItem)
1289 {
1290     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1291     configASSERT(pxRingbuffer);
1292     configASSERT(pvItem != NULL);
1293 
1294     portENTER_CRITICAL(&pxRingbuffer->mux);
1295     pxRingbuffer->vReturnItem(pxRingbuffer, (uint8_t *)pvItem);
1296     portEXIT_CRITICAL(&pxRingbuffer->mux);
1297     xSemaphoreGive(rbGET_TX_SEM_HANDLE(pxRingbuffer));
1298 }
1299 
vRingbufferReturnItemFromISR(RingbufHandle_t xRingbuffer,void * pvItem,BaseType_t * pxHigherPriorityTaskWoken)1300 void vRingbufferReturnItemFromISR(RingbufHandle_t xRingbuffer, void *pvItem, BaseType_t *pxHigherPriorityTaskWoken)
1301 {
1302     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1303     configASSERT(pxRingbuffer);
1304     configASSERT(pvItem != NULL);
1305 
1306     portENTER_CRITICAL_ISR(&pxRingbuffer->mux);
1307     pxRingbuffer->vReturnItem(pxRingbuffer, (uint8_t *)pvItem);
1308     portEXIT_CRITICAL_ISR(&pxRingbuffer->mux);
1309     xSemaphoreGiveFromISR(rbGET_TX_SEM_HANDLE(pxRingbuffer), pxHigherPriorityTaskWoken);
1310 }
1311 
vRingbufferDelete(RingbufHandle_t xRingbuffer)1312 void vRingbufferDelete(RingbufHandle_t xRingbuffer)
1313 {
1314     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1315     configASSERT(pxRingbuffer);
1316 
1317     vSemaphoreDelete(rbGET_TX_SEM_HANDLE(pxRingbuffer));
1318     vSemaphoreDelete(rbGET_RX_SEM_HANDLE(pxRingbuffer));
1319 
1320 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
1321     if (pxRingbuffer->uxRingbufferFlags & rbBUFFER_STATIC_FLAG) {
1322         //Ring buffer was statically allocated, no need to free
1323         return;
1324     }
1325 #endif
1326     free(pxRingbuffer->pucHead);
1327     free(pxRingbuffer);
1328 }
1329 
xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer)1330 size_t xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer)
1331 {
1332     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1333     configASSERT(pxRingbuffer);
1334     return pxRingbuffer->xMaxItemSize;
1335 }
1336 
xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer)1337 size_t xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer)
1338 {
1339     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1340     configASSERT(pxRingbuffer);
1341 
1342     size_t xFreeSize;
1343     portENTER_CRITICAL(&pxRingbuffer->mux);
1344     xFreeSize = pxRingbuffer->xGetCurMaxSize(pxRingbuffer);
1345     portEXIT_CRITICAL(&pxRingbuffer->mux);
1346     return xFreeSize;
1347 }
1348 
xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer,QueueSetHandle_t xQueueSet)1349 BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet)
1350 {
1351     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1352     configASSERT(pxRingbuffer);
1353 
1354     BaseType_t xReturn;
1355     portENTER_CRITICAL(&pxRingbuffer->mux);
1356     //Cannot add semaphore to queue set if semaphore is not empty. Temporarily hold semaphore
1357     BaseType_t xHoldSemaphore = xSemaphoreTake(rbGET_RX_SEM_HANDLE(pxRingbuffer), 0);
1358     xReturn = xQueueAddToSet(rbGET_RX_SEM_HANDLE(pxRingbuffer), xQueueSet);
1359     if (xHoldSemaphore == pdTRUE) {
1360         //Return semaphore if temporarily held
1361         configASSERT(xSemaphoreGive(rbGET_RX_SEM_HANDLE(pxRingbuffer)) == pdTRUE);
1362     }
1363     portEXIT_CRITICAL(&pxRingbuffer->mux);
1364     return xReturn;
1365 }
1366 
xRingbufferCanRead(RingbufHandle_t xRingbuffer,QueueSetMemberHandle_t xMember)1367 BaseType_t xRingbufferCanRead(RingbufHandle_t xRingbuffer, QueueSetMemberHandle_t xMember)
1368 {
1369     //Check if the selected queue set member is the ring buffer's read semaphore
1370     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1371     configASSERT(pxRingbuffer);
1372     return (rbGET_RX_SEM_HANDLE(pxRingbuffer) == xMember) ? pdTRUE : pdFALSE;
1373 }
1374 
xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer,QueueSetHandle_t xQueueSet)1375 BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet)
1376 {
1377     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1378     configASSERT(pxRingbuffer);
1379 
1380     BaseType_t xReturn;
1381     portENTER_CRITICAL(&pxRingbuffer->mux);
1382     //Cannot remove semaphore from queue set if semaphore is not empty. Temporarily hold semaphore
1383     BaseType_t xHoldSemaphore = xSemaphoreTake(rbGET_RX_SEM_HANDLE(pxRingbuffer), 0);
1384     xReturn = xQueueRemoveFromSet(rbGET_RX_SEM_HANDLE(pxRingbuffer), xQueueSet);
1385     if (xHoldSemaphore == pdTRUE) {
1386         //Return semaphore if temporarily held
1387         configASSERT(xSemaphoreGive(rbGET_RX_SEM_HANDLE(pxRingbuffer)) == pdTRUE);
1388     }
1389     portEXIT_CRITICAL(&pxRingbuffer->mux);
1390     return xReturn;
1391 }
1392 
vRingbufferGetInfo(RingbufHandle_t xRingbuffer,UBaseType_t * uxFree,UBaseType_t * uxRead,UBaseType_t * uxWrite,UBaseType_t * uxAcquire,UBaseType_t * uxItemsWaiting)1393 void vRingbufferGetInfo(RingbufHandle_t xRingbuffer,
1394                         UBaseType_t *uxFree,
1395                         UBaseType_t *uxRead,
1396                         UBaseType_t *uxWrite,
1397                         UBaseType_t *uxAcquire,
1398                         UBaseType_t *uxItemsWaiting)
1399 {
1400     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1401     configASSERT(pxRingbuffer);
1402 
1403     portENTER_CRITICAL(&pxRingbuffer->mux);
1404     if (uxFree != NULL) {
1405         *uxFree = (UBaseType_t)(pxRingbuffer->pucFree - pxRingbuffer->pucHead);
1406     }
1407     if (uxRead != NULL) {
1408         *uxRead = (UBaseType_t)(pxRingbuffer->pucRead - pxRingbuffer->pucHead);
1409     }
1410     if (uxWrite != NULL) {
1411         *uxWrite = (UBaseType_t)(pxRingbuffer->pucWrite - pxRingbuffer->pucHead);
1412     }
1413     if (uxAcquire != NULL) {
1414         *uxAcquire = (UBaseType_t)(pxRingbuffer->pucAcquire - pxRingbuffer->pucHead);
1415     }
1416     if (uxItemsWaiting != NULL) {
1417         *uxItemsWaiting = (UBaseType_t)(pxRingbuffer->xItemsWaiting);
1418     }
1419     portEXIT_CRITICAL(&pxRingbuffer->mux);
1420 }
1421 
xRingbufferPrintInfo(RingbufHandle_t xRingbuffer)1422 void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer)
1423 {
1424     Ringbuffer_t *pxRingbuffer = (Ringbuffer_t *)xRingbuffer;
1425     configASSERT(pxRingbuffer);
1426     printf("Rb size:%d\tfree: %d\trptr: %d\tfreeptr: %d\twptr: %d, aptr: %d\n",
1427            pxRingbuffer->xSize, prvGetFreeSize(pxRingbuffer),
1428            pxRingbuffer->pucRead - pxRingbuffer->pucHead,
1429            pxRingbuffer->pucFree - pxRingbuffer->pucHead,
1430            pxRingbuffer->pucWrite - pxRingbuffer->pucHead,
1431            pxRingbuffer->pucAcquire - pxRingbuffer->pucHead);
1432 }
1433