← Documents Documentation/core-api/this_cpu_ops.rst GitHub 원문 ↗

Linux 6.18.37 · Core API

this_cpu operations

현재 CPU의 per-CPU data에 segment-relative single instruction으로 접근하는 this_cpu operation, pointer와 offset 의미론, variant와 remote 접근 위험을 설명합니다.

Source pathDocumentation/core-api/this_cpu_ops.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

this_cpu_ops.rst:1-347

`this_cpu_*`는 per-CPU base와 variable offset의 결합을 instruction에 encode하여 address 계산과 RMW를 하나의 CPU-local operation으로 수행합니다. 많은 경우 preemption이나 interrupt를 별도로 끌 필요가 없습니다.

Per-CPU symbol은 실제 address가 아니라 area 시작점에 대한 offset입니다. `this_cpu_ptr()`와 `raw_cpu_ptr()`는 사용 context와 migration 가능성을 구분하며, 반환 pointer의 lifetime을 critical section 밖으로 넘기지 않아야 합니다.

`__this_cpu_*`는 interrupt safety를 보장하지 않습니다. Remote write는 local RMW와 충돌하고 cache line을 퇴출할 수 있으므로 가능한 한 IPI로 owner CPU가 직접 갱신하게 해야 합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

this_cpu operation 개요

1-63

this_cpu operation

저자: Christoph Lameter, 2014년 8월 4일

저자: Pranith Kumar, 2014년 8월 2일

`this_cpu` operation은 현재 실행 중인 processor에 연결된 per-CPU variable 접근을 최적화하는 방법입니다. Segment register 또는 특정 processor의 per-CPU area 시작점을 CPU가 영구 저장하는 전용 register를 사용합니다.

`this_cpu` operation은 processor별 per-CPU base에 per-CPU variable offset을 더하는 작업을 그 variable을 조작하는 instruction 안에 encode합니다.

따라서 offset 계산과 data operation 사이에 atomicity 문제가 없습니다. Address 계산과 data operation 사이에 processor가 바뀌지 않도록 preemption이나 interrupt를 끌 필요가 없습니다.

Read-modify-write operation이 특히 중요합니다. Processor에는 일반적인 synchronization overhead 없이 동작하면서 relaxed atomicity 보장을 제공하는 latency가 더 낮은 전용 instruction이 자주 있습니다.

예를 들어 x86은 `inc`, `dec`, `cmpxchg` 같은 RMW(Read Modify Write) instruction을 lock prefix와 그 latency penalty 없이 실행할 수 있습니다.

Lock prefix 없는 variable 접근은 synchronize되지 않지만 현재 processor 전용 per-CPU data를 다루므로 synchronization이 필요하지 않습니다. 현재 processor만 해당 variable에 접근해야 하므로 다른 processor와의 concurrency 문제가 없습니다.

Remote processor가 per-CPU area에 접근하는 일은 예외적인 상황이며, remote write operation은 `this_cpu_*`를 통한 local RMW operation의 성능이나 correctness에 영향을 줄 수 있습니다.

`this_cpu` operation은 주로 counter operation 최적화에 사용되어 왔습니다.

암묵적인 preemption protection을 포함한 다음 `this_cpu()` operation이 정의되어 있습니다. Preemption과 interrupt를 걱정하지 않고 사용할 수 있습니다.

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)

this_cpu operation 내부 동작

64-126

this_cpu operation 내부 동작

x86에서는 `fs:` 또는 `gs:` segment register가 per-CPU area의 base를 담습니다. Segment override를 사용하면 per-CPU relative address를 해당 processor의 올바른 per-CPU area로 옮길 수 있습니다. 즉 per-CPU base relocation이 segment register prefix를 통해 instruction에 encode됩니다.

예:

DEFINE_PER_CPU(int, x);
int z;

z = this_cpu_read(x);

이 code는 다음 single instruction이 됩니다.

mov ax, gs:[x]

일반 per-CPU operation처럼 address를 계산한 뒤 그 address에서 fetch하는 sequence가 필요하지 않습니다. `this_cpu_ops` 전에는 계산 도중 kernel이 thread를 다른 processor로 옮기지 못하게 이 sequence에 preempt disable과 enable도 필요했습니다.

다음 `this_cpu` operation을 보십시오.

this_cpu_inc(x)

위 operation은 lock prefix가 없는 다음 single instruction이 됩니다.

inc gs:[x]

Segment register가 없다면 대신 다음 operation이 필요합니다.

int *y;
int cpu;

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

이 operation은 특정 processor에 예약된 per-CPU data에만 사용할 수 있습니다. 주변 code에서 preemption을 끄지 않으면 `this_cpu_inc()`는 per-CPU counter 중 하나가 올바르게 증가한다는 사실만 보장합니다.

OS가 `this_cpu` instruction 실행 직전이나 직후 process를 옮기지 않는다는 보장은 없습니다. 일반적으로 processor별 개별 counter 값은 의미가 없고 모든 per-CPU counter의 합만 중요합니다.

Per-CPU variable은 성능을 위해 사용합니다. 여러 processor가 같은 code path를 동시에 지나도 각자 고유한 per-CPU variable을 가지므로 concurrent cache-line update와 cache-line bouncing을 피할 수 있습니다.

이 최적화의 대가는 counter 값이 필요할 때 모든 per-CPU counter를 더해야 한다는 것입니다.

특수 operation

127-157

특수 operation

y = this_cpu_ptr(&x)

`this_cpu_ptr(&x)`는 per-CPU variable의 offset인 `&x`를 받아 현재 실행 중인 processor에 속한 per-CPU variable address를 반환합니다. 일반적인 `get_cpu()`와 `put_cpu()` sequence의 여러 단계를 피합니다.

Processor number는 얻지 않습니다. 대신 local per-CPU area의 offset을 per-CPU offset에 바로 더합니다.

이 operation은 preemption이 비활성화된 곳처럼 `smp_processor_id()`를 사용할 수 있는 code segment에서만 쓸 수 있습니다. 반환 pointer는 critical section에서 local per-CPU data에 접근하는 데 사용합니다.

Preemption을 다시 켜면 pointer가 현재 processor의 per-CPU data를 더 이상 가리키지 않을 수 있으므로 보통 쓸모가 없어집니다.

Preemptible code에서 per-CPU pointer를 얻는 것이 타당한 특수 사례는 `raw_cpu_ptr()`로 처리합니다. 하지만 이 경우 서로 다른 두 CPU가 제3 CPU의 것일 수도 있는 같은 per-CPU variable에 접근하는 상황을 처리해야 합니다.

이 용도는 대개 성능 최적화입니다. 예를 들어 SRCU는 counter pair를 per-CPU variable pair로 구현하고, `rcu_read_lock_nmisafe()`는 `raw_cpu_ptr()`로 어떤 CPU의 counter pointer를 얻은 뒤 `atomic_inc_long()`을 사용하여 `raw_cpu_ptr()`와 `atomic_inc_long()` 사이의 migration을 처리합니다.

Per-CPU variable과 offset

158-186

Per-CPU variable과 offset

Per-CPU variable은 per-CPU area 시작점에 대한 offset을 가집니다. Code에서 address처럼 보여도 address가 아니며 offset을 직접 dereference할 수 없습니다. Valid address를 만들려면 processor의 per-CPU area base pointer에 offset을 더해야 합니다.

따라서 per-CPU operation context 밖에서 `x`나 `&x`를 사용하는 것은 invalid이며 일반적으로 `NULL` pointer dereference처럼 처리됩니다.

DEFINE_PER_CPU(int, x);

Per-CPU operation context에서 위 선언은 `x`가 per-CPU variable이라는 뜻입니다. 대부분의 `this_cpu` operation은 CPU variable을 받습니다.

int __percpu *p = &x;

`&x`, 따라서 `p`는 per-CPU variable의 offset입니다. `this_cpu_ptr()`가 per-CPU variable offset을 받기 때문에 표현이 다소 낯설게 보일 수 있습니다.

Per-CPU structure field operation

187-226

Per-CPU structure field operation

다음 per-CPU structure가 있다고 가정합니다.

struct s {
        int n,m;
};

DEFINE_PER_CPU(struct s, p);

이 field에 대한 operation은 간단합니다.

this_cpu_inc(p.m)

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

`struct s`에 대한 offset이 있다면 다음과 같습니다.

struct s __percpu *ps = &p;

this_cpu_dec(ps->m);

z = this_cpu_inc_return(ps->n);

이후 field 조작에 `this_cpu` operation을 사용하지 않는다면 pointer 계산에 `this_cpu_ptr()`가 필요할 수 있습니다.

struct s *pp;

pp = this_cpu_ptr(&p);

pp->m--;

z = pp->n++;

__this_cpu variant

227-267

this_cpu operation variant

`this_cpu` operation은 interrupt-safe입니다. 일부 architecture는 이 per-CPU local operation을 지원하지 않습니다. 그러면 interrupt를 끄고 atomicity가 보장되는 operation을 수행한 뒤 interrupt를 다시 켜는 code로 대체해야 하며 비용이 큽니다.

Scheduler가 현재 실행 중인 processor를 바꿀 수 없는 다른 이유가 있다면 interrupt를 끌 필요가 없습니다. 이 용도를 위해 다음 `__this_cpu` operation을 제공합니다.

이 operation은 concurrent interrupt나 preemption에 대해 아무 보장도 하지 않습니다. Per-CPU variable을 interrupt context에서 사용하지 않고 scheduler가 preempt할 수 없다면 안전합니다.

Operation 진행 중 interrupt가 발생하고 interrupt도 variable을 수정한다면 RMW action의 안전성을 보장할 수 없습니다.

__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)

이 variant는 x를 증가시키며, address relocation과 Read-Modify-Write를 같은 instruction으로 수행해 atomicity를 달성할 수 없는 platform에서도 interrupt를 비활성화하는 code로 fallback하지 않습니다.

this_cpu_ptr pointer 표현 비교

268-280

`&this_cpu_ptr(pp)->n`과 `this_cpu_ptr(&pp->n)` 비교

첫 번째 표현은 offset을 받아 address를 만든 뒤 `n` field offset을 더합니다. Compiler가 add instruction 두 개를 생성할 수 있습니다.

두 번째 표현은 먼저 두 offset을 더한 뒤 relocation을 수행합니다. 두 번째 형태가 더 깔끔하고 괄호 처리도 쉬우며 `this_cpu_read()`와 관련 operation의 사용 방식에도 일관됩니다.

Per-CPU data의 remote 접근

281-347

Per-CPU data의 remote 접근

Per-CPU data structure는 CPU 하나가 독점적으로 사용하도록 설계되었습니다. 의도대로 사용하면 다른 CPU가 이 data structure에 접근하지 않으므로 `this_cpu_ops()`는 atomic하다고 보장할 수 있습니다.

특수한 경우 per-CPU data structure에 remote 접근해야 할 수 있습니다. Counter를 요약할 때 자주 하는 remote read는 보통 안전합니다. 하지만 remote write는 `this_cpu` operation에 lock 의미론이 없으므로 문제가 될 수 있고 local `this_cpu` RMW operation을 방해할 수 있습니다.

꼭 필요한 경우가 아니라면 per-CPU data structure의 remote write를 강하게 피해야 합니다. Remote CPU를 IPI로 깨워 그 CPU가 자신의 per-CPU area를 갱신하도록 하는 방법을 검토하십시오.

Per-CPU data structure에 remote 접근할 때는 보통 `per_cpu_ptr()` function을 사용합니다.

DEFINE_PER_CPU(struct data, datap);

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

이 표현은 per-CPU area에 remote 접근할 준비를 한다는 사실을 명시적으로 보여줍니다.

`datap` offset을 address로 바꾸려면 다음 표현도 사용할 수 있습니다.

struct data *p = this_cpu_ptr(&datap);

하지만 `this_cpu_ptr()`로 계산한 pointer를 다른 CPU에 전달하는 일은 일반적이지 않으며 피해야 합니다.

Remote access는 보통 다른 CPU의 per-CPU data 상태를 읽는 용도입니다. Write access는 `this_cpu` operation의 relaxed synchronization 요구 때문에 고유한 문제를 일으킬 수 있습니다.

두 per-CPU variable이 cache line 하나를 공유하지만 relaxed synchronization은 그 cache line을 갱신하는 process 하나에만 적용되는 다음 시나리오가 write 문제를 보여줍니다.

다음 예제를 보십시오.

struct test {
        atomic_t a;
        int b;
};

DEFINE_PER_CPU(struct test, onecacheline);

한 processor가 field `a`를 remote로 갱신하고 local processor가 `this_cpu` operation으로 field `b`를 갱신할 때 문제가 생길 수 있습니다. 같은 cache line 안의 data에 이런 동시 접근을 피하도록 주의해야 하며 비싼 synchronization이 필요할 수도 있습니다.

이 시나리오에서는 다른 processor의 per-CPU area를 remote write하는 대신 IPI를 사용하는 방법을 일반적으로 권장합니다.

Remote write가 드문 경우에도 그 write는 해당 cache line을 가장 자주 접근할 processor의 cache에서 퇴출합니다. Processor가 깨어났을 때 per-CPU area의 local cache line이 없으면 성능과 wakeup time에 영향을 받습니다.