xref: /openbmc/linux/Documentation/mm/hmm.rst (revision c900529f3d9161bfde5cca0754f83b4d3c3e0220)
1ee65728eSMike Rapoport=====================================
2ee65728eSMike RapoportHeterogeneous Memory Management (HMM)
3ee65728eSMike Rapoport=====================================
4ee65728eSMike Rapoport
5ee65728eSMike RapoportProvide infrastructure and helpers to integrate non-conventional memory (device
6ee65728eSMike Rapoportmemory like GPU on board memory) into regular kernel path, with the cornerstone
7ee65728eSMike Rapoportof this being specialized struct page for such memory (see sections 5 to 7 of
8ee65728eSMike Rapoportthis document).
9ee65728eSMike Rapoport
10ee65728eSMike RapoportHMM also provides optional helpers for SVM (Share Virtual Memory), i.e.,
11ee65728eSMike Rapoportallowing a device to transparently access program addresses coherently with
12ee65728eSMike Rapoportthe CPU meaning that any valid pointer on the CPU is also a valid pointer
13ee65728eSMike Rapoportfor the device. This is becoming mandatory to simplify the use of advanced
14ee65728eSMike Rapoportheterogeneous computing where GPU, DSP, or FPGA are used to perform various
15ee65728eSMike Rapoportcomputations on behalf of a process.
16ee65728eSMike Rapoport
17ee65728eSMike RapoportThis document is divided as follows: in the first section I expose the problems
18ee65728eSMike Rapoportrelated to using device specific memory allocators. In the second section, I
19ee65728eSMike Rapoportexpose the hardware limitations that are inherent to many platforms. The third
20ee65728eSMike Rapoportsection gives an overview of the HMM design. The fourth section explains how
21ee65728eSMike RapoportCPU page-table mirroring works and the purpose of HMM in this context. The
22ee65728eSMike Rapoportfifth section deals with how device memory is represented inside the kernel.
23ee65728eSMike RapoportFinally, the last section presents a new migration helper that allows
24ee65728eSMike Rapoportleveraging the device DMA engine.
25ee65728eSMike Rapoport
26ee65728eSMike Rapoport.. contents:: :local:
27ee65728eSMike Rapoport
28ee65728eSMike RapoportProblems of using a device specific memory allocator
29ee65728eSMike Rapoport====================================================
30ee65728eSMike Rapoport
31ee65728eSMike RapoportDevices with a large amount of on board memory (several gigabytes) like GPUs
32ee65728eSMike Rapoporthave historically managed their memory through dedicated driver specific APIs.
33ee65728eSMike RapoportThis creates a disconnect between memory allocated and managed by a device
34ee65728eSMike Rapoportdriver and regular application memory (private anonymous, shared memory, or
35ee65728eSMike Rapoportregular file backed memory). From here on I will refer to this aspect as split
36ee65728eSMike Rapoportaddress space. I use shared address space to refer to the opposite situation:
37ee65728eSMike Rapoporti.e., one in which any application memory region can be used by a device
38ee65728eSMike Rapoporttransparently.
39ee65728eSMike Rapoport
40ee65728eSMike RapoportSplit address space happens because devices can only access memory allocated
41ee65728eSMike Rapoportthrough a device specific API. This implies that all memory objects in a program
42ee65728eSMike Rapoportare not equal from the device point of view which complicates large programs
43ee65728eSMike Rapoportthat rely on a wide set of libraries.
44ee65728eSMike Rapoport
45ee65728eSMike RapoportConcretely, this means that code that wants to leverage devices like GPUs needs
46ee65728eSMike Rapoportto copy objects between generically allocated memory (malloc, mmap private, mmap
47ee65728eSMike Rapoportshare) and memory allocated through the device driver API (this still ends up
48ee65728eSMike Rapoportwith an mmap but of the device file).
49ee65728eSMike Rapoport
50ee65728eSMike RapoportFor flat data sets (array, grid, image, ...) this isn't too hard to achieve but
51ee65728eSMike Rapoportfor complex data sets (list, tree, ...) it's hard to get right. Duplicating a
52ee65728eSMike Rapoportcomplex data set needs to re-map all the pointer relations between each of its
53ee65728eSMike Rapoportelements. This is error prone and programs get harder to debug because of the
54ee65728eSMike Rapoportduplicate data set and addresses.
55ee65728eSMike Rapoport
56ee65728eSMike RapoportSplit address space also means that libraries cannot transparently use data
57ee65728eSMike Rapoportthey are getting from the core program or another library and thus each library
58ee65728eSMike Rapoportmight have to duplicate its input data set using the device specific memory
59ee65728eSMike Rapoportallocator. Large projects suffer from this and waste resources because of the
60ee65728eSMike Rapoportvarious memory copies.
61ee65728eSMike Rapoport
62ee65728eSMike RapoportDuplicating each library API to accept as input or output memory allocated by
63ee65728eSMike Rapoporteach device specific allocator is not a viable option. It would lead to a
64ee65728eSMike Rapoportcombinatorial explosion in the library entry points.
65ee65728eSMike Rapoport
66ee65728eSMike RapoportFinally, with the advance of high level language constructs (in C++ but in
67ee65728eSMike Rapoportother languages too) it is now possible for the compiler to leverage GPUs and
68ee65728eSMike Rapoportother devices without programmer knowledge. Some compiler identified patterns
69ee65728eSMike Rapoportare only do-able with a shared address space. It is also more reasonable to use
70ee65728eSMike Rapoporta shared address space for all other patterns.
71ee65728eSMike Rapoport
72ee65728eSMike Rapoport
73ee65728eSMike RapoportI/O bus, device memory characteristics
74ee65728eSMike Rapoport======================================
75ee65728eSMike Rapoport
76ee65728eSMike RapoportI/O buses cripple shared address spaces due to a few limitations. Most I/O
77ee65728eSMike Rapoportbuses only allow basic memory access from device to main memory; even cache
78ee65728eSMike Rapoportcoherency is often optional. Access to device memory from a CPU is even more
79ee65728eSMike Rapoportlimited. More often than not, it is not cache coherent.
80ee65728eSMike Rapoport
81ee65728eSMike RapoportIf we only consider the PCIE bus, then a device can access main memory (often
82ee65728eSMike Rapoportthrough an IOMMU) and be cache coherent with the CPUs. However, it only allows
83ee65728eSMike Rapoporta limited set of atomic operations from the device on main memory. This is worse
84ee65728eSMike Rapoportin the other direction: the CPU can only access a limited range of the device
85ee65728eSMike Rapoportmemory and cannot perform atomic operations on it. Thus device memory cannot
86ee65728eSMike Rapoportbe considered the same as regular memory from the kernel point of view.
87ee65728eSMike Rapoport
88ee65728eSMike RapoportAnother crippling factor is the limited bandwidth (~32GBytes/s with PCIE 4.0
89ee65728eSMike Rapoportand 16 lanes). This is 33 times less than the fastest GPU memory (1 TBytes/s).
90ee65728eSMike RapoportThe final limitation is latency. Access to main memory from the device has an
91ee65728eSMike Rapoportorder of magnitude higher latency than when the device accesses its own memory.
92ee65728eSMike Rapoport
93ee65728eSMike RapoportSome platforms are developing new I/O buses or additions/modifications to PCIE
94ee65728eSMike Rapoportto address some of these limitations (OpenCAPI, CCIX). They mainly allow
95ee65728eSMike Rapoporttwo-way cache coherency between CPU and device and allow all atomic operations the
96ee65728eSMike Rapoportarchitecture supports. Sadly, not all platforms are following this trend and
97ee65728eSMike Rapoportsome major architectures are left without hardware solutions to these problems.
98ee65728eSMike Rapoport
99ee65728eSMike RapoportSo for shared address space to make sense, not only must we allow devices to
100ee65728eSMike Rapoportaccess any memory but we must also permit any memory to be migrated to device
101ee65728eSMike Rapoportmemory while the device is using it (blocking CPU access while it happens).
102ee65728eSMike Rapoport
103ee65728eSMike Rapoport
104ee65728eSMike RapoportShared address space and migration
105ee65728eSMike Rapoport==================================
106ee65728eSMike Rapoport
107ee65728eSMike RapoportHMM intends to provide two main features. The first one is to share the address
108ee65728eSMike Rapoportspace by duplicating the CPU page table in the device page table so the same
109ee65728eSMike Rapoportaddress points to the same physical memory for any valid main memory address in
110ee65728eSMike Rapoportthe process address space.
111ee65728eSMike Rapoport
112ee65728eSMike RapoportTo achieve this, HMM offers a set of helpers to populate the device page table
113ee65728eSMike Rapoportwhile keeping track of CPU page table updates. Device page table updates are
114ee65728eSMike Rapoportnot as easy as CPU page table updates. To update the device page table, you must
115ee65728eSMike Rapoportallocate a buffer (or use a pool of pre-allocated buffers) and write GPU
116ee65728eSMike Rapoportspecific commands in it to perform the update (unmap, cache invalidations, and
117ee65728eSMike Rapoportflush, ...). This cannot be done through common code for all devices. Hence
118ee65728eSMike Rapoportwhy HMM provides helpers to factor out everything that can be while leaving the
119ee65728eSMike Rapoporthardware specific details to the device driver.
120ee65728eSMike Rapoport
121ee65728eSMike RapoportThe second mechanism HMM provides is a new kind of ZONE_DEVICE memory that
122ee65728eSMike Rapoportallows allocating a struct page for each page of device memory. Those pages
123ee65728eSMike Rapoportare special because the CPU cannot map them. However, they allow migrating
124ee65728eSMike Rapoportmain memory to device memory using existing migration mechanisms and everything
125ee65728eSMike Rapoportlooks like a page that is swapped out to disk from the CPU point of view. Using a
126ee65728eSMike Rapoportstruct page gives the easiest and cleanest integration with existing mm
127ee65728eSMike Rapoportmechanisms. Here again, HMM only provides helpers, first to hotplug new ZONE_DEVICE
128ee65728eSMike Rapoportmemory for the device memory and second to perform migration. Policy decisions
129ee65728eSMike Rapoportof what and when to migrate is left to the device driver.
130ee65728eSMike Rapoport
131ee65728eSMike RapoportNote that any CPU access to a device page triggers a page fault and a migration
132ee65728eSMike Rapoportback to main memory. For example, when a page backing a given CPU address A is
133ee65728eSMike Rapoportmigrated from a main memory page to a device page, then any CPU access to
134ee65728eSMike Rapoportaddress A triggers a page fault and initiates a migration back to main memory.
135ee65728eSMike Rapoport
136ee65728eSMike RapoportWith these two features, HMM not only allows a device to mirror process address
137ee65728eSMike Rapoportspace and keeps both CPU and device page tables synchronized, but also
138ee65728eSMike Rapoportleverages device memory by migrating the part of the data set that is actively being
139ee65728eSMike Rapoportused by the device.
140ee65728eSMike Rapoport
141ee65728eSMike Rapoport
142ee65728eSMike RapoportAddress space mirroring implementation and API
143ee65728eSMike Rapoport==============================================
144ee65728eSMike Rapoport
145ee65728eSMike RapoportAddress space mirroring's main objective is to allow duplication of a range of
146ee65728eSMike RapoportCPU page table into a device page table; HMM helps keep both synchronized. A
147ee65728eSMike Rapoportdevice driver that wants to mirror a process address space must start with the
148ee65728eSMike Rapoportregistration of a mmu_interval_notifier::
149ee65728eSMike Rapoport
150ee65728eSMike Rapoport int mmu_interval_notifier_insert(struct mmu_interval_notifier *interval_sub,
151ee65728eSMike Rapoport				  struct mm_struct *mm, unsigned long start,
152ee65728eSMike Rapoport				  unsigned long length,
153ee65728eSMike Rapoport				  const struct mmu_interval_notifier_ops *ops);
154ee65728eSMike Rapoport
155ee65728eSMike RapoportDuring the ops->invalidate() callback the device driver must perform the
156ee65728eSMike Rapoportupdate action to the range (mark range read only, or fully unmap, etc.). The
157ee65728eSMike Rapoportdevice must complete the update before the driver callback returns.
158ee65728eSMike Rapoport
159ee65728eSMike RapoportWhen the device driver wants to populate a range of virtual addresses, it can
160ee65728eSMike Rapoportuse::
161ee65728eSMike Rapoport
162ee65728eSMike Rapoport  int hmm_range_fault(struct hmm_range *range);
163ee65728eSMike Rapoport
164ee65728eSMike RapoportIt will trigger a page fault on missing or read-only entries if write access is
165ee65728eSMike Rapoportrequested (see below). Page faults use the generic mm page fault code path just
166*090a7f10SMarco Paganilike a CPU page fault. The usage pattern is::
167ee65728eSMike Rapoport
168ee65728eSMike Rapoport int driver_populate_range(...)
169ee65728eSMike Rapoport {
170ee65728eSMike Rapoport      struct hmm_range range;
171ee65728eSMike Rapoport      ...
172ee65728eSMike Rapoport
173ee65728eSMike Rapoport      range.notifier = &interval_sub;
174ee65728eSMike Rapoport      range.start = ...;
175ee65728eSMike Rapoport      range.end = ...;
176ee65728eSMike Rapoport      range.hmm_pfns = ...;
177ee65728eSMike Rapoport
178ee65728eSMike Rapoport      if (!mmget_not_zero(interval_sub->notifier.mm))
179ee65728eSMike Rapoport          return -EFAULT;
180ee65728eSMike Rapoport
181ee65728eSMike Rapoport again:
182ee65728eSMike Rapoport      range.notifier_seq = mmu_interval_read_begin(&interval_sub);
183ee65728eSMike Rapoport      mmap_read_lock(mm);
184ee65728eSMike Rapoport      ret = hmm_range_fault(&range);
185ee65728eSMike Rapoport      if (ret) {
186ee65728eSMike Rapoport          mmap_read_unlock(mm);
187ee65728eSMike Rapoport          if (ret == -EBUSY)
188ee65728eSMike Rapoport                 goto again;
189ee65728eSMike Rapoport          return ret;
190ee65728eSMike Rapoport      }
191ee65728eSMike Rapoport      mmap_read_unlock(mm);
192ee65728eSMike Rapoport
193ee65728eSMike Rapoport      take_lock(driver->update);
194ee65728eSMike Rapoport      if (mmu_interval_read_retry(&ni, range.notifier_seq) {
195ee65728eSMike Rapoport          release_lock(driver->update);
196ee65728eSMike Rapoport          goto again;
197ee65728eSMike Rapoport      }
198ee65728eSMike Rapoport
199ee65728eSMike Rapoport      /* Use pfns array content to update device page table,
200ee65728eSMike Rapoport       * under the update lock */
201ee65728eSMike Rapoport
202ee65728eSMike Rapoport      release_lock(driver->update);
203ee65728eSMike Rapoport      return 0;
204ee65728eSMike Rapoport }
205ee65728eSMike Rapoport
206ee65728eSMike RapoportThe driver->update lock is the same lock that the driver takes inside its
207ee65728eSMike Rapoportinvalidate() callback. That lock must be held before calling
208ee65728eSMike Rapoportmmu_interval_read_retry() to avoid any race with a concurrent CPU page table
209ee65728eSMike Rapoportupdate.
210ee65728eSMike Rapoport
211ee65728eSMike RapoportLeverage default_flags and pfn_flags_mask
212ee65728eSMike Rapoport=========================================
213ee65728eSMike Rapoport
214ee65728eSMike RapoportThe hmm_range struct has 2 fields, default_flags and pfn_flags_mask, that specify
215ee65728eSMike Rapoportfault or snapshot policy for the whole range instead of having to set them
216ee65728eSMike Rapoportfor each entry in the pfns array.
217ee65728eSMike Rapoport
218ee65728eSMike RapoportFor instance if the device driver wants pages for a range with at least read
219ee65728eSMike Rapoportpermission, it sets::
220ee65728eSMike Rapoport
221ee65728eSMike Rapoport    range->default_flags = HMM_PFN_REQ_FAULT;
222ee65728eSMike Rapoport    range->pfn_flags_mask = 0;
223ee65728eSMike Rapoport
224ee65728eSMike Rapoportand calls hmm_range_fault() as described above. This will fill fault all pages
225ee65728eSMike Rapoportin the range with at least read permission.
226ee65728eSMike Rapoport
227ee65728eSMike RapoportNow let's say the driver wants to do the same except for one page in the range for
228ee65728eSMike Rapoportwhich it wants to have write permission. Now driver set::
229ee65728eSMike Rapoport
230ee65728eSMike Rapoport    range->default_flags = HMM_PFN_REQ_FAULT;
231ee65728eSMike Rapoport    range->pfn_flags_mask = HMM_PFN_REQ_WRITE;
232ee65728eSMike Rapoport    range->pfns[index_of_write] = HMM_PFN_REQ_WRITE;
233ee65728eSMike Rapoport
234ee65728eSMike RapoportWith this, HMM will fault in all pages with at least read (i.e., valid) and for the
235ee65728eSMike Rapoportaddress == range->start + (index_of_write << PAGE_SHIFT) it will fault with
236ee65728eSMike Rapoportwrite permission i.e., if the CPU pte does not have write permission set then HMM
237ee65728eSMike Rapoportwill call handle_mm_fault().
238ee65728eSMike Rapoport
239ee65728eSMike RapoportAfter hmm_range_fault completes the flag bits are set to the current state of
240ee65728eSMike Rapoportthe page tables, ie HMM_PFN_VALID | HMM_PFN_WRITE will be set if the page is
241ee65728eSMike Rapoportwritable.
242ee65728eSMike Rapoport
243ee65728eSMike Rapoport
244ee65728eSMike RapoportRepresent and manage device memory from core kernel point of view
245ee65728eSMike Rapoport=================================================================
246ee65728eSMike Rapoport
247ee65728eSMike RapoportSeveral different designs were tried to support device memory. The first one
248ee65728eSMike Rapoportused a device specific data structure to keep information about migrated memory
249ee65728eSMike Rapoportand HMM hooked itself in various places of mm code to handle any access to
250ee65728eSMike Rapoportaddresses that were backed by device memory. It turns out that this ended up
251ee65728eSMike Rapoportreplicating most of the fields of struct page and also needed many kernel code
252ee65728eSMike Rapoportpaths to be updated to understand this new kind of memory.
253ee65728eSMike Rapoport
254ee65728eSMike RapoportMost kernel code paths never try to access the memory behind a page
255ee65728eSMike Rapoportbut only care about struct page contents. Because of this, HMM switched to
256ee65728eSMike Rapoportdirectly using struct page for device memory which left most kernel code paths
257ee65728eSMike Rapoportunaware of the difference. We only need to make sure that no one ever tries to
258ee65728eSMike Rapoportmap those pages from the CPU side.
259ee65728eSMike Rapoport
260ee65728eSMike RapoportMigration to and from device memory
261ee65728eSMike Rapoport===================================
262ee65728eSMike Rapoport
263ee65728eSMike RapoportBecause the CPU cannot access device memory directly, the device driver must
264ee65728eSMike Rapoportuse hardware DMA or device specific load/store instructions to migrate data.
265ee65728eSMike RapoportThe migrate_vma_setup(), migrate_vma_pages(), and migrate_vma_finalize()
266ee65728eSMike Rapoportfunctions are designed to make drivers easier to write and to centralize common
267ee65728eSMike Rapoportcode across drivers.
268ee65728eSMike Rapoport
269ee65728eSMike RapoportBefore migrating pages to device private memory, special device private
270ee65728eSMike Rapoport``struct page`` need to be created. These will be used as special "swap"
271ee65728eSMike Rapoportpage table entries so that a CPU process will fault if it tries to access
272ee65728eSMike Rapoporta page that has been migrated to device private memory.
273ee65728eSMike Rapoport
274ee65728eSMike RapoportThese can be allocated and freed with::
275ee65728eSMike Rapoport
276ee65728eSMike Rapoport    struct resource *res;
277ee65728eSMike Rapoport    struct dev_pagemap pagemap;
278ee65728eSMike Rapoport
279ee65728eSMike Rapoport    res = request_free_mem_region(&iomem_resource, /* number of bytes */,
280ee65728eSMike Rapoport                                  "name of driver resource");
281ee65728eSMike Rapoport    pagemap.type = MEMORY_DEVICE_PRIVATE;
282ee65728eSMike Rapoport    pagemap.range.start = res->start;
283ee65728eSMike Rapoport    pagemap.range.end = res->end;
284ee65728eSMike Rapoport    pagemap.nr_range = 1;
285ee65728eSMike Rapoport    pagemap.ops = &device_devmem_ops;
286ee65728eSMike Rapoport    memremap_pages(&pagemap, numa_node_id());
287ee65728eSMike Rapoport
288ee65728eSMike Rapoport    memunmap_pages(&pagemap);
289ee65728eSMike Rapoport    release_mem_region(pagemap.range.start, range_len(&pagemap.range));
290ee65728eSMike Rapoport
291ee65728eSMike RapoportThere are also devm_request_free_mem_region(), devm_memremap_pages(),
292ee65728eSMike Rapoportdevm_memunmap_pages(), and devm_release_mem_region() when the resources can
293ee65728eSMike Rapoportbe tied to a ``struct device``.
294ee65728eSMike Rapoport
295ee65728eSMike RapoportThe overall migration steps are similar to migrating NUMA pages within system
296ee865889SMike Rapoport (IBM)memory (see Documentation/mm/page_migration.rst) but the steps are split
297ee65728eSMike Rapoportbetween device driver specific code and shared common code:
298ee65728eSMike Rapoport
299ee65728eSMike Rapoport1. ``mmap_read_lock()``
300ee65728eSMike Rapoport
301ee65728eSMike Rapoport   The device driver has to pass a ``struct vm_area_struct`` to
302ee65728eSMike Rapoport   migrate_vma_setup() so the mmap_read_lock() or mmap_write_lock() needs to
303ee65728eSMike Rapoport   be held for the duration of the migration.
304ee65728eSMike Rapoport
305ee65728eSMike Rapoport2. ``migrate_vma_setup(struct migrate_vma *args)``
306ee65728eSMike Rapoport
307ee65728eSMike Rapoport   The device driver initializes the ``struct migrate_vma`` fields and passes
308ee65728eSMike Rapoport   the pointer to migrate_vma_setup(). The ``args->flags`` field is used to
309ee65728eSMike Rapoport   filter which source pages should be migrated. For example, setting
310ee65728eSMike Rapoport   ``MIGRATE_VMA_SELECT_SYSTEM`` will only migrate system memory and
311ee65728eSMike Rapoport   ``MIGRATE_VMA_SELECT_DEVICE_PRIVATE`` will only migrate pages residing in
312ee65728eSMike Rapoport   device private memory. If the latter flag is set, the ``args->pgmap_owner``
313ee65728eSMike Rapoport   field is used to identify device private pages owned by the driver. This
314ee65728eSMike Rapoport   avoids trying to migrate device private pages residing in other devices.
315ee65728eSMike Rapoport   Currently only anonymous private VMA ranges can be migrated to or from
316ee65728eSMike Rapoport   system memory and device private memory.
317ee65728eSMike Rapoport
318ee65728eSMike Rapoport   One of the first steps migrate_vma_setup() does is to invalidate other
319ee65728eSMike Rapoport   device's MMUs with the ``mmu_notifier_invalidate_range_start(()`` and
320ee65728eSMike Rapoport   ``mmu_notifier_invalidate_range_end()`` calls around the page table
321ee65728eSMike Rapoport   walks to fill in the ``args->src`` array with PFNs to be migrated.
322ee65728eSMike Rapoport   The ``invalidate_range_start()`` callback is passed a
323ee65728eSMike Rapoport   ``struct mmu_notifier_range`` with the ``event`` field set to
324ee65728eSMike Rapoport   ``MMU_NOTIFY_MIGRATE`` and the ``owner`` field set to
325ee65728eSMike Rapoport   the ``args->pgmap_owner`` field passed to migrate_vma_setup(). This is
326ee65728eSMike Rapoport   allows the device driver to skip the invalidation callback and only
327ee65728eSMike Rapoport   invalidate device private MMU mappings that are actually migrating.
328ee65728eSMike Rapoport   This is explained more in the next section.
329ee65728eSMike Rapoport
330ee65728eSMike Rapoport   While walking the page tables, a ``pte_none()`` or ``is_zero_pfn()``
331ee65728eSMike Rapoport   entry results in a valid "zero" PFN stored in the ``args->src`` array.
332ee65728eSMike Rapoport   This lets the driver allocate device private memory and clear it instead
333ee65728eSMike Rapoport   of copying a page of zeros. Valid PTE entries to system memory or
334ee65728eSMike Rapoport   device private struct pages will be locked with ``lock_page()``, isolated
335ee65728eSMike Rapoport   from the LRU (if system memory since device private pages are not on
336ee65728eSMike Rapoport   the LRU), unmapped from the process, and a special migration PTE is
337ee65728eSMike Rapoport   inserted in place of the original PTE.
338ee65728eSMike Rapoport   migrate_vma_setup() also clears the ``args->dst`` array.
339ee65728eSMike Rapoport
340ee65728eSMike Rapoport3. The device driver allocates destination pages and copies source pages to
341ee65728eSMike Rapoport   destination pages.
342ee65728eSMike Rapoport
343ee65728eSMike Rapoport   The driver checks each ``src`` entry to see if the ``MIGRATE_PFN_MIGRATE``
344ee65728eSMike Rapoport   bit is set and skips entries that are not migrating. The device driver
345ee65728eSMike Rapoport   can also choose to skip migrating a page by not filling in the ``dst``
346ee65728eSMike Rapoport   array for that page.
347ee65728eSMike Rapoport
348ee65728eSMike Rapoport   The driver then allocates either a device private struct page or a
349ee65728eSMike Rapoport   system memory page, locks the page with ``lock_page()``, and fills in the
350ee65728eSMike Rapoport   ``dst`` array entry with::
351ee65728eSMike Rapoport
352ee65728eSMike Rapoport     dst[i] = migrate_pfn(page_to_pfn(dpage));
353ee65728eSMike Rapoport
354ee65728eSMike Rapoport   Now that the driver knows that this page is being migrated, it can
355ee65728eSMike Rapoport   invalidate device private MMU mappings and copy device private memory
356ee65728eSMike Rapoport   to system memory or another device private page. The core Linux kernel
357ee65728eSMike Rapoport   handles CPU page table invalidations so the device driver only has to
358ee65728eSMike Rapoport   invalidate its own MMU mappings.
359ee65728eSMike Rapoport
360ee65728eSMike Rapoport   The driver can use ``migrate_pfn_to_page(src[i])`` to get the
361ee65728eSMike Rapoport   ``struct page`` of the source and either copy the source page to the
362ee65728eSMike Rapoport   destination or clear the destination device private memory if the pointer
363ee65728eSMike Rapoport   is ``NULL`` meaning the source page was not populated in system memory.
364ee65728eSMike Rapoport
365ee65728eSMike Rapoport4. ``migrate_vma_pages()``
366ee65728eSMike Rapoport
367ee65728eSMike Rapoport   This step is where the migration is actually "committed".
368ee65728eSMike Rapoport
369ee65728eSMike Rapoport   If the source page was a ``pte_none()`` or ``is_zero_pfn()`` page, this
370ee65728eSMike Rapoport   is where the newly allocated page is inserted into the CPU's page table.
371ee65728eSMike Rapoport   This can fail if a CPU thread faults on the same page. However, the page
372ee65728eSMike Rapoport   table is locked and only one of the new pages will be inserted.
373ee65728eSMike Rapoport   The device driver will see that the ``MIGRATE_PFN_MIGRATE`` bit is cleared
374ee65728eSMike Rapoport   if it loses the race.
375ee65728eSMike Rapoport
376ee65728eSMike Rapoport   If the source page was locked, isolated, etc. the source ``struct page``
377ee65728eSMike Rapoport   information is now copied to destination ``struct page`` finalizing the
378ee65728eSMike Rapoport   migration on the CPU side.
379ee65728eSMike Rapoport
380ee65728eSMike Rapoport5. Device driver updates device MMU page tables for pages still migrating,
381ee65728eSMike Rapoport   rolling back pages not migrating.
382ee65728eSMike Rapoport
383ee65728eSMike Rapoport   If the ``src`` entry still has ``MIGRATE_PFN_MIGRATE`` bit set, the device
384ee65728eSMike Rapoport   driver can update the device MMU and set the write enable bit if the
385ee65728eSMike Rapoport   ``MIGRATE_PFN_WRITE`` bit is set.
386ee65728eSMike Rapoport
387ee65728eSMike Rapoport6. ``migrate_vma_finalize()``
388ee65728eSMike Rapoport
389ee65728eSMike Rapoport   This step replaces the special migration page table entry with the new
390ee65728eSMike Rapoport   page's page table entry and releases the reference to the source and
391ee65728eSMike Rapoport   destination ``struct page``.
392ee65728eSMike Rapoport
393ee65728eSMike Rapoport7. ``mmap_read_unlock()``
394ee65728eSMike Rapoport
395ee65728eSMike Rapoport   The lock can now be released.
396ee65728eSMike Rapoport
397ee65728eSMike RapoportExclusive access memory
398ee65728eSMike Rapoport=======================
399ee65728eSMike Rapoport
400ee65728eSMike RapoportSome devices have features such as atomic PTE bits that can be used to implement
401ee65728eSMike Rapoportatomic access to system memory. To support atomic operations to a shared virtual
402ee65728eSMike Rapoportmemory page such a device needs access to that page which is exclusive of any
403ee65728eSMike Rapoportuserspace access from the CPU. The ``make_device_exclusive_range()`` function
404ee65728eSMike Rapoportcan be used to make a memory range inaccessible from userspace.
405ee65728eSMike Rapoport
406ee65728eSMike RapoportThis replaces all mappings for pages in the given range with special swap
407ee65728eSMike Rapoportentries. Any attempt to access the swap entry results in a fault which is
408ee65728eSMike Rapoportresovled by replacing the entry with the original mapping. A driver gets
409ee65728eSMike Rapoportnotified that the mapping has been changed by MMU notifiers, after which point
410ee65728eSMike Rapoportit will no longer have exclusive access to the page. Exclusive access is
411d56b699dSBjorn Helgaasguaranteed to last until the driver drops the page lock and page reference, at
412ee65728eSMike Rapoportwhich point any CPU faults on the page may proceed as described.
413ee65728eSMike Rapoport
414ee65728eSMike RapoportMemory cgroup (memcg) and rss accounting
415ee65728eSMike Rapoport========================================
416ee65728eSMike Rapoport
417ee65728eSMike RapoportFor now, device memory is accounted as any regular page in rss counters (either
418ee65728eSMike Rapoportanonymous if device page is used for anonymous, file if device page is used for
419ee65728eSMike Rapoportfile backed page, or shmem if device page is used for shared memory). This is a
420ee65728eSMike Rapoportdeliberate choice to keep existing applications, that might start using device
421ee65728eSMike Rapoportmemory without knowing about it, running unimpacted.
422ee65728eSMike Rapoport
423ee65728eSMike RapoportA drawback is that the OOM killer might kill an application using a lot of
424ee65728eSMike Rapoportdevice memory and not a lot of regular system memory and thus not freeing much
425ee65728eSMike Rapoportsystem memory. We want to gather more real world experience on how applications
426ee65728eSMike Rapoportand system react under memory pressure in the presence of device memory before
427ee65728eSMike Rapoportdeciding to account device memory differently.
428ee65728eSMike Rapoport
429ee65728eSMike Rapoport
430ee65728eSMike RapoportSame decision was made for memory cgroup. Device memory pages are accounted
431ee65728eSMike Rapoportagainst same memory cgroup a regular page would be accounted to. This does
432ee65728eSMike Rapoportsimplify migration to and from device memory. This also means that migration
433ee65728eSMike Rapoportback from device memory to regular memory cannot fail because it would
434ee65728eSMike Rapoportgo above memory cgroup limit. We might revisit this choice latter on once we
435ee65728eSMike Rapoportget more experience in how device memory is used and its impact on memory
436ee65728eSMike Rapoportresource control.
437ee65728eSMike Rapoport
438ee65728eSMike Rapoport
439ee65728eSMike RapoportNote that device memory can never be pinned by a device driver nor through GUP
440ee65728eSMike Rapoportand thus such memory is always free upon process exit. Or when last reference
441ee65728eSMike Rapoportis dropped in case of shared memory or file backed memory.
442