FreeRTOS Advanced Chapter 5---freertos queue analysis

Source: Internet
Author: User

FreeRTOS provides a variety of inter-mission communication methods, including:
    • Task notifications (version V8.2 and above)
    • Queue
    • Binary signal Volume
    • Count Signal Volume
    • Mutex Amount
    • Recursive Mutex amount
The binary semaphore, count semaphore, mutex and recursive mutex are all implemented by using queue, so it is necessary to master the operation mechanism of the queue.
The queue is the primary communication between the FreeRTOS tasks. You can transfer information between tasks and tasks, interrupts, and tasks. Messages sent to the queue are implemented through a copy, which means that the data stored by the queue is the original data, not the reference to the original data. First look at the data structure of the queue:
typedef struct queuedefinition{int8_t *pchead;             /* points to the starting position of the queue store, the first queue item */int8_t *pctail;          /* points to the next byte after the end of the queue store */int8_t *pcwriteto;     /* refers to the next idle position in the down queue Store */union/* Use a union to ensure that two mutually exclusive struct members do not appear at the same time/{int8_t *pcreadfrom; /* When the structure is used for queues, this field points to the last one in the team project. */ubasetype_t uxrecursivecallcount;/* When the struct is used as a mutex, the number of times that the recursive mutex is "fetched" is used as a counter.    */} U;      list_t Xtaskswaitingtosend;   /* The list of tasks blocked by waiting for the queue, stored in priority order */list_t xtaskswaitingtoreceive;            /* The list of tasks blocked by waiting for queue items, in order of priority store */volatile ubasetype_t uxmessageswaiting;/*< Current queue number of queue items */ubasetype_t uxlength;          /* Number of queue items */ubasetype_t uxitemsize;   /* Size of each queue item */volatile basetype_t xrxlock;   /* When the queue is locked, the number of list items received from the queue is stored, if the queue is not locked, set to queueunlocked */volatile basetype_t xtxlock; /* After the queue is locked, the number of list items sent to the queue is stored, if the queue is not locked, set to queueunlocked */#if (configuse_queue_sets = = 1) struct queuedefinition *px    Queuesetcontainer; #endif #if (confIguse_trace_facility = = 1) ubasetype_t uxqueuenumber;    uint8_t Ucqueuetype;    #endif #if (configsupport_static_allocation = = 1) uint8_t ucstaticallocationflags; #endif} xqueue;typedef xqueue queue_t;
All of the following API functions are expanded around this data structure, so every member of the data structure needs to know. If you are reading this article for the first time, even if there is a comment, maybe you do not understand some members of the structure, do not worry, it is normal. Following the introduction of API functions, will use these members, combined with specific instances, will be very understandable, what you need to do is to repeatedly turn over here to see.
1. Queue creation FunctionIn the article "FreeRTOS series 18th---the FreeRTOS queue API function", we introduced the Create Queue API function Xqueuecreate (), but this is a macro, just a definition of an image function. The function that is actually executed is xqueuegenericcreate (), which we call the function to create for the universal queue. Let's analyze the Xqueuegenericcreate () function, the function prototype is:
queuehandle_t xqueuegenericcreate        (                 const ubasetype_t uxqueuelength,                 const ubasetype_t uxitemsize,                 uint8_t *pucqueuestorage,                 staticqueue_t *pxstaticqueue,                 const uint8_t Ucqueuetype         )
    • Uxqueuelength: Number of queue items
    • Uxitemsize: The size of each queue item
    • Pucqueuestorage: used when assigning queues statically, point to define queue storage, pass NULL to this parameter if using dynamic allocation queue space (default).
    • Pxstaticqueue: used when assigning queues statically, pointing to the queue control structure, passing NULL to this parameter if using dynamic allocation queue space (default).
    • Ucqueuetype: Type. The possible values are:
      • Queuequeue_type_base: Indicates a queue
      • Queuequeue_type_set: Represents a Queue collection
      • Queuequeue_type_mutex: Represents the mutex amount
      • Queuequeue_type_counting_semaphore: Indicates the count signal volume
      • Queuequeue_type_binary_semaphore: Represents the binary semaphore
      • Queuequeue_type_recursive_mutex: Represents a recursive mutex
However, when we look at the source code, we will see that in the Xqueuegenericcreate () function, the parameter ucqueuetype is only used to visualize the tracking tune trial.
The source code for the Xqueuegenericcreate () function is as follows:
queuehandle_t xqueuegenericcreate (const ubasetype_t uxqueuelength, const ubasetype_t Uxitemsi Ze, uint8_t *pucqueuestorage, staticqueue_t *pxstaticqueue, const uint8_t ucqueuety    PE) {queue_t *pxnewqueue; /* If you enable visual trace debugging, this is used to eliminate compiler warnings.    */(void) Ucqueuetype; /* Allocates queue structure body and queue item storage space. Can be statically or dynamically allocated, depending on the parameter value, freertos default to take dynamic assignment */pxnewqueue = Prvallocatequeuememory (Uxqueuelength,    Uxitemsize, &pucqueuestorage, Pxstaticqueue); if (pxnewqueue! = NULL) {if (uxitemsize = = (ubasetype_t) 0) {/* does not allocate memory for queue item storage, but the Pchead pointer does not        can be set to NULL, because the pchead is set to NULL when the queue is used as a mutex. Here just point the pchead to a known area */Pxnewqueue->pchead = (int8_t *) Pxnewqueue;        } else {/* points to the queue item storage area */Pxnewqueue->pchead = (int8_t *) pucqueuestorage;        }/* Initializes the queue struct member */pxnewqueue->uxlength = uxqueuelength;        Pxnewqueue->uxitemsize = uxitemsize; (void ) Xqueuegenericreset (Pxnewqueue, pdtrue);        #if (configuse_trace_facility = = 1) {pxnewqueue->ucqueuetype = Ucqueuetype;    } #endif/* configuse_trace_facility */tracequeue_create (pxnewqueue); } return (queuehandle_t) Pxnewqueue;}
We tell the queue creation process in the default dynamic allocation queue storage space. The function prvallocatequeuememory is first called to allocate the queue structure and queue item storage space, and the structure and queue items are contiguous on the storage space, as shown in 1-1.
Figure 1-1: Memory allocated for a queue if the queue memory request succeeds, the queue struct member is then initialized, first the Pchead member, then the Uxlength and Uxitemsize members, and the last call to the function Xqueuegenericreset () Initializes the remaining struct members.
Suppose we request 3 queue items, each of which consumes 4 bytes of storage (that is, uxlength=3, uxitemsize=4), then the initialized queue memory 1-2 is shown. (this figure depicts the role of most members of the queue structure).
Figure 1-2: Memory of the queue item after initialization2. Queuequeue items are also called delivery (Send), which are divided into queued operations with interrupt protection and queued operations without interrupt protection. In each case, it is divided into two operations from the queue tail and the queue header, and a special case is queued at the end of the queue, and the overlay is queued, that is, the queue will automatically overwrite the oldest queue item when it is full. As shown in table 2-1.
Table 2-1: Queued API Interface List
2.1 xqueuegenericsend ()This function is used for queued operations and must never be used in an interrupt service program. Depending on the parameters, you can queue from the end of the queues, queue first, and overlay. The overlay is used for only one queue item, and when the queue is full, the previous queue item is overwritten. The function prototypes are:
basetype_t xqueuegenericsend (queuehandle_t xqueue, const void * Const PVITEMTOQUEUE, ticktype_t xtickstowait, const BaseT ype_t xcopyposition)
    • Xqueue: Queue handle
    • Pvitemtoqueue: pointer, pointing to the item to be queued
    • Xtickstowait: If the queue is full, the maximum time to wait for the queue to be idle, and if the queue is full and xtickstowait is set to 0, the function returns immediately. The time unit is the system beat clock cycle, and the macro Porttick_period_ms can be used to assist in calculating the true delay value. If Include_vtasksuspend is set to 1, and specifying a delay of Portmax_delay will cause the task to block indefinitely (no timeouts).
    • Xcopyposition: Position, you can choose to queue from the end of the queues, the queue first and the cover-up.
This function relaxes the coding standard for maximum efficiency: There are multiple return points. Therefore, if the purely textual way to explain, I find it difficult to achieve good results, so I first give the collation of the source code (to remove debugging and the queue collection of related codes), and then draw a flowchart, the key points of the function to focus on the description.
The source code after finishing:
basetype_t xqueuegenericsend (queuehandle_t xqueue, const void * Const PVITEMTOQUEUE, ticktype_t xtickstowait, const BaseT ype_t xcopyposition) {basetype_t Xentrytimeset = Pdfalse, xyieldrequired; timeout_t xtimeout;    queue_t * Const PXQUEUE = (queue_t *) Xqueue;    for (;;)        {taskenter_critical (); {/* queue is still idle? The running task must have a higher priority than the task waiting to access the queue. If you are using an overlay, you do not need to pay attention to whether the queue is full */if (pxqueue->uxmessageswaiting &lt ; Pxqueue->uxlength) | |            (xcopyposition = = Queueoverwrite)) {/* Complete data copy work, divided into queues from the end of the queue, from the queue to the first team and the covered type * * xyieldrequired = Prvcopydatatoqueue (Pxqueue, Pvitemtoq                                Ueue, xcopyposition); /* If there is a task waiting for the queue data to arrive, unblock the task */if (Listlist_is_empty (& (pxqueue->xtaskswaitingtoreceive)) = = Pdfa LSE) {/* There are tasks that are blocked by waiting to be out of the queue, remove the task from the queued wait receive list, and then add to the Ready list */if (Xtaskremovefro Meventlist (& (pxqueue->xtaskswaitingtoreceive))! = PdfaLSE) {/* The unblocked task has a higher priority, the current task has to yield the CPU, thus triggering a context switch. Because it is still in the critical section, the context switch is not performed until the critical section is exited.                    */queueyield_if_using_preemption ();                     }} else if (xyieldrequired! = pdfalse) {/* This branch handles special cases */                Queueyield_if_using_preemption ();                } taskexit_critical ();            return pdpass; } else {if (xtickstowait = = (ticktype_t) 0) {/                    * If the queue is full and no timeout is set, exit */taskexit_critical () directly;                /* Return queue full error code */return errqueue_full;                    The else if (Xentrytimeset = = Pdfalse) {/* queue is full and the blocking time is specified, so you need to configure the time-out struct object */                    Vtasksettimeoutstate (&xtimeout);                Xentrytimeset = Pdtrue; }            }        } taskexit_critical (); /* Exits the critical section, where interrupts and other tasks can be queued (posted) or outbound (read) operations to this queue. Because the queue is full, the task cannot be queued, the following code will block the current task on this queue, we need to suspend the scheduler during this code execution, to prevent other tasks from operating the Queue event list The suspend scheduler can prohibit other tasks from operating this queue, but it does not prevent the interrupt service program from operating this queue, so it also needs to lock the queue, prevent the interrupt program from reading the queue, cause the blocking to be unblocked in the outbound operation other tasks, and perform context switching (because the context switch is not allowed after the scheduler hangs)        */Vtasksuspendall ();        Prvlockqueue (Pxqueue); /* See if the task's time-out expires */if (Xtaskcheckfortimeout (&xtimeout, &xtickstowait) = = Pdfalse) {i F (prvisqueuefull (pxqueue)! = Pdfalse) {/* time-out expires and the queue is still full */vtaskplaceonevent                List (& (Pxqueue->xtaskswaitingtosend), xtickstowait);                /* Unlock the queue, and if there is a task to unblock, move the task to the pending ready list (because the current scheduler is suspended so it cannot be moved to the Ready list) */Prvunlockqueue (pxqueue); /* Restore the Scheduler to move the task from the pending ready list to the Ready list */if (xtaskresumeall () = = Pdfalse) {Portyiel                D_within_api (); }} else {/* queue has idle, retry */               Prvunlockqueue (Pxqueue);            (void) xtaskresumeall ();            }} else {/* time-out expires, return queue full error code */Prvunlockqueue (pxqueue);            (void) xtaskresumeall ();            Tracequeue_send_failed (Pxqueue);        return errqueue_full; }    }}
As shown in program flow 2-1, we have a detailed description of the parts of the red font highlighted in the figure.

Figure 2-1: Universal Queued Operation Flowchart When a task queues data, if the queue is not full or is queued with an overlay, the simplest is to call the function Prvcopydatatoqueue () to copy the queued data to the queue. This function handles three types of queues, the first of which is the queue item size of 0 o'clock (that is, the queue structure member Uxitemsize is 0, such as the binary semaphore and the count Semaphore), not the data copy work, but the queue item counter plus 1 (that is, the queue structure member uxmessageswaiting + +); The second case is when the queue is queued, the data is copied to the point where the pointer Pxqueue->pcwriteto, the position where the pointer is updated, the queue item counter is incremented by 1, and the third case is when the queue is first enqueued, the data is copied to the pointer pxqueue-> Where the u.pcreadfrom points, the position where the pointer is updated, and the queue item counter is incremented by 1. If the overlay is queued, the value of the queue item counter is also adjusted.
After the data is queued, check to see if a task is blocked because it waits for the queue to be queued, because this time the data is enqueued, there is at least one queue entry for the queues, and if there is a blocking task, the highest priority task that is blocked can be unblocked.
A task that is blocked by waiting to be out of the queue will xeventlistitem the event list item for the task (that is, the task TCB struct member), and we talked about the event list item in the FreeRTOS Advanced 2---freertos Task creation analysis article. It is a struct member of the task TCB) that is attached to the queue's waiting-out queue table (that is, the queue struct member xtaskswaitingtoreceive). Now, because you want to unblock a task, we need to remove the task's event list item from the queue's waiting queue and move the task to the Ready list. All of this is done by calling function Xtaskremovefromeventlist ().
After that, if the unblocked task has a higher priority than the current task, a PENDSV interrupt is triggered, and then the context switches after exiting the critical section. The task is completed.
The best-case scenario is discussed above, and the process is straightforward, but the situation becomes complicated if the queue is full and does not allow coverage to be queued when the task is queued.
In this case, let's look at a simple branch: A blocking time of 0. Setting a blocking time of 0 means that when the queue is full, the function returns immediately, returning an error code that indicates that the queue is full.
If the blocking time is not 0, the task will be blocked by waiting for the queue to enter. In the process of setting a task to block, you do not want to have additional tasks and interrupt operations on this queue's list of events (queue struct Member Xtaskswaitingtoreceive list and xtaskswaitingtosend list), Because the list of Action queue events can cause other tasks to be unblocked, this may result in a priority rollover. For example, the priority of task A is lower than this task, but in the process of this task entering the block, task A is unblocked because of other reasons, which is obviously to be strictly forbidden. So FreeRTOS uses the suspend scheduler to simply and rudely prohibit other tasks from operating the queue, because suspending the scheduler means that the task cannot be toggled and it is not allowed to invoke API functions that might cause task switching.
However, suspending the scheduler does not prohibit interrupts, and the interrupt service function can still manipulate the list of queue events, which may cause the task to be unblocked and may be context-switched, which is not allowed. So, the solution is not only to suspend the scheduler, but also to lock the queue!
There are two members in the queue structure associated with the lock on the queue: Xrxlock and Xtxlock. When these two member variables are queueunlocked (macro, defined as-1), the queue is unlocked, and when the two member variable is queuelocked_unmodified (a macro, defined as 0), the queue is locked.
Locking the queue is implemented by calling Macro Prvlockqueue (), and the code is simple, setting the queue struct members Xrxlock and Xtxlock to queuelocked_unmodified.
Let's see how locking the queue works. When the interrupt service program operates the queue and causes the blocked task to unblock, it first determines whether the queue is locked, if it is not locked, the blocked task is unblocked, and the context switch request flag is set as needed, and if the queue is locked, the blocked task is not lifted, instead, Add Xrxlock or Xtxlock plus 1 to indicate the number of teams that are out or queued during the lockout period, and also indicate that a task can be unblocked. This part of the code is in the queued and outbound API functions with interrupt protection, as we'll talk about here, here's the first impression.
There is a lock operation on the queue, there will be an unlock queue operation. The function Prvunlockqueue () is used to unblock a queue lock, insert a task that can be unblocked into the ready list, and the maximum number of tasks to dismiss is specified by Xrxlock and Xtxlock.
After a series of logical judgments, it is found that the task is still going into the blocking state, then call the function Vtaskplaceoneventlist () to implement. This function will reveal the detailed steps that the task is going to block by waiting for a specific event, in fact it is very simple and only two steps: the first step, Inserts a task's Event list item (Task TCB struct member Xeventlistitem) into the queue's waiting-in queue table (queue struct member xtaskswaitingtosend); Removes the task's Status list item (task TCB struct member Xstatelistitem) from the Ready list and then inserts it into the delay list, and the maximum delay time for the task is put into Xstatelistitem. In Xitemvalue, this value is checked every time the system Beats timer interrupts the service function to detect if the task timed out.
When the task is successfully blocked waiting for the queue operation, the current task is no longer necessary to occupy the CPU, so the next release of the queues Lock, Recovery Scheduler, task switching, the next highest priority of the ready task will be run.
2.2 Xqueuegenericsendfromisr ()This function is used to queue and interrupt the service program. Depending on the parameters, you can queue from the end of the queues, or you can join the queue at the top. The overlay is used for only one queue item, and when the queue is full, the previous queue item is overwritten. The function prototypes are:
basetype_t Xqueuegenericsendfromisr (queuehandle_t xqueue, const void * Const PVITEMTOQUEUE, basetype_t * Const PXHIGHERPR Ioritytaskwoken, const basetype_t xcopyposition)
    • Xqueue: Queue handle.
    • Pvitemtoqueue: Pointer to the item you want to queue.
    • Pxhigherprioritytaskwoken: If the queue causes a task to be unlocked and the unlocked task takes precedence over the currently running task, the function sets *pxhigherprioritytaskwoken to Pdtrue. If XQUEUESENDFROMISR () sets this value to Pdtrue, a context switch is required before the interrupt exits. From FreeRTOS V7.3.0, Pxhigherprioritytaskwoken is called an optional parameter and can be set to null.
    • Xcopyposition: Position, you can choose to queue from the end of the queues, the queue first and the cover-up.
This function is similar to Xqueuegenericsend (), but does not block when the queue is full and returns an error code that indicates the queue is full (equivalent to blocking time of 0). So, with the foundation of the Analysis Xqueuegenericsend (), this function we'll be able to read soon. The source code is simplified as follows:
basetype_t Xqueuegenericsendfromisr (queuehandle_t xqueue, const void * Const PVITEMTOQUEUE, basetype_t * Const PXHIGHERPR Ioritytaskwoken, const basetype_t xcopyposition) {basetype_t xreturn; ubasetype_t Uxsavedinterruptstatus;    queue_t * Const PXQUEUE = (queue_t *) Xqueue;    Uxsavedinterruptstatus = Portset_interrupt_mask_from_isr (); {if (pxqueue->uxmessageswaiting < pxqueue->uxlength) | |        (xcopyposition = = Queueoverwrite))            {TRACEQUEUE_SEND_FROM_ISR (pxqueue);            /* Complete data copy work, divided into queues from the end of the queue, from the queue first queued and covered type * * (void) prvcopydatatoqueue (Pxqueue, Pvitemtoqueue, xcopyposition);                /* Check if the queue is locked and if locked, the queue event list cannot be changed */if (Pxqueue->xtxlock = = queueunlocked) {/* Queue not locked */                    if (Listlist_is_empty (& (pxqueue->xtaskswaitingtoreceive)) = = Pdfalse) {                  if (Xtaskremovefromeventlist (& (pxqueue->xtaskswaitingtoreceive))! = Pdfalse)  {/* unblocked task priority is higher than current task, record context switch request, etc. after returning interrupt service program, you can display a forced context switch */if (PXHIGHERPRI                        Oritytaskwoken = NULL) {*pxhigherprioritytaskwoken = Pdtrue; }}}} else {/* Queue locked, increasing            Lock counter, waiting for the task to unlock the queue, use this counter to know how much data queued, can be lifted up to wait from the queue to read the data blocked by the task */+ (Pxqueue->xtxlock);        } Xreturn = Pdpass;        } else {xreturn = Errqueue_full;    }} PORTCLEAR_INTERRUPT_MASK_FROM_ISR (Uxsavedinterruptstatus); return Xreturn;}
Because there is no blocking, so the code is a lot simpler, the only thing to note is that, when the team is successfully queued, if there is a task that is blocked by waiting for the queue, it is now possible to unblock the task with the highest priority, before performing the unblocking operation, it will determine whether the queues are locked. If it is not locked, the blocked task is unblocked, and the context switch request flag is set as needed, and if the queue is locked, the blocked task will not be unblocked, instead of Xtxlock plus 1, which indicates the number of queues during lock-up of the queue, and also indicates that a task can be unblocked.
3. The TeamThe API functions of the team are relatively small, and are divided into the team with interrupt protection and the operation without interruption protection. You can choose whether or not to delete queue items for each type of team. The out-of-team API functions are shown in table 3-1.
Table 3-1: List of Outbound API interfaces
There are many similarities between the team operation and the queue operation, the team will understand the process thoroughly, so we do not analyze the source code.

FreeRTOS Advanced Chapter 5---freertos queue analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.