Path: blob/master/Documentation/circular-buffers.txt
10820 views
================1CIRCULAR BUFFERS2================34By: David Howells <[email protected]>5Paul E. McKenney <[email protected]>678Linux provides a number of features that can be used to implement circular9buffering. There are two sets of such features:1011(1) Convenience functions for determining information about power-of-2 sized12buffers.1314(2) Memory barriers for when the producer and the consumer of objects in the15buffer don't want to share a lock.1617To use these facilities, as discussed below, there needs to be just one18producer and just one consumer. It is possible to handle multiple producers by19serialising them, and to handle multiple consumers by serialising them.202122Contents:2324(*) What is a circular buffer?2526(*) Measuring power-of-2 buffers.2728(*) Using memory barriers with circular buffers.29- The producer.30- The consumer.313233==========================34WHAT IS A CIRCULAR BUFFER?35==========================3637First of all, what is a circular buffer? A circular buffer is a buffer of38fixed, finite size into which there are two indices:3940(1) A 'head' index - the point at which the producer inserts items into the41buffer.4243(2) A 'tail' index - the point at which the consumer finds the next item in44the buffer.4546Typically when the tail pointer is equal to the head pointer, the buffer is47empty; and the buffer is full when the head pointer is one less than the tail48pointer.4950The head index is incremented when items are added, and the tail index when51items are removed. The tail index should never jump the head index, and both52indices should be wrapped to 0 when they reach the end of the buffer, thus53allowing an infinite amount of data to flow through the buffer.5455Typically, items will all be of the same unit size, but this isn't strictly56required to use the techniques below. The indices can be increased by more57than 1 if multiple items or variable-sized items are to be included in the58buffer, provided that neither index overtakes the other. The implementer must59be careful, however, as a region more than one unit in size may wrap the end of60the buffer and be broken into two segments.616263============================64MEASURING POWER-OF-2 BUFFERS65============================6667Calculation of the occupancy or the remaining capacity of an arbitrarily sized68circular buffer would normally be a slow operation, requiring the use of a69modulus (divide) instruction. However, if the buffer is of a power-of-2 size,70then a much quicker bitwise-AND instruction can be used instead.7172Linux provides a set of macros for handling power-of-2 circular buffers. These73can be made use of by:7475#include <linux/circ_buf.h>7677The macros are:7879(*) Measure the remaining capacity of a buffer:8081CIRC_SPACE(head_index, tail_index, buffer_size);8283This returns the amount of space left in the buffer[1] into which items84can be inserted.858687(*) Measure the maximum consecutive immediate space in a buffer:8889CIRC_SPACE_TO_END(head_index, tail_index, buffer_size);9091This returns the amount of consecutive space left in the buffer[1] into92which items can be immediately inserted without having to wrap back to the93beginning of the buffer.949596(*) Measure the occupancy of a buffer:9798CIRC_CNT(head_index, tail_index, buffer_size);99100This returns the number of items currently occupying a buffer[2].101102103(*) Measure the non-wrapping occupancy of a buffer:104105CIRC_CNT_TO_END(head_index, tail_index, buffer_size);106107This returns the number of consecutive items[2] that can be extracted from108the buffer without having to wrap back to the beginning of the buffer.109110111Each of these macros will nominally return a value between 0 and buffer_size-1,112however:113114[1] CIRC_SPACE*() are intended to be used in the producer. To the producer115they will return a lower bound as the producer controls the head index,116but the consumer may still be depleting the buffer on another CPU and117moving the tail index.118119To the consumer it will show an upper bound as the producer may be busy120depleting the space.121122[2] CIRC_CNT*() are intended to be used in the consumer. To the consumer they123will return a lower bound as the consumer controls the tail index, but the124producer may still be filling the buffer on another CPU and moving the125head index.126127To the producer it will show an upper bound as the consumer may be busy128emptying the buffer.129130[3] To a third party, the order in which the writes to the indices by the131producer and consumer become visible cannot be guaranteed as they are132independent and may be made on different CPUs - so the result in such a133situation will merely be a guess, and may even be negative.134135136===========================================137USING MEMORY BARRIERS WITH CIRCULAR BUFFERS138===========================================139140By using memory barriers in conjunction with circular buffers, you can avoid141the need to:142143(1) use a single lock to govern access to both ends of the buffer, thus144allowing the buffer to be filled and emptied at the same time; and145146(2) use atomic counter operations.147148There are two sides to this: the producer that fills the buffer, and the149consumer that empties it. Only one thing should be filling a buffer at any one150time, and only one thing should be emptying a buffer at any one time, but the151two sides can operate simultaneously.152153154THE PRODUCER155------------156157The producer will look something like this:158159spin_lock(&producer_lock);160161unsigned long head = buffer->head;162unsigned long tail = ACCESS_ONCE(buffer->tail);163164if (CIRC_SPACE(head, tail, buffer->size) >= 1) {165/* insert one item into the buffer */166struct item *item = buffer[head];167168produce_item(item);169170smp_wmb(); /* commit the item before incrementing the head */171172buffer->head = (head + 1) & (buffer->size - 1);173174/* wake_up() will make sure that the head is committed before175* waking anyone up */176wake_up(consumer);177}178179spin_unlock(&producer_lock);180181This will instruct the CPU that the contents of the new item must be written182before the head index makes it available to the consumer and then instructs the183CPU that the revised head index must be written before the consumer is woken.184185Note that wake_up() doesn't have to be the exact mechanism used, but whatever186is used must guarantee a (write) memory barrier between the update of the head187index and the change of state of the consumer, if a change of state occurs.188189190THE CONSUMER191------------192193The consumer will look something like this:194195spin_lock(&consumer_lock);196197unsigned long head = ACCESS_ONCE(buffer->head);198unsigned long tail = buffer->tail;199200if (CIRC_CNT(head, tail, buffer->size) >= 1) {201/* read index before reading contents at that index */202smp_read_barrier_depends();203204/* extract one item from the buffer */205struct item *item = buffer[tail];206207consume_item(item);208209smp_mb(); /* finish reading descriptor before incrementing tail */210211buffer->tail = (tail + 1) & (buffer->size - 1);212}213214spin_unlock(&consumer_lock);215216This will instruct the CPU to make sure the index is up to date before reading217the new item, and then it shall make sure the CPU has finished reading the item218before it writes the new tail pointer, which will erase the item.219220221Note the use of ACCESS_ONCE() in both algorithms to read the opposition index.222This prevents the compiler from discarding and reloading its cached value -223which some compilers will do across smp_read_barrier_depends(). This isn't224strictly needed if you can be sure that the opposition index will _only_ be225used the once.226227228===============229FURTHER READING230===============231232See also Documentation/memory-barriers.txt for a description of Linux's memory233barrier facilities.234235236