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

Linux 6.18.37 · Core API

Cache and TLB Flushing Under Linux

Linux VM이 page table과 virtual-to-physical mapping을 바꿀 때 사용하는 TLB, data cache, instruction cache flush API와 architecture별 coherency 책임을 설명합니다.

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

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

1. 요약·해설

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

요약과 해설

cachetlb.rst:1-398

Page table을 바꾼 뒤 오래된 TLB translation이 남지 않도록 address space 전체, 범위, 단일 page 수준의 flush API를 선택합니다. SMP에서는 실제로 그 address space를 실행한 CPU만 골라 flush하는 최적화가 가능합니다.

Cache flush는 translation을 바꾸기 전에, TLB flush는 page table을 바꾼 뒤에 수행합니다. 이 순서는 flush 자체에 유효한 translation이 필요한 cache architecture까지 지원합니다.

Virtually indexed D-cache의 aliasing, user와 kernel mapping의 cache color, page cache와 anonymous page, vmap I/O alias는 서로 다른 coherency interface를 요구합니다. Coherent architecture는 일부를 nop으로 둘 수 있지만 incoherent architecture는 각 계약을 구현해야 합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ==================================
2 Cache and TLB Flushing Under Linux
3 ==================================
4
5 :Author: David S. Miller <[email protected]>
6
7 This document describes the cache/tlb flushing interfaces called
8 by the Linux VM subsystem. It enumerates over each interface,
9 describes its intended purpose, and what side effect is expected
10 after the interface is invoked.
11
12 The side effects described below are stated for a uniprocessor
13 implementation, and what is to happen on that single processor. The
14 SMP cases are a simple extension, in that you just extend the
15 definition such that the side effect for a particular interface occurs
16 on all processors in the system. Don't let this scare you into
17 thinking SMP cache/tlb flushing must be so inefficient, this is in
18 fact an area where many optimizations are possible. For example,
19 if it can be proven that a user address space has never executed
20 on a cpu (see mm_cpumask()), one need not perform a flush
21 for this address space on that cpu.
22
23 First, the TLB flushing interfaces, since they are the simplest. The
24 "TLB" is abstracted under Linux as something the cpu uses to cache
25 virtual-->physical address translations obtained from the software
26 page tables. Meaning that if the software page tables change, it is
27 possible for stale translations to exist in this "TLB" cache.
28 Therefore when software page table changes occur, the kernel will
29 invoke one of the following flush methods _after_ the page table
30 changes occur:
31
32 1) ``void flush_tlb_all(void)``
33
34 The most severe flush of all. After this interface runs,
35 any previous page table modification whatsoever will be
36 visible to the cpu.
37
38 This is usually invoked when the kernel page tables are
39 changed, since such translations are "global" in nature.
40
41 2) ``void flush_tlb_mm(struct mm_struct *mm)``
42
43 This interface flushes an entire user address space from
44 the TLB. After running, this interface must make sure that
45 any previous page table modifications for the address space
46 'mm' will be visible to the cpu. That is, after running,
47 there will be no entries in the TLB for 'mm'.
48
49 This interface is used to handle whole address space
50 page table operations such as what happens during
51 fork, and exec.
52
53 3) ``void flush_tlb_range(struct vm_area_struct *vma,
54 unsigned long start, unsigned long end)``
55
56 Here we are flushing a specific range of (user) virtual
57 address translations from the TLB. After running, this
58 interface must make sure that any previous page table
59 modifications for the address space 'vma->vm_mm' in the range
60 'start' to 'end-1' will be visible to the cpu. That is, after
61 running, there will be no entries in the TLB for 'mm' for
62 virtual addresses in the range 'start' to 'end-1'.
63
64 The "vma" is the backing store being used for the region.
65 Primarily, this is used for munmap() type operations.
66
67 The interface is provided in hopes that the port can find
68 a suitably efficient method for removing multiple page
69 sized translations from the TLB, instead of having the kernel
70 call flush_tlb_page (see below) for each entry which may be
71 modified.
72
73 4) ``void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)``
74
75 This time we need to remove the PAGE_SIZE sized translation
76 from the TLB. The 'vma' is the backing structure used by
77 Linux to keep track of mmap'd regions for a process, the
78 address space is available via vma->vm_mm. Also, one may
79 test (vma->vm_flags & VM_EXEC) to see if this region is
80 executable (and thus could be in the 'instruction TLB' in
81 split-tlb type setups).
82
83 After running, this interface must make sure that any previous
84 page table modification for address space 'vma->vm_mm' for
85 user virtual address 'addr' will be visible to the cpu. That
86 is, after running, there will be no entries in the TLB for
87 'vma->vm_mm' for virtual address 'addr'.
88
89 This is used primarily during fault processing.
90
91 5) ``void update_mmu_cache_range(struct vm_fault *vmf,
92 struct vm_area_struct *vma, unsigned long address, pte_t *ptep,
93 unsigned int nr)``
94
95 At the end of every page fault, this routine is invoked to tell
96 the architecture specific code that translations now exists
97 in the software page tables for address space "vma->vm_mm"
98 at virtual address "address" for "nr" consecutive pages.
99
100 This routine is also invoked in various other places which pass
101 a NULL "vmf".
102
103 A port may use this information in any way it so chooses.
104 For example, it could use this event to pre-load TLB
105 translations for software managed TLB configurations.
106 The sparc64 port currently does this.
107
108 Next, we have the cache flushing interfaces. In general, when Linux
109 is changing an existing virtual-->physical mapping to a new value,
110 the sequence will be in one of the following forms::
111
112 1) flush_cache_mm(mm);
113 change_all_page_tables_of(mm);
114 flush_tlb_mm(mm);
115
116 2) flush_cache_range(vma, start, end);
117 change_range_of_page_tables(mm, start, end);
118 flush_tlb_range(vma, start, end);
119
120 3) flush_cache_page(vma, addr, pfn);
121 set_pte(pte_pointer, new_pte_val);
122 flush_tlb_page(vma, addr);
123
124 The cache level flush will always be first, because this allows
125 us to properly handle systems whose caches are strict and require
126 a virtual-->physical translation to exist for a virtual address
127 when that virtual address is flushed from the cache. The HyperSparc
128 cpu is one such cpu with this attribute.
129
130 The cache flushing routines below need only deal with cache flushing
131 to the extent that it is necessary for a particular cpu. Mostly,
132 these routines must be implemented for cpus which have virtually
133 indexed caches which must be flushed when virtual-->physical
134 translations are changed or removed. So, for example, the physically
135 indexed physically tagged caches of IA32 processors have no need to
136 implement these interfaces since the caches are fully synchronized
137 and have no dependency on translation information.
138
139 Here are the routines, one by one:
140
141 1) ``void flush_cache_mm(struct mm_struct *mm)``
142
143 This interface flushes an entire user address space from
144 the caches. That is, after running, there will be no cache
145 lines associated with 'mm'.
146
147 This interface is used to handle whole address space
148 page table operations such as what happens during exit and exec.
149
150 2) ``void flush_cache_dup_mm(struct mm_struct *mm)``
151
152 This interface flushes an entire user address space from
153 the caches. That is, after running, there will be no cache
154 lines associated with 'mm'.
155
156 This interface is used to handle whole address space
157 page table operations such as what happens during fork.
158
159 This option is separate from flush_cache_mm to allow some
160 optimizations for VIPT caches.
161
162 3) ``void flush_cache_range(struct vm_area_struct *vma,
163 unsigned long start, unsigned long end)``
164
165 Here we are flushing a specific range of (user) virtual
166 addresses from the cache. After running, there will be no
167 entries in the cache for 'vma->vm_mm' for virtual addresses in
168 the range 'start' to 'end-1'.
169
170 The "vma" is the backing store being used for the region.
171 Primarily, this is used for munmap() type operations.
172
173 The interface is provided in hopes that the port can find
174 a suitably efficient method for removing multiple page
175 sized regions from the cache, instead of having the kernel
176 call flush_cache_page (see below) for each entry which may be
177 modified.
178
179 4) ``void flush_cache_page(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn)``
180
181 This time we need to remove a PAGE_SIZE sized range
182 from the cache. The 'vma' is the backing structure used by
183 Linux to keep track of mmap'd regions for a process, the
184 address space is available via vma->vm_mm. Also, one may
185 test (vma->vm_flags & VM_EXEC) to see if this region is
186 executable (and thus could be in the 'instruction cache' in
187 "Harvard" type cache layouts).
188
189 The 'pfn' indicates the physical page frame (shift this value
190 left by PAGE_SHIFT to get the physical address) that 'addr'
191 translates to. It is this mapping which should be removed from
192 the cache.
193
194 After running, there will be no entries in the cache for
195 'vma->vm_mm' for virtual address 'addr' which translates
196 to 'pfn'.
197
198 This is used primarily during fault processing.
199
200 5) ``void flush_cache_kmaps(void)``
201
202 This routine need only be implemented if the platform utilizes
203 highmem. It will be called right before all of the kmaps
204 are invalidated.
205
206 After running, there will be no entries in the cache for
207 the kernel virtual address range PKMAP_ADDR(0) to
208 PKMAP_ADDR(LAST_PKMAP).
209
210 This routing should be implemented in asm/highmem.h
211
212 6) ``void flush_cache_vmap(unsigned long start, unsigned long end)``
213 ``void flush_cache_vunmap(unsigned long start, unsigned long end)``
214
215 Here in these two interfaces we are flushing a specific range
216 of (kernel) virtual addresses from the cache. After running,
217 there will be no entries in the cache for the kernel address
218 space for virtual addresses in the range 'start' to 'end-1'.
219
220 The first of these two routines is invoked after vmap_range()
221 has installed the page table entries. The second is invoked
222 before vunmap_range() deletes the page table entries.
223
224 There exists another whole class of cpu cache issues which currently
225 require a whole different set of interfaces to handle properly.
226 The biggest problem is that of virtual aliasing in the data cache
227 of a processor.
228
229 Is your port susceptible to virtual aliasing in its D-cache?
230 Well, if your D-cache is virtually indexed, is larger in size than
231 PAGE_SIZE, and does not prevent multiple cache lines for the same
232 physical address from existing at once, you have this problem.
233
234 If your D-cache has this problem, first define asm/shmparam.h SHMLBA
235 properly, it should essentially be the size of your virtually
236 addressed D-cache (or if the size is variable, the largest possible
237 size). This setting will force the SYSv IPC layer to only allow user
238 processes to mmap shared memory at address which are a multiple of
239 this value.
240
241 .. note::
242
243 This does not fix shared mmaps, check out the sparc64 port for
244 one way to solve this (in particular SPARC_FLAG_MMAPSHARED).
245
246 Next, you have to solve the D-cache aliasing issue for all
247 other cases. Please keep in mind that fact that, for a given page
248 mapped into some user address space, there is always at least one more
249 mapping, that of the kernel in its linear mapping starting at
250 PAGE_OFFSET. So immediately, once the first user maps a given
251 physical page into its address space, by implication the D-cache
252 aliasing problem has the potential to exist since the kernel already
253 maps this page at its virtual address.
254
255 ``void copy_user_page(void *to, void *from, unsigned long addr, struct page *page)``
256 ``void clear_user_page(void *to, unsigned long addr, struct page *page)``
257
258 These two routines store data in user anonymous or COW
259 pages. It allows a port to efficiently avoid D-cache alias
260 issues between userspace and the kernel.
261
262 For example, a port may temporarily map 'from' and 'to' to
263 kernel virtual addresses during the copy. The virtual address
264 for these two pages is chosen in such a way that the kernel
265 load/store instructions happen to virtual addresses which are
266 of the same "color" as the user mapping of the page. Sparc64
267 for example, uses this technique.
268
269 The 'addr' parameter tells the virtual address where the
270 user will ultimately have this page mapped, and the 'page'
271 parameter gives a pointer to the struct page of the target.
272
273 If D-cache aliasing is not an issue, these two routines may
274 simply call memcpy/memset directly and do nothing more.
275
276 ``void flush_dcache_folio(struct folio *folio)``
277
278 This routines must be called when:
279
280 a) the kernel did write to a page that is in the page cache page
281 and / or in high memory
282 b) the kernel is about to read from a page cache page and user space
283 shared/writable mappings of this page potentially exist. Note
284 that {get,pin}_user_pages{_fast} already call flush_dcache_folio
285 on any page found in the user address space and thus driver
286 code rarely needs to take this into account.
287
288 .. note::
289
290 This routine need only be called for page cache pages
291 which can potentially ever be mapped into the address
292 space of a user process. So for example, VFS layer code
293 handling vfs symlinks in the page cache need not call
294 this interface at all.
295
296 The phrase "kernel writes to a page cache page" means, specifically,
297 that the kernel executes store instructions that dirty data in that
298 page at the kernel virtual mapping of that page. It is important to
299 flush here to handle D-cache aliasing, to make sure these kernel stores
300 are visible to user space mappings of that page.
301
302 The corollary case is just as important, if there are users which have
303 shared+writable mappings of this file, we must make sure that kernel
304 reads of these pages will see the most recent stores done by the user.
305
306 If D-cache aliasing is not an issue, this routine may simply be defined
307 as a nop on that architecture.
308
309 There is a bit set aside in folio->flags (PG_arch_1) as "architecture
310 private". The kernel guarantees that, for pagecache pages, it will
311 clear this bit when such a page first enters the pagecache.
312
313 This allows these interfaces to be implemented much more
314 efficiently. It allows one to "defer" (perhaps indefinitely) the
315 actual flush if there are currently no user processes mapping this
316 page. See sparc64's flush_dcache_folio and update_mmu_cache_range
317 implementations for an example of how to go about doing this.
318
319 The idea is, first at flush_dcache_folio() time, if
320 folio_flush_mapping() returns a mapping, and mapping_mapped() on that
321 mapping returns %false, just mark the architecture private page
322 flag bit. Later, in update_mmu_cache_range(), a check is made
323 of this flag bit, and if set the flush is done and the flag bit
324 is cleared.
325
326 .. important::
327
328 It is often important, if you defer the flush,
329 that the actual flush occurs on the same CPU
330 as did the cpu stores into the page to make it
331 dirty. Again, see sparc64 for examples of how
332 to deal with this.
333
334 ``void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
335 unsigned long user_vaddr, void *dst, void *src, int len)``
336 ``void copy_from_user_page(struct vm_area_struct *vma, struct page *page,
337 unsigned long user_vaddr, void *dst, void *src, int len)``
338
339 When the kernel needs to copy arbitrary data in and out
340 of arbitrary user pages (f.e. for ptrace()) it will use
341 these two routines.
342
343 Any necessary cache flushing or other coherency operations
344 that need to occur should happen here. If the processor's
345 instruction cache does not snoop cpu stores, it is very
346 likely that you will need to flush the instruction cache
347 for copy_to_user_page().
348
349 ``void flush_anon_page(struct vm_area_struct *vma, struct page *page,
350 unsigned long vmaddr)``
351
352 When the kernel needs to access the contents of an anonymous
353 page, it calls this function (currently only
354 get_user_pages()). Note: flush_dcache_folio() deliberately
355 doesn't work for an anonymous page. The default
356 implementation is a nop (and should remain so for all coherent
357 architectures). For incoherent architectures, it should flush
358 the cache of the page at vmaddr.
359
360 ``void flush_icache_range(unsigned long start, unsigned long end)``
361
362 When the kernel stores into addresses that it will execute
363 out of (eg when loading modules), this function is called.
364
365 If the icache does not snoop stores then this routine will need
366 to flush it.
367
368 ``void flush_icache_page(struct vm_area_struct *vma, struct page *page)``
369
370 All the functionality of flush_icache_page can be implemented in
371 flush_dcache_folio and update_mmu_cache_range. In the future, the hope
372 is to remove this interface completely.
373
374 The final category of APIs is for I/O to deliberately aliased address
375 ranges inside the kernel. Such aliases are set up by use of the
376 vmap/vmalloc API. Since kernel I/O goes via physical pages, the I/O
377 subsystem assumes that the user mapping and kernel offset mapping are
378 the only aliases. This isn't true for vmap aliases, so anything in
379 the kernel trying to do I/O to vmap areas must manually manage
380 coherency. It must do this by flushing the vmap range before doing
381 I/O and invalidating it after the I/O returns.
382
383 ``void flush_kernel_vmap_range(void *vaddr, int size)``
384
385 flushes the kernel cache for a given virtual address range in
386 the vmap area. This is to make sure that any data the kernel
387 modified in the vmap range is made visible to the physical
388 page. The design is to make this area safe to perform I/O on.
389 Note that this API does *not* also flush the offset map alias
390 of the area.
391
392 ``void invalidate_kernel_vmap_range(void *vaddr, int size) invalidates``
393
394 the cache for a given virtual address range in the vmap area
395 which prevents the processor from making the cache stale by
396 speculatively reading data while the I/O was occurring to the
397 physical pages. This is only necessary for data reads into the
398 vmap area.
399

3. 한국어 전문 번역

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

Cache and TLB Flushing Under Linux

1-22

저자는 David S. Miller <[email protected]>입니다.

이 문서는 Linux VM subsystem이 호출하는 cache/TLB flushing interface를 열거하고, 각 interface의 목적과 호출 뒤에 기대되는 side effect를 설명합니다.

아래의 side effect는 uniprocessor 구현과 그 단일 processor에서 일어나야 하는 동작을 기준으로 서술합니다. SMP에서는 해당 interface의 side effect가 시스템의 모든 processor에서 발생하도록 정의를 확장하면 됩니다.

그렇다고 SMP cache/TLB flush가 반드시 비효율적이어야 하는 것은 아니며, 많은 최적화가 가능합니다. 예를 들어 어떤 user address space가 특정 CPU에서 실행된 적이 없음을 `mm_cpumask()`로 증명할 수 있다면 그 CPU에서는 해당 address space를 flush할 필요가 없습니다.

TLB 추상화와 flush_tlb_all()

23-40

먼저 더 단순한 TLB flushing interface를 설명합니다. Linux에서 TLB는 CPU가 software page table에서 얻은 virtual-to-physical address translation을 cache하는 대상으로 추상화됩니다. 따라서 software page table이 바뀌면 TLB cache에 오래된 translation이 남을 수 있습니다.

이 때문에 kernel은 software page table을 변경한 뒤 다음 flush method 가운데 하나를 호출합니다.

1) ``void flush_tlb_all(void)``

`flush_tlb_all()`은 가장 강력한 flush입니다. 호출이 끝나면 그 전에 이루어진 모든 page table 변경이 CPU에 보여야 합니다. 보통 translation이 global 성격을 갖는 kernel page table을 변경할 때 호출합니다.

전체 user address space TLB flush

41-52
2) ``void flush_tlb_mm(struct mm_struct *mm)``

`flush_tlb_mm()`은 user address space 전체를 TLB에서 flush합니다. 실행 뒤에는 `mm` address space에 대해 이전에 수행된 모든 page table 변경이 CPU에 보여야 하며, TLB에 `mm`의 entry가 하나도 남아 있지 않아야 합니다.

이 interface는 `fork`와 `exec`에서 일어나는 것과 같은 전체 address space page table 작업을 처리할 때 사용합니다.

가상 주소 범위 TLB flush

53-72
3) ``void flush_tlb_range(struct vm_area_struct *vma,
   unsigned long start, unsigned long end)``

`flush_tlb_range()`는 특정 user virtual address translation 범위를 TLB에서 flush합니다. 실행 뒤에는 `vma->vm_mm` address space의 `start`부터 `end-1`까지에 대한 이전 page table 변경이 CPU에 보여야 하며, 해당 범위의 TLB entry가 남아 있지 않아야 합니다.

`vma`는 이 영역에 사용되는 backing store입니다. 주된 용도는 `munmap()` 유형의 작업입니다.

이 interface는 수정될 수 있는 각 entry마다 kernel이 아래의 `flush_tlb_page()`를 호출하는 대신, port가 page 크기의 translation 여러 개를 TLB에서 효율적으로 제거할 수 있도록 제공합니다.

단일 page TLB flush

73-90
4) ``void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)``

`flush_tlb_page()`는 TLB에서 `PAGE_SIZE` 크기의 translation을 제거합니다. `vma`는 process의 mmap 영역을 추적하는 backing structure이고 address space는 `vma->vm_mm`으로 얻습니다. `(vma->vm_flags & VM_EXEC)`를 검사하면 이 영역이 실행 가능하여 split-TLB 구성의 instruction TLB에 들어갈 수 있는지도 알 수 있습니다.

실행 뒤에는 `vma->vm_mm`의 user virtual address `addr`에 대해 이전의 모든 page table 변경이 CPU에 보여야 하며, 그 주소의 TLB entry가 없어야 합니다. 주로 fault 처리 중에 사용합니다.

page fault 뒤 translation 통지

91-107
5) ``void update_mmu_cache_range(struct vm_fault *vmf,
   struct vm_area_struct *vma, unsigned long address, pte_t *ptep,
   unsigned int nr)``

모든 page fault의 끝에서 `update_mmu_cache_range()`를 호출하여 architecture-specific code에 `vma->vm_mm` address space의 virtual address `address`부터 연속된 `nr`개 page에 대한 translation이 software page table에 생겼음을 알립니다.

이 routine은 여러 다른 위치에서도 호출되며, 이때는 `vmf`에 `NULL`을 전달합니다. Port는 이 정보를 원하는 방식으로 활용할 수 있습니다. 예를 들어 software-managed TLB 구성에서는 이 event를 이용해 TLB translation을 미리 load할 수 있으며, 현재 sparc64 port가 그렇게 합니다.

cache flush와 page table 변경 순서

108-140

다음은 cache flushing interface입니다. Linux가 기존 virtual-to-physical mapping을 새 값으로 바꿀 때의 순서는 보통 다음 세 형태 가운데 하나입니다.

1) flush_cache_mm(mm);
   change_all_page_tables_of(mm);
   flush_tlb_mm(mm);

2) flush_cache_range(vma, start, end);
   change_range_of_page_tables(mm, start, end);
   flush_tlb_range(vma, start, end);

3) flush_cache_page(vma, addr, pfn);
   set_pte(pte_pointer, new_pte_val);
   flush_tlb_page(vma, addr);

cache level flush는 항상 먼저 수행됩니다. 이는 virtual address를 cache에서 flush할 때 그 주소의 virtual-to-physical translation이 존재해야 하는 strict cache 시스템을 올바르게 처리하기 위해서입니다. HyperSparc CPU가 이 특성을 갖습니다.

아래 routine은 특정 CPU에 필요한 범위까지만 cache flush를 처리하면 됩니다. 대체로 virtual-to-physical translation을 변경하거나 제거할 때 flush해야 하는 virtually indexed cache를 가진 CPU에서 구현해야 합니다.

반대로 IA32 processor의 physically indexed, physically tagged cache는 완전히 동기화되어 있고 translation 정보에 의존하지 않으므로 이 interface를 구현할 필요가 없습니다.

전체 address space cache flush

141-161
1) ``void flush_cache_mm(struct mm_struct *mm)``

`flush_cache_mm()`은 user address space 전체를 cache에서 flush합니다. 실행 뒤에는 `mm`과 연관된 cache line이 하나도 남지 않아야 합니다. `exit`와 `exec` 같은 전체 address space page table 작업에 사용합니다.

2) ``void flush_cache_dup_mm(struct mm_struct *mm)``

`flush_cache_dup_mm()`도 user address space 전체를 flush하여 `mm` 관련 cache line을 모두 제거하지만, `fork` 중의 전체 address space page table 작업에 사용합니다. VIPT cache를 위한 최적화를 허용하기 위해 `flush_cache_mm()`과 분리되어 있습니다.

가상 주소 범위 cache flush

162-178
3) ``void flush_cache_range(struct vm_area_struct *vma,
   unsigned long start, unsigned long end)``

`flush_cache_range()`는 특정 user virtual address 범위를 cache에서 flush합니다. 실행 뒤에는 `vma->vm_mm`의 `start`부터 `end-1`까지에 해당하는 cache entry가 남지 않아야 합니다.

`vma`는 이 영역의 backing store이며 주된 용도는 `munmap()` 유형 작업입니다. Kernel이 수정 가능한 entry마다 아래의 `flush_cache_page()`를 호출하는 대신, port가 page 크기 영역 여러 개를 효율적으로 제거할 수 있도록 이 interface를 제공합니다.

page, kmap, vmap cache flush

179-223
4) ``void flush_cache_page(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn)``

`flush_cache_page()`는 cache에서 `PAGE_SIZE` 크기의 범위를 제거합니다. `vma`는 process의 mmap 영역을 추적하고, address space는 `vma->vm_mm`으로 얻습니다. `(vma->vm_flags & VM_EXEC)`로 실행 가능한 영역인지 검사하면 Harvard형 cache layout의 instruction cache에 들어갈 수 있는지도 판단할 수 있습니다.

`pfn`은 `addr`이 translation되는 physical page frame을 나타냅니다. 이 값을 `PAGE_SHIFT`만큼 왼쪽으로 shift하면 physical address가 됩니다. 호출 뒤에는 `addr`에서 `pfn`으로 translation되는 `vma->vm_mm` cache entry가 없어야 하며, 주로 fault 처리 중에 사용합니다.

5) ``void flush_cache_kmaps(void)``

`flush_cache_kmaps()`는 platform이 highmem을 사용할 때만 구현하면 됩니다. 모든 kmap을 invalidate하기 직전에 호출되며, 실행 뒤에는 `PKMAP_ADDR(0)`부터 `PKMAP_ADDR(LAST_PKMAP)`까지의 kernel virtual address 범위에 cache entry가 없어야 합니다. 이 routine은 `asm/highmem.h`에 구현해야 합니다.

6) ``void flush_cache_vmap(unsigned long start, unsigned long end)``
   ``void flush_cache_vunmap(unsigned long start, unsigned long end)``

`flush_cache_vmap()`과 `flush_cache_vunmap()`은 특정 kernel virtual address 범위를 cache에서 flush합니다. 실행 뒤에는 kernel address space의 `start`부터 `end-1`까지에 cache entry가 없어야 합니다.

첫 번째 routine은 `vmap_range()`가 page table entry를 설치한 뒤 호출하고, 두 번째 routine은 `vunmap_range()`가 page table entry를 삭제하기 전에 호출합니다.

D-cache virtual aliasing

224-254

CPU cache 문제 가운데에는 별도의 interface 집합이 필요한 또 다른 부류가 있으며, 가장 큰 문제는 processor data cache의 virtual aliasing입니다.

D-cache가 virtually indexed이고 크기가 `PAGE_SIZE`보다 크며, 같은 physical address에 대한 cache line 여러 개가 동시에 존재하는 것을 막지 않는다면 이 문제가 발생합니다.

해당 port는 먼저 `asm/shmparam.h`의 `SHMLBA`를 올바르게 정의해야 합니다. 값은 본질적으로 virtually addressed D-cache의 크기여야 하며, 크기가 가변이면 가능한 최대 크기를 써야 합니다. 그러면 SYSV IPC layer는 user process가 이 값의 배수인 address에만 shared memory를 mmap하도록 제한합니다.

이 설정만으로 shared mmap 문제를 해결할 수는 없습니다. 한 가지 해결 방식은 sparc64 port, 특히 `SPARC_FLAG_MMAPSHARED`를 참고하십시오.

그 밖의 모든 경우에 대해서도 D-cache aliasing을 해결해야 합니다. 어떤 page가 user address space에 mapping되면 `PAGE_OFFSET`에서 시작하는 kernel linear mapping에도 항상 적어도 하나의 mapping이 있습니다. 따라서 첫 user가 physical page를 mapping하는 즉시 kernel의 virtual address mapping과 aliasing할 가능성이 생깁니다.

anonymous 및 COW page 복사와 초기화

255-275
``void copy_user_page(void *to, void *from, unsigned long addr, struct page *page)``
``void clear_user_page(void *to, unsigned long addr, struct page *page)``

`copy_user_page()`와 `clear_user_page()`는 user anonymous page 또는 COW page에 data를 저장하며, port가 userspace와 kernel 사이의 D-cache alias 문제를 효율적으로 피할 수 있게 합니다.

예를 들어 copy 중에 `from`과 `to`를 임시 kernel virtual address에 mapping할 수 있습니다. 두 page의 virtual address는 kernel load/store instruction이 user mapping과 같은 cache "color"의 virtual address에 접근하도록 선택합니다. sparc64가 이 기법을 사용합니다.

`addr` parameter는 user가 최종적으로 이 page를 mapping할 virtual address를 알리고, `page` parameter는 target의 `struct page` pointer를 제공합니다. D-cache aliasing이 문제가 아니라면 두 routine은 단순히 `memcpy` 또는 `memset`을 직접 호출해도 됩니다.

page cache의 flush_dcache_folio()

276-333
``void flush_dcache_folio(struct folio *folio)``

`flush_dcache_folio()`는 다음 상황에서 호출해야 합니다.

  • kernel이 page cache에 있으면서 또는 high memory에 있는 page에 data를 쓴 경우
  • kernel이 page cache page를 읽으려 하고, 이 page의 user space shared/writable mapping이 존재할 가능성이 있는 경우. `{get,pin}_user_pages{_fast}`는 user address space에서 찾은 모든 page에 이미 `flush_dcache_folio()`를 호출하므로 driver code가 이를 직접 고려해야 하는 일은 드뭅니다.

이 routine은 user process address space에 mapping될 가능성이 있는 page cache page에만 호출하면 됩니다. 예를 들어 page cache의 VFS symlink를 처리하는 VFS layer code는 이 interface를 호출할 필요가 없습니다.

"kernel이 page cache page에 쓴다"는 말은 구체적으로 kernel이 해당 page의 kernel virtual mapping에서 store instruction을 실행해 data를 dirty하게 만든다는 뜻입니다. 이러한 kernel store가 page의 user space mapping에 보이도록 D-cache aliasing을 처리하기 위해 여기서 flush하는 것이 중요합니다.

반대 경우도 중요합니다. 이 file의 shared+writable mapping을 가진 user가 있다면 kernel이 이 page를 읽을 때 user의 최신 store를 보도록 보장해야 합니다. D-cache aliasing이 문제가 아니면 architecture에서 이 routine을 nop으로 정의할 수 있습니다.

`folio->flags`에는 architecture private 용도의 `PG_arch_1` bit가 마련되어 있습니다. Kernel은 pagecache page가 처음 pagecache에 들어갈 때 이 bit를 clear하도록 보장합니다.

이를 이용하면 현재 이 page를 mapping한 user process가 없을 때 실제 flush를 나중으로, 어쩌면 무기한 연기할 수 있습니다. 구현 예는 sparc64의 `flush_dcache_folio()`와 `update_mmu_cache_range()`를 참고하십시오.

`flush_dcache_folio()` 시점에 `folio_flush_mapping()`이 mapping을 반환하고 그 mapping에 대한 `mapping_mapped()`가 `%false`를 반환하면 architecture private page flag bit만 set합니다. 나중에 `update_mmu_cache_range()`에서 이 bit를 검사하여 set되어 있으면 flush한 뒤 bit를 clear합니다.

Flush를 연기한다면 실제 flush가 page를 dirty하게 만든 CPU store와 같은 CPU에서 실행되어야 하는 경우가 많습니다. 이 문제를 다루는 방법 역시 sparc64 구현을 참고하십시오.

user page와 instruction cache interface

334-373
``void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long user_vaddr, void *dst, void *src, int len)``
``void copy_from_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long user_vaddr, void *dst, void *src, int len)``

Kernel이 `ptrace()` 등의 목적으로 임의의 user page에 임의 data를 복사하거나 그 page에서 복사할 때 `copy_to_user_page()`와 `copy_from_user_page()`를 사용합니다. 필요한 cache flush 또는 coherency 작업은 여기에서 수행해야 합니다. Processor instruction cache가 CPU store를 snoop하지 않는다면 `copy_to_user_page()`에서 instruction cache를 flush해야 할 가능성이 큽니다.

``void flush_anon_page(struct vm_area_struct *vma, struct page *page,
unsigned long vmaddr)``

Kernel이 anonymous page 내용에 접근해야 할 때, 현재는 `get_user_pages()`에서 `flush_anon_page()`를 호출합니다. `flush_dcache_folio()`는 의도적으로 anonymous page에 동작하지 않습니다. 기본 구현은 nop이며 모든 coherent architecture에서도 그대로여야 합니다. Incoherent architecture에서는 `vmaddr`에 있는 page의 cache를 flush해야 합니다.

``void flush_icache_range(unsigned long start, unsigned long end)``

Kernel이 module을 load할 때처럼 나중에 실행할 address에 store하면 `flush_icache_range()`를 호출합니다. I-cache가 store를 snoop하지 않는다면 이 routine이 I-cache를 flush해야 합니다.

``void flush_icache_page(struct vm_area_struct *vma, struct page *page)``

`flush_icache_page()`의 모든 기능은 `flush_dcache_folio()`와 `update_mmu_cache_range()`로 구현할 수 있습니다. 향후에는 이 interface를 완전히 제거하는 것이 목표입니다.

vmap alias의 I/O coherency

374-398

마지막 API 부류는 kernel 내부에서 의도적으로 alias된 address range에 대한 I/O를 다룹니다. 이러한 alias는 `vmap`/`vmalloc` API로 만듭니다. Kernel I/O는 physical page를 통해 이루어지므로 I/O subsystem은 user mapping과 kernel offset mapping만 alias라고 가정하지만, vmap alias에서는 이 가정이 맞지 않습니다.

따라서 vmap 영역에 I/O를 수행하는 kernel code는 I/O 전에 vmap range를 flush하고 I/O가 돌아온 뒤 invalidate하여 coherency를 직접 관리해야 합니다.

``void flush_kernel_vmap_range(void *vaddr, int size)``

`flush_kernel_vmap_range()`는 vmap 영역의 주어진 virtual address range에 대해 kernel cache를 flush합니다. Kernel이 vmap range에서 수정한 data가 physical page에 보이게 하여 이 영역에서 I/O를 안전하게 수행하도록 합니다. 이 API는 해당 영역의 offset map alias까지 flush하지는 않습니다.

``void invalidate_kernel_vmap_range(void *vaddr, int size) invalidates``

`invalidate_kernel_vmap_range()`는 vmap 영역의 주어진 virtual address range cache를 invalidate합니다. I/O가 physical page에서 진행되는 동안 processor가 data를 speculative read하여 cache를 stale하게 만드는 것을 막습니다. 이 작업은 vmap 영역으로 data를 읽어 들이는 경우에만 필요합니다.