this_cpu operations

Author:

Christoph Lameter, August 4th, 2014

Author:

Pranith Kumar, Aug 2nd, 2014

this_cpu operations are a way of optimizing access to per cpuvariables associated with thecurrently executing processor. This isdone through the use of segment registers (or a dedicated register wherethe cpu permanently stored the beginning of the per cpu area for aspecific processor).

this_cpu operations add a per cpu variable offset to the processorspecific per cpu base and encode that operation in the instructionoperating on the per cpu variable.

This means that there are no atomicity issues between the calculation ofthe offset and the operation on the data. Therefore it is notnecessary to disable preemption or interrupts to ensure that theprocessor is not changed between the calculation of the address andthe operation on the data.

Read-modify-write operations are of particular interest. Frequentlyprocessors have special lower latency instructions that can operatewithout the typical synchronization overhead, but still provide somesort of relaxed atomicity guarantees. The x86, for example, can executeRMW (Read Modify Write) instructions like inc/dec/cmpxchg without thelock prefix and the associated latency penalty.

Access to the variable without the lock prefix is not synchronized butsynchronization is not necessary since we are dealing with per cpudata specific to the currently executing processor. Only the currentprocessor should be accessing that variable and therefore there are noconcurrency issues with other processors in the system.

Please note that accesses by remote processors to a per cpu area areexceptional situations and may impact performance and/or correctness(remote write operations) of local RMW operations via this_cpu_*.

The main use of the this_cpu operations has been to optimize counteroperations.

The followingthis_cpu() operations with implied preemption protectionare defined. These operations can be used without worrying aboutpreemption and interrupts:

this_cpu_read(pcp)this_cpu_write(pcp, val)this_cpu_add(pcp, val)this_cpu_and(pcp, val)this_cpu_or(pcp, val)this_cpu_add_return(pcp, val)this_cpu_xchg(pcp, nval)this_cpu_cmpxchg(pcp, oval, nval)this_cpu_sub(pcp, val)this_cpu_inc(pcp)this_cpu_dec(pcp)this_cpu_sub_return(pcp, val)this_cpu_inc_return(pcp)this_cpu_dec_return(pcp)

Inner working of this_cpu operations

On x86 the fs: or the gs: segment registers contain the base of theper cpu area. It is then possible to simply use the segment overrideto relocate a per cpu relative address to the proper per cpu area forthe processor. So the relocation to the per cpu base is encoded in theinstruction via a segment register prefix.

For example:

DEFINE_PER_CPU(int, x);int z;z = this_cpu_read(x);

results in a single instruction:

mov ax, gs:[x]

instead of a sequence of calculation of the address and then a fetchfrom that address which occurs with the per cpu operations. Beforethis_cpu_ops such sequence also required preempt disable/enable toprevent the kernel from moving the thread to a different processorwhile the calculation is performed.

Consider the following this_cpu operation:

this_cpu_inc(x)

The above results in the following single instruction (no lock prefix!):

inc gs:[x]

instead of the following operations required if there is no segmentregister:

int *y;int cpu;cpu = get_cpu();y = per_cpu_ptr(&x, cpu);(*y)++;put_cpu();

Note that these operations can only be used on per cpu data that isreserved for a specific processor. Without disabling preemption in thesurrounding codethis_cpu_inc() will only guarantee that one of theper cpu counters is correctly incremented. However, there is noguarantee that the OS will not move the process directly before orafter the this_cpu instruction is executed. In general this means thatthe value of the individual counters for each processor aremeaningless. The sum of all the per cpu counters is the only valuethat is of interest.

Per cpu variables are used for performance reasons. Bouncing cachelines can be avoided if multiple processors concurrently go throughthe same code paths. Since each processor has its own per cpuvariables no concurrent cache line updates take place. The price thathas to be paid for this optimization is the need to add up the per cpucounters when the value of a counter is needed.

Special operations

y = this_cpu_ptr(&x)

Takes the offset of a per cpu variable (&x !) and returns the addressof the per cpu variable that belongs to the currently executingprocessor. this_cpu_ptr avoids multiple steps that the commonget_cpu/put_cpu sequence requires. No processor number isavailable. Instead, the offset of the local per cpu area is simplyadded to the per cpu offset.

Note that this operation can only be used in code segments wheresmp_processor_id() may be used, for example, where preemption has beendisabled. The pointer is then used to access local per cpu data in acritical section. When preemption is re-enabled this pointer is usuallyno longer useful since it may no longer point to per cpu data of thecurrent processor.

The special cases where it makes sense to obtain a per-CPU pointer inpreemptible code are addressed byraw_cpu_ptr(), but such use cases needto handle cases where two different CPUs are accessing the same per cpuvariable, which might well be that of a third CPU. These use cases aretypically performance optimizations. For example, SRCU implements a pairof counters as a pair of per-CPU variables, andrcu_read_lock_nmisafe()usesraw_cpu_ptr() to get a pointer to some CPU’s counter, and usesatomic_inc_long() to handle migration between theraw_cpu_ptr() andtheatomic_inc_long().

Per cpu variables and offsets

Per cpu variables haveoffsets to the beginning of the per cpuarea. They do not have addresses although they look like that in thecode. Offsets cannot be directly dereferenced. The offset must beadded to a base pointer of a per cpu area of a processor in order toform a valid address.

Therefore the use of x or &x outside of the context of per cpuoperations is invalid and will generally be treated like a NULLpointer dereference.

DEFINE_PER_CPU(int, x);

In the context of per cpu operations the above implies that x is a percpu variable. Most this_cpu operations take a cpu variable.

int __percpu *p = &x;

&x and hence p is theoffset of a per cpu variable.this_cpu_ptr()takes the offset of a per cpu variable which makes this look a bitstrange.

Operations on a field of a per cpu structure

Let’s say we have a percpu structure:

struct s {        int n,m;};DEFINE_PER_CPU(struct s, p);

Operations on these fields are straightforward:

this_cpu_inc(p.m)z = this_cpu_cmpxchg(p.m, 0, 1);

If we have an offset to struct s:

struct s __percpu *ps = &p;this_cpu_dec(ps->m);z = this_cpu_inc_return(ps->n);

The calculation of the pointer may require the use ofthis_cpu_ptr()if we do not make use of this_cpu ops later to manipulate fields:

struct s *pp;pp = this_cpu_ptr(&p);pp->m--;z = pp->n++;

Variants of this_cpu ops

this_cpu ops are interrupt safe. Some architectures do not supportthese per cpu local operations. In that case the operation must bereplaced by code that disables interrupts, then does the operationsthat are guaranteed to be atomic and then re-enable interrupts. Doingso is expensive. If there are other reasons why the scheduler cannotchange the processor we are executing on then there is no reason todisable interrupts. For that purpose the following __this_cpu operationsare provided.

These operations have no guarantee against concurrent interrupts orpreemption. If a per cpu variable is not used in an interrupt contextand the scheduler cannot preempt, then they are safe. If any interruptsstill occur while an operation is in progress and if the interrupt toomodifies the variable, then RMW actions can not be guaranteed to besafe:

__this_cpu_read(pcp)__this_cpu_write(pcp, val)__this_cpu_add(pcp, val)__this_cpu_and(pcp, val)__this_cpu_or(pcp, val)__this_cpu_add_return(pcp, val)__this_cpu_xchg(pcp, nval)__this_cpu_cmpxchg(pcp, oval, nval)__this_cpu_sub(pcp, val)__this_cpu_inc(pcp)__this_cpu_dec(pcp)__this_cpu_sub_return(pcp, val)__this_cpu_inc_return(pcp)__this_cpu_dec_return(pcp)

Will increment x and will not fall-back to code that disablesinterrupts on platforms that cannot accomplish atomicity throughaddress relocation and a Read-Modify-Write operation in the sameinstruction.

&this_cpu_ptr(pp)->n vs this_cpu_ptr(&pp->n)

The first operation takes the offset and forms an address and thenadds the offset of the n field. This may result in two addinstructions emitted by the compiler.

The second one first adds the two offsets and then does therelocation. IMHO the second form looks cleaner and has an easier timewith (). The second form also is consistent with the waythis_cpu_read() and friends are used.

Remote access to per cpu data

Per cpu data structures are designed to be used by one cpu exclusively.If you use the variables as intended,this_cpu_ops() are guaranteed tobe “atomic” as no other CPU has access to these data structures.

There are special cases where you might need to access per cpu datastructures remotely. It is usually safe to do a remote read accessand that is frequently done to summarize counters. Remote write accesssomething which could be problematic because this_cpu ops do nothave lock semantics. A remote write may interfere with a this_cpuRMW operation.

Remote write accesses to percpu data structures are highly discouragedunless absolutely necessary. Please consider using an IPI to wake upthe remote CPU and perform the update to its per cpu area.

To access per-cpu data structure remotely, typically theper_cpu_ptr()function is used:

DEFINE_PER_CPU(struct data, datap);struct data *p = per_cpu_ptr(&datap, cpu);

This makes it explicit that we are getting ready to access a percpuarea remotely.

You can also do the following to convert the datap offset to an address:

struct data *p = this_cpu_ptr(&datap);

but, passing of pointers calculated via this_cpu_ptr to other cpus isunusual and should be avoided.

Remote access are typically only for reading the status of another cpusper cpu data. Write accesses can cause unique problems due to therelaxed synchronization requirements for this_cpu operations.

One example that illustrates some concerns with write operations isthe following scenario that occurs because two per cpu variablesshare a cache-line but the relaxed synchronization is applied toonly one process updating the cache-line.

Consider the following example:

struct test {        atomic_t a;        int b;};DEFINE_PER_CPU(struct test, onecacheline);

There is some concern about what would happen if the field ‘a’ is updatedremotely from one processor and the local processor would use this_cpu opsto update field b. Care should be taken that such simultaneous accesses todata within the same cache line are avoided. Also costly synchronizationmay be necessary. IPIs are generally recommended in such scenarios insteadof a remote write to the per cpu area of another processor.

Even in cases where the remote writes are rare, please bear inmind that a remote write will evict the cache line from the processorthat most likely will access it. If the processor wakes up and finds amissing local cache line of a per cpu area, its performance and hencethe wake up times will be affected.