docs/vm: add index.rst and link MM documentation to top level index
[linux-block.git] / Documentation / vm / hmm.rst
1 .. hmm:
2
3 =====================================
4 Heterogeneous Memory Management (HMM)
5 =====================================
6
7 Transparently allow any component of a program to use any memory region of said
8 program with a device without using device specific memory allocator. This is
9 becoming a requirement to simplify the use of advance heterogeneous computing
10 where GPU, DSP or FPGA are use to perform various computations.
11
12 This document is divided as follow, in the first section i expose the problems
13 related to the use of a device specific allocator. The second section i expose
14 the hardware limitations that are inherent to many platforms. The third section
15 gives an overview of HMM designs. The fourth section explains how CPU page-
16 table mirroring works and what is HMM purpose in this context. Fifth section
17 deals with how device memory is represented inside the kernel. Finaly the last
18 section present the new migration helper that allow to leverage the device DMA
19 engine.
20
21 .. contents:: :local:
22
23 Problems of using device specific memory allocator
24 ==================================================
25
26 Device with large amount of on board memory (several giga bytes) like GPU have
27 historically manage their memory through dedicated driver specific API. This
28 creates a disconnect between memory allocated and managed by device driver and
29 regular application memory (private anonymous, share memory or regular file
30 back memory). From here on i will refer to this aspect as split address space.
31 I use share address space to refer to the opposite situation ie one in which
32 any memory region can be use by device transparently.
33
34 Split address space because device can only access memory allocated through the
35 device specific API. This imply that all memory object in a program are not
36 equal from device point of view which complicate large program that rely on a
37 wide set of libraries.
38
39 Concretly this means that code that wants to leverage device like GPU need to
40 copy object between genericly allocated memory (malloc, mmap private/share/)
41 and memory allocated through the device driver API (this still end up with an
42 mmap but of the device file).
43
44 For flat dataset (array, grid, image, ...) this isn't too hard to achieve but
45 complex data-set (list, tree, ...) are hard to get right. Duplicating a complex
46 data-set need to re-map all the pointer relations between each of its elements.
47 This is error prone and program gets harder to debug because of the duplicate
48 data-set.
49
50 Split address space also means that library can not transparently use data they
51 are getting from core program or other library and thus each library might have
52 to duplicate its input data-set using specific memory allocator. Large project
53 suffer from this and waste resources because of the various memory copy.
54
55 Duplicating each library API to accept as input or output memory allocted by
56 each device specific allocator is not a viable option. It would lead to a
57 combinatorial explosions in the library entry points.
58
59 Finaly with the advance of high level language constructs (in C++ but in other
60 language too) it is now possible for compiler to leverage GPU or other devices
61 without even the programmer knowledge. Some of compiler identified patterns are
62 only do-able with a share address. It is as well more reasonable to use a share
63 address space for all the other patterns.
64
65
66 System bus, device memory characteristics
67 =========================================
68
69 System bus cripple share address due to few limitations. Most system bus only
70 allow basic memory access from device to main memory, even cache coherency is
71 often optional. Access to device memory from CPU is even more limited, most
72 often than not it is not cache coherent.
73
74 If we only consider the PCIE bus than device can access main memory (often
75 through an IOMMU) and be cache coherent with the CPUs. However it only allows
76 a limited set of atomic operation from device on main memory. This is worse
77 in the other direction the CPUs can only access a limited range of the device
78 memory and can not perform atomic operations on it. Thus device memory can not
79 be consider like regular memory from kernel point of view.
80
81 Another crippling factor is the limited bandwidth (~32GBytes/s with PCIE 4.0
82 and 16 lanes). This is 33 times less that fastest GPU memory (1 TBytes/s).
83 The final limitation is latency, access to main memory from the device has an
84 order of magnitude higher latency than when the device access its own memory.
85
86 Some platform are developing new system bus or additions/modifications to PCIE
87 to address some of those limitations (OpenCAPI, CCIX). They mainly allow two
88 way cache coherency between CPU and device and allow all atomic operations the
89 architecture supports. Saddly not all platform are following this trends and
90 some major architecture are left without hardware solutions to those problems.
91
92 So for share address space to make sense not only we must allow device to
93 access any memory memory but we must also permit any memory to be migrated to
94 device memory while device is using it (blocking CPU access while it happens).
95
96
97 Share address space and migration
98 =================================
99
100 HMM intends to provide two main features. First one is to share the address
101 space by duplication the CPU page table into the device page table so same
102 address point to same memory and this for any valid main memory address in
103 the process address space.
104
105 To achieve this, HMM offer a set of helpers to populate the device page table
106 while keeping track of CPU page table updates. Device page table updates are
107 not as easy as CPU page table updates. To update the device page table you must
108 allow a buffer (or use a pool of pre-allocated buffer) and write GPU specifics
109 commands in it to perform the update (unmap, cache invalidations and flush,
110 ...). This can not be done through common code for all device. Hence why HMM
111 provides helpers to factor out everything that can be while leaving the gory
112 details to the device driver.
113
114 The second mechanism HMM provide is a new kind of ZONE_DEVICE memory that does
115 allow to allocate a struct page for each page of the device memory. Those page
116 are special because the CPU can not map them. They however allow to migrate
117 main memory to device memory using exhisting migration mechanism and everything
118 looks like if page was swap out to disk from CPU point of view. Using a struct
119 page gives the easiest and cleanest integration with existing mm mechanisms.
120 Again here HMM only provide helpers, first to hotplug new ZONE_DEVICE memory
121 for the device memory and second to perform migration. Policy decision of what
122 and when to migrate things is left to the device driver.
123
124 Note that any CPU access to a device page trigger a page fault and a migration
125 back to main memory ie when a page backing an given address A is migrated from
126 a main memory page to a device page then any CPU access to address A trigger a
127 page fault and initiate a migration back to main memory.
128
129
130 With this two features, HMM not only allow a device to mirror a process address
131 space and keeps both CPU and device page table synchronize, but also allow to
132 leverage device memory by migrating part of data-set that is actively use by a
133 device.
134
135
136 Address space mirroring implementation and API
137 ==============================================
138
139 Address space mirroring main objective is to allow to duplicate range of CPU
140 page table into a device page table and HMM helps keeping both synchronize. A
141 device driver that want to mirror a process address space must start with the
142 registration of an hmm_mirror struct::
143
144  int hmm_mirror_register(struct hmm_mirror *mirror,
145                          struct mm_struct *mm);
146  int hmm_mirror_register_locked(struct hmm_mirror *mirror,
147                                 struct mm_struct *mm);
148
149 The locked variant is to be use when the driver is already holding the mmap_sem
150 of the mm in write mode. The mirror struct has a set of callback that are use
151 to propagate CPU page table::
152
153  struct hmm_mirror_ops {
154      /* sync_cpu_device_pagetables() - synchronize page tables
155       *
156       * @mirror: pointer to struct hmm_mirror
157       * @update_type: type of update that occurred to the CPU page table
158       * @start: virtual start address of the range to update
159       * @end: virtual end address of the range to update
160       *
161       * This callback ultimately originates from mmu_notifiers when the CPU
162       * page table is updated. The device driver must update its page table
163       * in response to this callback. The update argument tells what action
164       * to perform.
165       *
166       * The device driver must not return from this callback until the device
167       * page tables are completely updated (TLBs flushed, etc); this is a
168       * synchronous call.
169       */
170       void (*update)(struct hmm_mirror *mirror,
171                      enum hmm_update action,
172                      unsigned long start,
173                      unsigned long end);
174  };
175
176 Device driver must perform update to the range following action (turn range
177 read only, or fully unmap, ...). Once driver callback returns the device must
178 be done with the update.
179
180
181 When device driver wants to populate a range of virtual address it can use
182 either::
183
184  int hmm_vma_get_pfns(struct vm_area_struct *vma,
185                       struct hmm_range *range,
186                       unsigned long start,
187                       unsigned long end,
188                       hmm_pfn_t *pfns);
189  int hmm_vma_fault(struct vm_area_struct *vma,
190                    struct hmm_range *range,
191                    unsigned long start,
192                    unsigned long end,
193                    hmm_pfn_t *pfns,
194                    bool write,
195                    bool block);
196
197 First one (hmm_vma_get_pfns()) will only fetch present CPU page table entry and
198 will not trigger a page fault on missing or non present entry. The second one
199 do trigger page fault on missing or read only entry if write parameter is true.
200 Page fault use the generic mm page fault code path just like a CPU page fault.
201
202 Both function copy CPU page table into their pfns array argument. Each entry in
203 that array correspond to an address in the virtual range. HMM provide a set of
204 flags to help driver identify special CPU page table entries.
205
206 Locking with the update() callback is the most important aspect the driver must
207 respect in order to keep things properly synchronize. The usage pattern is::
208
209  int driver_populate_range(...)
210  {
211       struct hmm_range range;
212       ...
213  again:
214       ret = hmm_vma_get_pfns(vma, &range, start, end, pfns);
215       if (ret)
216           return ret;
217       take_lock(driver->update);
218       if (!hmm_vma_range_done(vma, &range)) {
219           release_lock(driver->update);
220           goto again;
221       }
222
223       // Use pfns array content to update device page table
224
225       release_lock(driver->update);
226       return 0;
227  }
228
229 The driver->update lock is the same lock that driver takes inside its update()
230 callback. That lock must be call before hmm_vma_range_done() to avoid any race
231 with a concurrent CPU page table update.
232
233 HMM implements all this on top of the mmu_notifier API because we wanted to a
234 simpler API and also to be able to perform optimization latter own like doing
235 concurrent device update in multi-devices scenario.
236
237 HMM also serve as an impedence missmatch between how CPU page table update are
238 done (by CPU write to the page table and TLB flushes) from how device update
239 their own page table. Device update is a multi-step process, first appropriate
240 commands are write to a buffer, then this buffer is schedule for execution on
241 the device. It is only once the device has executed commands in the buffer that
242 the update is done. Creating and scheduling update command buffer can happen
243 concurrently for multiple devices. Waiting for each device to report commands
244 as executed is serialize (there is no point in doing this concurrently).
245
246
247 Represent and manage device memory from core kernel point of view
248 =================================================================
249
250 Several differents design were try to support device memory. First one use
251 device specific data structure to keep information about migrated memory and
252 HMM hooked itself in various place of mm code to handle any access to address
253 that were back by device memory. It turns out that this ended up replicating
254 most of the fields of struct page and also needed many kernel code path to be
255 updated to understand this new kind of memory.
256
257 Thing is most kernel code path never try to access the memory behind a page
258 but only care about struct page contents. Because of this HMM switchted to
259 directly using struct page for device memory which left most kernel code path
260 un-aware of the difference. We only need to make sure that no one ever try to
261 map those page from the CPU side.
262
263 HMM provide a set of helpers to register and hotplug device memory as a new
264 region needing struct page. This is offer through a very simple API::
265
266  struct hmm_devmem *hmm_devmem_add(const struct hmm_devmem_ops *ops,
267                                    struct device *device,
268                                    unsigned long size);
269  void hmm_devmem_remove(struct hmm_devmem *devmem);
270
271 The hmm_devmem_ops is where most of the important things are::
272
273  struct hmm_devmem_ops {
274      void (*free)(struct hmm_devmem *devmem, struct page *page);
275      int (*fault)(struct hmm_devmem *devmem,
276                   struct vm_area_struct *vma,
277                   unsigned long addr,
278                   struct page *page,
279                   unsigned flags,
280                   pmd_t *pmdp);
281  };
282
283 The first callback (free()) happens when the last reference on a device page is
284 drop. This means the device page is now free and no longer use by anyone. The
285 second callback happens whenever CPU try to access a device page which it can
286 not do. This second callback must trigger a migration back to system memory.
287
288
289 Migrate to and from device memory
290 =================================
291
292 Because CPU can not access device memory, migration must use device DMA engine
293 to perform copy from and to device memory. For this we need a new migration
294 helper::
295
296  int migrate_vma(const struct migrate_vma_ops *ops,
297                  struct vm_area_struct *vma,
298                  unsigned long mentries,
299                  unsigned long start,
300                  unsigned long end,
301                  unsigned long *src,
302                  unsigned long *dst,
303                  void *private);
304
305 Unlike other migration function it works on a range of virtual address, there
306 is two reasons for that. First device DMA copy has a high setup overhead cost
307 and thus batching multiple pages is needed as otherwise the migration overhead
308 make the whole excersie pointless. The second reason is because driver trigger
309 such migration base on range of address the device is actively accessing.
310
311 The migrate_vma_ops struct define two callbacks. First one (alloc_and_copy())
312 control destination memory allocation and copy operation. Second one is there
313 to allow device driver to perform cleanup operation after migration::
314
315  struct migrate_vma_ops {
316      void (*alloc_and_copy)(struct vm_area_struct *vma,
317                             const unsigned long *src,
318                             unsigned long *dst,
319                             unsigned long start,
320                             unsigned long end,
321                             void *private);
322      void (*finalize_and_map)(struct vm_area_struct *vma,
323                               const unsigned long *src,
324                               const unsigned long *dst,
325                               unsigned long start,
326                               unsigned long end,
327                               void *private);
328  };
329
330 It is important to stress that this migration helpers allow for hole in the
331 virtual address range. Some pages in the range might not be migrated for all
332 the usual reasons (page is pin, page is lock, ...). This helper does not fail
333 but just skip over those pages.
334
335 The alloc_and_copy() might as well decide to not migrate all pages in the
336 range (for reasons under the callback control). For those the callback just
337 have to leave the corresponding dst entry empty.
338
339 Finaly the migration of the struct page might fails (for file back page) for
340 various reasons (failure to freeze reference, or update page cache, ...). If
341 that happens then the finalize_and_map() can catch any pages that was not
342 migrated. Note those page were still copied to new page and thus we wasted
343 bandwidth but this is considered as a rare event and a price that we are
344 willing to pay to keep all the code simpler.
345
346
347 Memory cgroup (memcg) and rss accounting
348 ========================================
349
350 For now device memory is accounted as any regular page in rss counters (either
351 anonymous if device page is use for anonymous, file if device page is use for
352 file back page or shmem if device page is use for share memory). This is a
353 deliberate choice to keep existing application that might start using device
354 memory without knowing about it to keep runing unimpacted.
355
356 Drawbacks is that OOM killer might kill an application using a lot of device
357 memory and not a lot of regular system memory and thus not freeing much system
358 memory. We want to gather more real world experience on how application and
359 system react under memory pressure in the presence of device memory before
360 deciding to account device memory differently.
361
362
363 Same decision was made for memory cgroup. Device memory page are accounted
364 against same memory cgroup a regular page would be accounted to. This does
365 simplify migration to and from device memory. This also means that migration
366 back from device memory to regular memory can not fail because it would
367 go above memory cgroup limit. We might revisit this choice latter on once we
368 get more experience in how device memory is use and its impact on memory
369 resource control.
370
371
372 Note that device memory can never be pin nor by device driver nor through GUP
373 and thus such memory is always free upon process exit. Or when last reference
374 is drop in case of share memory or file back memory.