Back to home page

OSCL-LXR

 
 

    


0001 .. _hmm:
0002 
0003 =====================================
0004 Heterogeneous Memory Management (HMM)
0005 =====================================
0006 
0007 Provide infrastructure and helpers to integrate non-conventional memory (device
0008 memory like GPU on board memory) into regular kernel path, with the cornerstone
0009 of this being specialized struct page for such memory (see sections 5 to 7 of
0010 this document).
0011 
0012 HMM also provides optional helpers for SVM (Share Virtual Memory), i.e.,
0013 allowing a device to transparently access program addresses coherently with
0014 the CPU meaning that any valid pointer on the CPU is also a valid pointer
0015 for the device. This is becoming mandatory to simplify the use of advanced
0016 heterogeneous computing where GPU, DSP, or FPGA are used to perform various
0017 computations on behalf of a process.
0018 
0019 This document is divided as follows: in the first section I expose the problems
0020 related to using device specific memory allocators. In the second section, I
0021 expose the hardware limitations that are inherent to many platforms. The third
0022 section gives an overview of the HMM design. The fourth section explains how
0023 CPU page-table mirroring works and the purpose of HMM in this context. The
0024 fifth section deals with how device memory is represented inside the kernel.
0025 Finally, the last section presents a new migration helper that allows
0026 leveraging the device DMA engine.
0027 
0028 .. contents:: :local:
0029 
0030 Problems of using a device specific memory allocator
0031 ====================================================
0032 
0033 Devices with a large amount of on board memory (several gigabytes) like GPUs
0034 have historically managed their memory through dedicated driver specific APIs.
0035 This creates a disconnect between memory allocated and managed by a device
0036 driver and regular application memory (private anonymous, shared memory, or
0037 regular file backed memory). From here on I will refer to this aspect as split
0038 address space. I use shared address space to refer to the opposite situation:
0039 i.e., one in which any application memory region can be used by a device
0040 transparently.
0041 
0042 Split address space happens because devices can only access memory allocated
0043 through a device specific API. This implies that all memory objects in a program
0044 are not equal from the device point of view which complicates large programs
0045 that rely on a wide set of libraries.
0046 
0047 Concretely, this means that code that wants to leverage devices like GPUs needs
0048 to copy objects between generically allocated memory (malloc, mmap private, mmap
0049 share) and memory allocated through the device driver API (this still ends up
0050 with an mmap but of the device file).
0051 
0052 For flat data sets (array, grid, image, ...) this isn't too hard to achieve but
0053 for complex data sets (list, tree, ...) it's hard to get right. Duplicating a
0054 complex data set needs to re-map all the pointer relations between each of its
0055 elements. This is error prone and programs get harder to debug because of the
0056 duplicate data set and addresses.
0057 
0058 Split address space also means that libraries cannot transparently use data
0059 they are getting from the core program or another library and thus each library
0060 might have to duplicate its input data set using the device specific memory
0061 allocator. Large projects suffer from this and waste resources because of the
0062 various memory copies.
0063 
0064 Duplicating each library API to accept as input or output memory allocated by
0065 each device specific allocator is not a viable option. It would lead to a
0066 combinatorial explosion in the library entry points.
0067 
0068 Finally, with the advance of high level language constructs (in C++ but in
0069 other languages too) it is now possible for the compiler to leverage GPUs and
0070 other devices without programmer knowledge. Some compiler identified patterns
0071 are only do-able with a shared address space. It is also more reasonable to use
0072 a shared address space for all other patterns.
0073 
0074 
0075 I/O bus, device memory characteristics
0076 ======================================
0077 
0078 I/O buses cripple shared address spaces due to a few limitations. Most I/O
0079 buses only allow basic memory access from device to main memory; even cache
0080 coherency is often optional. Access to device memory from a CPU is even more
0081 limited. More often than not, it is not cache coherent.
0082 
0083 If we only consider the PCIE bus, then a device can access main memory (often
0084 through an IOMMU) and be cache coherent with the CPUs. However, it only allows
0085 a limited set of atomic operations from the device on main memory. This is worse
0086 in the other direction: the CPU can only access a limited range of the device
0087 memory and cannot perform atomic operations on it. Thus device memory cannot
0088 be considered the same as regular memory from the kernel point of view.
0089 
0090 Another crippling factor is the limited bandwidth (~32GBytes/s with PCIE 4.0
0091 and 16 lanes). This is 33 times less than the fastest GPU memory (1 TBytes/s).
0092 The final limitation is latency. Access to main memory from the device has an
0093 order of magnitude higher latency than when the device accesses its own memory.
0094 
0095 Some platforms are developing new I/O buses or additions/modifications to PCIE
0096 to address some of these limitations (OpenCAPI, CCIX). They mainly allow
0097 two-way cache coherency between CPU and device and allow all atomic operations the
0098 architecture supports. Sadly, not all platforms are following this trend and
0099 some major architectures are left without hardware solutions to these problems.
0100 
0101 So for shared address space to make sense, not only must we allow devices to
0102 access any memory but we must also permit any memory to be migrated to device
0103 memory while the device is using it (blocking CPU access while it happens).
0104 
0105 
0106 Shared address space and migration
0107 ==================================
0108 
0109 HMM intends to provide two main features. The first one is to share the address
0110 space by duplicating the CPU page table in the device page table so the same
0111 address points to the same physical memory for any valid main memory address in
0112 the process address space.
0113 
0114 To achieve this, HMM offers a set of helpers to populate the device page table
0115 while keeping track of CPU page table updates. Device page table updates are
0116 not as easy as CPU page table updates. To update the device page table, you must
0117 allocate a buffer (or use a pool of pre-allocated buffers) and write GPU
0118 specific commands in it to perform the update (unmap, cache invalidations, and
0119 flush, ...). This cannot be done through common code for all devices. Hence
0120 why HMM provides helpers to factor out everything that can be while leaving the
0121 hardware specific details to the device driver.
0122 
0123 The second mechanism HMM provides is a new kind of ZONE_DEVICE memory that
0124 allows allocating a struct page for each page of device memory. Those pages
0125 are special because the CPU cannot map them. However, they allow migrating
0126 main memory to device memory using existing migration mechanisms and everything
0127 looks like a page that is swapped out to disk from the CPU point of view. Using a
0128 struct page gives the easiest and cleanest integration with existing mm
0129 mechanisms. Here again, HMM only provides helpers, first to hotplug new ZONE_DEVICE
0130 memory for the device memory and second to perform migration. Policy decisions
0131 of what and when to migrate is left to the device driver.
0132 
0133 Note that any CPU access to a device page triggers a page fault and a migration
0134 back to main memory. For example, when a page backing a given CPU address A is
0135 migrated from a main memory page to a device page, then any CPU access to
0136 address A triggers a page fault and initiates a migration back to main memory.
0137 
0138 With these two features, HMM not only allows a device to mirror process address
0139 space and keeps both CPU and device page tables synchronized, but also
0140 leverages device memory by migrating the part of the data set that is actively being
0141 used by the device.
0142 
0143 
0144 Address space mirroring implementation and API
0145 ==============================================
0146 
0147 Address space mirroring's main objective is to allow duplication of a range of
0148 CPU page table into a device page table; HMM helps keep both synchronized. A
0149 device driver that wants to mirror a process address space must start with the
0150 registration of a mmu_interval_notifier::
0151 
0152  int mmu_interval_notifier_insert(struct mmu_interval_notifier *interval_sub,
0153                                   struct mm_struct *mm, unsigned long start,
0154                                   unsigned long length,
0155                                   const struct mmu_interval_notifier_ops *ops);
0156 
0157 During the ops->invalidate() callback the device driver must perform the
0158 update action to the range (mark range read only, or fully unmap, etc.). The
0159 device must complete the update before the driver callback returns.
0160 
0161 When the device driver wants to populate a range of virtual addresses, it can
0162 use::
0163 
0164   int hmm_range_fault(struct hmm_range *range);
0165 
0166 It will trigger a page fault on missing or read-only entries if write access is
0167 requested (see below). Page faults use the generic mm page fault code path just
0168 like a CPU page fault.
0169 
0170 Both functions copy CPU page table entries into their pfns array argument. Each
0171 entry in that array corresponds to an address in the virtual range. HMM
0172 provides a set of flags to help the driver identify special CPU page table
0173 entries.
0174 
0175 Locking within the sync_cpu_device_pagetables() callback is the most important
0176 aspect the driver must respect in order to keep things properly synchronized.
0177 The usage pattern is::
0178 
0179  int driver_populate_range(...)
0180  {
0181       struct hmm_range range;
0182       ...
0183 
0184       range.notifier = &interval_sub;
0185       range.start = ...;
0186       range.end = ...;
0187       range.hmm_pfns = ...;
0188 
0189       if (!mmget_not_zero(interval_sub->notifier.mm))
0190           return -EFAULT;
0191 
0192  again:
0193       range.notifier_seq = mmu_interval_read_begin(&interval_sub);
0194       mmap_read_lock(mm);
0195       ret = hmm_range_fault(&range);
0196       if (ret) {
0197           mmap_read_unlock(mm);
0198           if (ret == -EBUSY)
0199                  goto again;
0200           return ret;
0201       }
0202       mmap_read_unlock(mm);
0203 
0204       take_lock(driver->update);
0205       if (mmu_interval_read_retry(&ni, range.notifier_seq) {
0206           release_lock(driver->update);
0207           goto again;
0208       }
0209 
0210       /* Use pfns array content to update device page table,
0211        * under the update lock */
0212 
0213       release_lock(driver->update);
0214       return 0;
0215  }
0216 
0217 The driver->update lock is the same lock that the driver takes inside its
0218 invalidate() callback. That lock must be held before calling
0219 mmu_interval_read_retry() to avoid any race with a concurrent CPU page table
0220 update.
0221 
0222 Leverage default_flags and pfn_flags_mask
0223 =========================================
0224 
0225 The hmm_range struct has 2 fields, default_flags and pfn_flags_mask, that specify
0226 fault or snapshot policy for the whole range instead of having to set them
0227 for each entry in the pfns array.
0228 
0229 For instance if the device driver wants pages for a range with at least read
0230 permission, it sets::
0231 
0232     range->default_flags = HMM_PFN_REQ_FAULT;
0233     range->pfn_flags_mask = 0;
0234 
0235 and calls hmm_range_fault() as described above. This will fill fault all pages
0236 in the range with at least read permission.
0237 
0238 Now let's say the driver wants to do the same except for one page in the range for
0239 which it wants to have write permission. Now driver set::
0240 
0241     range->default_flags = HMM_PFN_REQ_FAULT;
0242     range->pfn_flags_mask = HMM_PFN_REQ_WRITE;
0243     range->pfns[index_of_write] = HMM_PFN_REQ_WRITE;
0244 
0245 With this, HMM will fault in all pages with at least read (i.e., valid) and for the
0246 address == range->start + (index_of_write << PAGE_SHIFT) it will fault with
0247 write permission i.e., if the CPU pte does not have write permission set then HMM
0248 will call handle_mm_fault().
0249 
0250 After hmm_range_fault completes the flag bits are set to the current state of
0251 the page tables, ie HMM_PFN_VALID | HMM_PFN_WRITE will be set if the page is
0252 writable.
0253 
0254 
0255 Represent and manage device memory from core kernel point of view
0256 =================================================================
0257 
0258 Several different designs were tried to support device memory. The first one
0259 used a device specific data structure to keep information about migrated memory
0260 and HMM hooked itself in various places of mm code to handle any access to
0261 addresses that were backed by device memory. It turns out that this ended up
0262 replicating most of the fields of struct page and also needed many kernel code
0263 paths to be updated to understand this new kind of memory.
0264 
0265 Most kernel code paths never try to access the memory behind a page
0266 but only care about struct page contents. Because of this, HMM switched to
0267 directly using struct page for device memory which left most kernel code paths
0268 unaware of the difference. We only need to make sure that no one ever tries to
0269 map those pages from the CPU side.
0270 
0271 Migration to and from device memory
0272 ===================================
0273 
0274 Because the CPU cannot access device memory directly, the device driver must
0275 use hardware DMA or device specific load/store instructions to migrate data.
0276 The migrate_vma_setup(), migrate_vma_pages(), and migrate_vma_finalize()
0277 functions are designed to make drivers easier to write and to centralize common
0278 code across drivers.
0279 
0280 Before migrating pages to device private memory, special device private
0281 ``struct page`` need to be created. These will be used as special "swap"
0282 page table entries so that a CPU process will fault if it tries to access
0283 a page that has been migrated to device private memory.
0284 
0285 These can be allocated and freed with::
0286 
0287     struct resource *res;
0288     struct dev_pagemap pagemap;
0289 
0290     res = request_free_mem_region(&iomem_resource, /* number of bytes */,
0291                                   "name of driver resource");
0292     pagemap.type = MEMORY_DEVICE_PRIVATE;
0293     pagemap.range.start = res->start;
0294     pagemap.range.end = res->end;
0295     pagemap.nr_range = 1;
0296     pagemap.ops = &device_devmem_ops;
0297     memremap_pages(&pagemap, numa_node_id());
0298 
0299     memunmap_pages(&pagemap);
0300     release_mem_region(pagemap.range.start, range_len(&pagemap.range));
0301 
0302 There are also devm_request_free_mem_region(), devm_memremap_pages(),
0303 devm_memunmap_pages(), and devm_release_mem_region() when the resources can
0304 be tied to a ``struct device``.
0305 
0306 The overall migration steps are similar to migrating NUMA pages within system
0307 memory (see :ref:`Page migration <page_migration>`) but the steps are split
0308 between device driver specific code and shared common code:
0309 
0310 1. ``mmap_read_lock()``
0311 
0312    The device driver has to pass a ``struct vm_area_struct`` to
0313    migrate_vma_setup() so the mmap_read_lock() or mmap_write_lock() needs to
0314    be held for the duration of the migration.
0315 
0316 2. ``migrate_vma_setup(struct migrate_vma *args)``
0317 
0318    The device driver initializes the ``struct migrate_vma`` fields and passes
0319    the pointer to migrate_vma_setup(). The ``args->flags`` field is used to
0320    filter which source pages should be migrated. For example, setting
0321    ``MIGRATE_VMA_SELECT_SYSTEM`` will only migrate system memory and
0322    ``MIGRATE_VMA_SELECT_DEVICE_PRIVATE`` will only migrate pages residing in
0323    device private memory. If the latter flag is set, the ``args->pgmap_owner``
0324    field is used to identify device private pages owned by the driver. This
0325    avoids trying to migrate device private pages residing in other devices.
0326    Currently only anonymous private VMA ranges can be migrated to or from
0327    system memory and device private memory.
0328 
0329    One of the first steps migrate_vma_setup() does is to invalidate other
0330    device's MMUs with the ``mmu_notifier_invalidate_range_start(()`` and
0331    ``mmu_notifier_invalidate_range_end()`` calls around the page table
0332    walks to fill in the ``args->src`` array with PFNs to be migrated.
0333    The ``invalidate_range_start()`` callback is passed a
0334    ``struct mmu_notifier_range`` with the ``event`` field set to
0335    ``MMU_NOTIFY_MIGRATE`` and the ``owner`` field set to
0336    the ``args->pgmap_owner`` field passed to migrate_vma_setup(). This is
0337    allows the device driver to skip the invalidation callback and only
0338    invalidate device private MMU mappings that are actually migrating.
0339    This is explained more in the next section.
0340 
0341    While walking the page tables, a ``pte_none()`` or ``is_zero_pfn()``
0342    entry results in a valid "zero" PFN stored in the ``args->src`` array.
0343    This lets the driver allocate device private memory and clear it instead
0344    of copying a page of zeros. Valid PTE entries to system memory or
0345    device private struct pages will be locked with ``lock_page()``, isolated
0346    from the LRU (if system memory since device private pages are not on
0347    the LRU), unmapped from the process, and a special migration PTE is
0348    inserted in place of the original PTE.
0349    migrate_vma_setup() also clears the ``args->dst`` array.
0350 
0351 3. The device driver allocates destination pages and copies source pages to
0352    destination pages.
0353 
0354    The driver checks each ``src`` entry to see if the ``MIGRATE_PFN_MIGRATE``
0355    bit is set and skips entries that are not migrating. The device driver
0356    can also choose to skip migrating a page by not filling in the ``dst``
0357    array for that page.
0358 
0359    The driver then allocates either a device private struct page or a
0360    system memory page, locks the page with ``lock_page()``, and fills in the
0361    ``dst`` array entry with::
0362 
0363      dst[i] = migrate_pfn(page_to_pfn(dpage));
0364 
0365    Now that the driver knows that this page is being migrated, it can
0366    invalidate device private MMU mappings and copy device private memory
0367    to system memory or another device private page. The core Linux kernel
0368    handles CPU page table invalidations so the device driver only has to
0369    invalidate its own MMU mappings.
0370 
0371    The driver can use ``migrate_pfn_to_page(src[i])`` to get the
0372    ``struct page`` of the source and either copy the source page to the
0373    destination or clear the destination device private memory if the pointer
0374    is ``NULL`` meaning the source page was not populated in system memory.
0375 
0376 4. ``migrate_vma_pages()``
0377 
0378    This step is where the migration is actually "committed".
0379 
0380    If the source page was a ``pte_none()`` or ``is_zero_pfn()`` page, this
0381    is where the newly allocated page is inserted into the CPU's page table.
0382    This can fail if a CPU thread faults on the same page. However, the page
0383    table is locked and only one of the new pages will be inserted.
0384    The device driver will see that the ``MIGRATE_PFN_MIGRATE`` bit is cleared
0385    if it loses the race.
0386 
0387    If the source page was locked, isolated, etc. the source ``struct page``
0388    information is now copied to destination ``struct page`` finalizing the
0389    migration on the CPU side.
0390 
0391 5. Device driver updates device MMU page tables for pages still migrating,
0392    rolling back pages not migrating.
0393 
0394    If the ``src`` entry still has ``MIGRATE_PFN_MIGRATE`` bit set, the device
0395    driver can update the device MMU and set the write enable bit if the
0396    ``MIGRATE_PFN_WRITE`` bit is set.
0397 
0398 6. ``migrate_vma_finalize()``
0399 
0400    This step replaces the special migration page table entry with the new
0401    page's page table entry and releases the reference to the source and
0402    destination ``struct page``.
0403 
0404 7. ``mmap_read_unlock()``
0405 
0406    The lock can now be released.
0407 
0408 Exclusive access memory
0409 =======================
0410 
0411 Some devices have features such as atomic PTE bits that can be used to implement
0412 atomic access to system memory. To support atomic operations to a shared virtual
0413 memory page such a device needs access to that page which is exclusive of any
0414 userspace access from the CPU. The ``make_device_exclusive_range()`` function
0415 can be used to make a memory range inaccessible from userspace.
0416 
0417 This replaces all mappings for pages in the given range with special swap
0418 entries. Any attempt to access the swap entry results in a fault which is
0419 resovled by replacing the entry with the original mapping. A driver gets
0420 notified that the mapping has been changed by MMU notifiers, after which point
0421 it will no longer have exclusive access to the page. Exclusive access is
0422 guranteed to last until the driver drops the page lock and page reference, at
0423 which point any CPU faults on the page may proceed as described.
0424 
0425 Memory cgroup (memcg) and rss accounting
0426 ========================================
0427 
0428 For now, device memory is accounted as any regular page in rss counters (either
0429 anonymous if device page is used for anonymous, file if device page is used for
0430 file backed page, or shmem if device page is used for shared memory). This is a
0431 deliberate choice to keep existing applications, that might start using device
0432 memory without knowing about it, running unimpacted.
0433 
0434 A drawback is that the OOM killer might kill an application using a lot of
0435 device memory and not a lot of regular system memory and thus not freeing much
0436 system memory. We want to gather more real world experience on how applications
0437 and system react under memory pressure in the presence of device memory before
0438 deciding to account device memory differently.
0439 
0440 
0441 Same decision was made for memory cgroup. Device memory pages are accounted
0442 against same memory cgroup a regular page would be accounted to. This does
0443 simplify migration to and from device memory. This also means that migration
0444 back from device memory to regular memory cannot fail because it would
0445 go above memory cgroup limit. We might revisit this choice latter on once we
0446 get more experience in how device memory is used and its impact on memory
0447 resource control.
0448 
0449 
0450 Note that device memory can never be pinned by a device driver nor through GUP
0451 and thus such memory is always free upon process exit. Or when last reference
0452 is dropped in case of shared memory or file backed memory.