1=================== 2this_cpu operations 3=================== 4 5:Author: Christoph Lameter, August 4th, 2014 6:Author: Pranith Kumar, Aug 2nd, 2014 7 8this_cpu operations are a way of optimizing access to per cpu 9variables associated with the *currently* executing processor. This is 10done through the use of segment registers (or a dedicated register where 11the cpu permanently stored the beginning of the per cpu area for a 12specific processor). 13 14this_cpu operations add a per cpu variable offset to the processor 15specific per cpu base and encode that operation in the instruction 16operating on the per cpu variable. 17 18This means that there are no atomicity issues between the calculation of 19the offset and the operation on the data. Therefore it is not 20necessary to disable preemption or interrupts to ensure that the 21processor is not changed between the calculation of the address and 22the operation on the data. 23 24Read-modify-write operations are of particular interest. Frequently 25processors have special lower latency instructions that can operate 26without the typical synchronization overhead, but still provide some 27sort of relaxed atomicity guarantees. The x86, for example, can execute 28RMW (Read Modify Write) instructions like inc/dec/cmpxchg without the 29lock prefix and the associated latency penalty. 30 31Access to the variable without the lock prefix is not synchronized but 32synchronization is not necessary since we are dealing with per cpu 33data specific to the currently executing processor. Only the current 34processor should be accessing that variable and therefore there are no 35concurrency issues with other processors in the system. 36 37Please note that accesses by remote processors to a per cpu area are 38exceptional situations and may impact performance and/or correctness 39(remote write operations) of local RMW operations via this_cpu_*. 40 41The main use of the this_cpu operations has been to optimize counter 42operations. 43 44The following this_cpu() operations with implied preemption protection 45are defined. These operations can be used without worrying about 46preemption and interrupts:: 47 48 this_cpu_read(pcp) 49 this_cpu_write(pcp, val) 50 this_cpu_add(pcp, val) 51 this_cpu_and(pcp, val) 52 this_cpu_or(pcp, val) 53 this_cpu_add_return(pcp, val) 54 this_cpu_xchg(pcp, nval) 55 this_cpu_cmpxchg(pcp, oval, nval) 56 this_cpu_sub(pcp, val) 57 this_cpu_inc(pcp) 58 this_cpu_dec(pcp) 59 this_cpu_sub_return(pcp, val) 60 this_cpu_inc_return(pcp) 61 this_cpu_dec_return(pcp) 62 63 64Inner working of this_cpu operations 65------------------------------------ 66 67On x86 the fs: or the gs: segment registers contain the base of the 68per cpu area. It is then possible to simply use the segment override 69to relocate a per cpu relative address to the proper per cpu area for 70the processor. So the relocation to the per cpu base is encoded in the 71instruction via a segment register prefix. 72 73For example:: 74 75 DEFINE_PER_CPU(int, x); 76 int z; 77 78 z = this_cpu_read(x); 79 80results in a single instruction:: 81 82 mov ax, gs:[x] 83 84instead of a sequence of calculation of the address and then a fetch 85from that address which occurs with the per cpu operations. Before 86this_cpu_ops such sequence also required preempt disable/enable to 87prevent the kernel from moving the thread to a different processor 88while the calculation is performed. 89 90Consider the following this_cpu operation:: 91 92 this_cpu_inc(x) 93 94The above results in the following single instruction (no lock prefix!):: 95 96 inc gs:[x] 97 98instead of the following operations required if there is no segment 99register:: 100 101 int *y; 102 int cpu; 103 104 cpu = get_cpu(); 105 y = per_cpu_ptr(&x, cpu); 106 (*y)++; 107 put_cpu(); 108 109Note that these operations can only be used on per cpu data that is 110reserved for a specific processor. Without disabling preemption in the 111surrounding code this_cpu_inc() will only guarantee that one of the 112per cpu counters is correctly incremented. However, there is no 113guarantee that the OS will not move the process directly before or 114after the this_cpu instruction is executed. In general this means that 115the value of the individual counters for each processor are 116meaningless. The sum of all the per cpu counters is the only value 117that is of interest. 118 119Per cpu variables are used for performance reasons. Bouncing cache 120lines can be avoided if multiple processors concurrently go through 121the same code paths. Since each processor has its own per cpu 122variables no concurrent cache line updates take place. The price that 123has to be paid for this optimization is the need to add up the per cpu 124counters when the value of a counter is needed. 125 126 127Special operations 128------------------ 129 130:: 131 132 y = this_cpu_ptr(&x) 133 134Takes the offset of a per cpu variable (&x !) and returns the address 135of the per cpu variable that belongs to the currently executing 136processor. this_cpu_ptr avoids multiple steps that the common 137get_cpu/put_cpu sequence requires. No processor number is 138available. Instead, the offset of the local per cpu area is simply 139added to the per cpu offset. 140 141Note that this operation can only be used in code segments where 142smp_processor_id() may be used, for example, where preemption has been 143disabled. The pointer is then used to access local per cpu data in a 144critical section. When preemption is re-enabled this pointer is usually 145no longer useful since it may no longer point to per cpu data of the 146current processor. 147 148The special cases where it makes sense to obtain a per-CPU pointer in 149preemptible code are addressed by raw_cpu_ptr(), but such use cases need 150to handle cases where two different CPUs are accessing the same per cpu 151variable, which might well be that of a third CPU. These use cases are 152typically performance optimizations. For example, SRCU implements a pair 153of counters as a pair of per-CPU variables, and rcu_read_lock_nmisafe() 154uses raw_cpu_ptr() to get a pointer to some CPU's counter, and uses 155atomic_inc_long() to handle migration between the raw_cpu_ptr() and 156the atomic_inc_long(). 157 158Per cpu variables and offsets 159----------------------------- 160 161Per cpu variables have *offsets* to the beginning of the per cpu 162area. They do not have addresses although they look like that in the 163code. Offsets cannot be directly dereferenced. The offset must be 164added to a base pointer of a per cpu area of a processor in order to 165form a valid address. 166 167Therefore the use of x or &x outside of the context of per cpu 168operations is invalid and will generally be treated like a NULL 169pointer dereference. 170 171:: 172 173 DEFINE_PER_CPU(int, x); 174 175In the context of per cpu operations the above implies that x is a per 176cpu variable. Most this_cpu operations take a cpu variable. 177 178:: 179 180 int __percpu *p = &x; 181 182&x and hence p is the *offset* of a per cpu variable. this_cpu_ptr() 183takes the offset of a per cpu variable which makes this look a bit 184strange. 185 186 187Operations on a field of a per cpu structure 188-------------------------------------------- 189 190Let's say we have a percpu structure:: 191 192 struct s { 193 int n,m; 194 }; 195 196 DEFINE_PER_CPU(struct s, p); 197 198 199Operations on these fields are straightforward:: 200 201 this_cpu_inc(p.m) 202 203 z = this_cpu_cmpxchg(p.m, 0, 1); 204 205 206If we have an offset to struct s:: 207 208 struct s __percpu *ps = &p; 209 210 this_cpu_dec(ps->m); 211 212 z = this_cpu_inc_return(ps->n); 213 214 215The calculation of the pointer may require the use of this_cpu_ptr() 216if we do not make use of this_cpu ops later to manipulate fields:: 217 218 struct s *pp; 219 220 pp = this_cpu_ptr(&p); 221 222 pp->m--; 223 224 z = pp->n++; 225 226 227Variants of this_cpu ops 228------------------------ 229 230this_cpu ops are interrupt safe. Some architectures do not support 231these per cpu local operations. In that case the operation must be 232replaced by code that disables interrupts, then does the operations 233that are guaranteed to be atomic and then re-enable interrupts. Doing 234so is expensive. If there are other reasons why the scheduler cannot 235change the processor we are executing on then there is no reason to 236disable interrupts. For that purpose the following __this_cpu operations 237are provided. 238 239These operations have no guarantee against concurrent interrupts or 240preemption. If a per cpu variable is not used in an interrupt context 241and the scheduler cannot preempt, then they are safe. If any interrupts 242still occur while an operation is in progress and if the interrupt too 243modifies the variable, then RMW actions can not be guaranteed to be 244safe:: 245 246 __this_cpu_read(pcp) 247 __this_cpu_write(pcp, val) 248 __this_cpu_add(pcp, val) 249 __this_cpu_and(pcp, val) 250 __this_cpu_or(pcp, val) 251 __this_cpu_add_return(pcp, val) 252 __this_cpu_xchg(pcp, nval) 253 __this_cpu_cmpxchg(pcp, oval, nval) 254 __this_cpu_sub(pcp, val) 255 __this_cpu_inc(pcp) 256 __this_cpu_dec(pcp) 257 __this_cpu_sub_return(pcp, val) 258 __this_cpu_inc_return(pcp) 259 __this_cpu_dec_return(pcp) 260 261 262Will increment x and will not fall-back to code that disables 263interrupts on platforms that cannot accomplish atomicity through 264address relocation and a Read-Modify-Write operation in the same 265instruction. 266 267 268&this_cpu_ptr(pp)->n vs this_cpu_ptr(&pp->n) 269-------------------------------------------- 270 271The first operation takes the offset and forms an address and then 272adds the offset of the n field. This may result in two add 273instructions emitted by the compiler. 274 275The second one first adds the two offsets and then does the 276relocation. IMHO the second form looks cleaner and has an easier time 277with (). The second form also is consistent with the way 278this_cpu_read() and friends are used. 279 280 281Remote access to per cpu data 282------------------------------ 283 284Per cpu data structures are designed to be used by one cpu exclusively. 285If you use the variables as intended, this_cpu_ops() are guaranteed to 286be "atomic" as no other CPU has access to these data structures. 287 288There are special cases where you might need to access per cpu data 289structures remotely. It is usually safe to do a remote read access 290and that is frequently done to summarize counters. Remote write access 291something which could be problematic because this_cpu ops do not 292have lock semantics. A remote write may interfere with a this_cpu 293RMW operation. 294 295Remote write accesses to percpu data structures are highly discouraged 296unless absolutely necessary. Please consider using an IPI to wake up 297the remote CPU and perform the update to its per cpu area. 298 299To access per-cpu data structure remotely, typically the per_cpu_ptr() 300function is used:: 301 302 303 DEFINE_PER_CPU(struct data, datap); 304 305 struct data *p = per_cpu_ptr(&datap, cpu); 306 307This makes it explicit that we are getting ready to access a percpu 308area remotely. 309 310You can also do the following to convert the datap offset to an address:: 311 312 struct data *p = this_cpu_ptr(&datap); 313 314but, passing of pointers calculated via this_cpu_ptr to other cpus is 315unusual and should be avoided. 316 317Remote access are typically only for reading the status of another cpus 318per cpu data. Write accesses can cause unique problems due to the 319relaxed synchronization requirements for this_cpu operations. 320 321One example that illustrates some concerns with write operations is 322the following scenario that occurs because two per cpu variables 323share a cache-line but the relaxed synchronization is applied to 324only one process updating the cache-line. 325 326Consider the following example:: 327 328 329 struct test { 330 atomic_t a; 331 int b; 332 }; 333 334 DEFINE_PER_CPU(struct test, onecacheline); 335 336There is some concern about what would happen if the field 'a' is updated 337remotely from one processor and the local processor would use this_cpu ops 338to update field b. Care should be taken that such simultaneous accesses to 339data within the same cache line are avoided. Also costly synchronization 340may be necessary. IPIs are generally recommended in such scenarios instead 341of a remote write to the per cpu area of another processor. 342 343Even in cases where the remote writes are rare, please bear in 344mind that a remote write will evict the cache line from the processor 345that most likely will access it. If the processor wakes up and finds a 346missing local cache line of a per cpu area, its performance and hence 347the wake up times will be affected. 348