feac86196a65f55e38dadcf808a3d90d6b0e8d72
[linux-block.git] / mm / hmm.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright 2013 Red Hat Inc.
4  *
5  * Authors: Jérôme Glisse <jglisse@redhat.com>
6  */
7 /*
8  * Refer to include/linux/hmm.h for information about heterogeneous memory
9  * management or HMM for short.
10  */
11 #include <linux/pagewalk.h>
12 #include <linux/hmm.h>
13 #include <linux/hmm-dma.h>
14 #include <linux/init.h>
15 #include <linux/rmap.h>
16 #include <linux/swap.h>
17 #include <linux/slab.h>
18 #include <linux/sched.h>
19 #include <linux/mmzone.h>
20 #include <linux/pagemap.h>
21 #include <linux/swapops.h>
22 #include <linux/hugetlb.h>
23 #include <linux/memremap.h>
24 #include <linux/sched/mm.h>
25 #include <linux/jump_label.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/pci-p2pdma.h>
28 #include <linux/mmu_notifier.h>
29 #include <linux/memory_hotplug.h>
30
31 #include "internal.h"
32
33 struct hmm_vma_walk {
34         struct hmm_range        *range;
35         unsigned long           last;
36 };
37
38 enum {
39         HMM_NEED_FAULT = 1 << 0,
40         HMM_NEED_WRITE_FAULT = 1 << 1,
41         HMM_NEED_ALL_BITS = HMM_NEED_FAULT | HMM_NEED_WRITE_FAULT,
42 };
43
44 enum {
45         /* These flags are carried from input-to-output */
46         HMM_PFN_INOUT_FLAGS = HMM_PFN_DMA_MAPPED | HMM_PFN_P2PDMA |
47                               HMM_PFN_P2PDMA_BUS,
48 };
49
50 static int hmm_pfns_fill(unsigned long addr, unsigned long end,
51                          struct hmm_range *range, unsigned long cpu_flags)
52 {
53         unsigned long i = (addr - range->start) >> PAGE_SHIFT;
54
55         for (; addr < end; addr += PAGE_SIZE, i++) {
56                 range->hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
57                 range->hmm_pfns[i] |= cpu_flags;
58         }
59         return 0;
60 }
61
62 /*
63  * hmm_vma_fault() - fault in a range lacking valid pmd or pte(s)
64  * @addr: range virtual start address (inclusive)
65  * @end: range virtual end address (exclusive)
66  * @required_fault: HMM_NEED_* flags
67  * @walk: mm_walk structure
68  * Return: -EBUSY after page fault, or page fault error
69  *
70  * This function will be called whenever pmd_none() or pte_none() returns true,
71  * or whenever there is no page directory covering the virtual address range.
72  */
73 static int hmm_vma_fault(unsigned long addr, unsigned long end,
74                          unsigned int required_fault, struct mm_walk *walk)
75 {
76         struct hmm_vma_walk *hmm_vma_walk = walk->private;
77         struct vm_area_struct *vma = walk->vma;
78         unsigned int fault_flags = FAULT_FLAG_REMOTE;
79
80         WARN_ON_ONCE(!required_fault);
81         hmm_vma_walk->last = addr;
82
83         if (required_fault & HMM_NEED_WRITE_FAULT) {
84                 if (!(vma->vm_flags & VM_WRITE))
85                         return -EPERM;
86                 fault_flags |= FAULT_FLAG_WRITE;
87         }
88
89         for (; addr < end; addr += PAGE_SIZE)
90                 if (handle_mm_fault(vma, addr, fault_flags, NULL) &
91                     VM_FAULT_ERROR)
92                         return -EFAULT;
93         return -EBUSY;
94 }
95
96 static unsigned int hmm_pte_need_fault(const struct hmm_vma_walk *hmm_vma_walk,
97                                        unsigned long pfn_req_flags,
98                                        unsigned long cpu_flags)
99 {
100         struct hmm_range *range = hmm_vma_walk->range;
101
102         /*
103          * So we not only consider the individual per page request we also
104          * consider the default flags requested for the range. The API can
105          * be used 2 ways. The first one where the HMM user coalesces
106          * multiple page faults into one request and sets flags per pfn for
107          * those faults. The second one where the HMM user wants to pre-
108          * fault a range with specific flags. For the latter one it is a
109          * waste to have the user pre-fill the pfn arrays with a default
110          * flags value.
111          */
112         pfn_req_flags &= range->pfn_flags_mask;
113         pfn_req_flags |= range->default_flags;
114
115         /* We aren't ask to do anything ... */
116         if (!(pfn_req_flags & HMM_PFN_REQ_FAULT))
117                 return 0;
118
119         /* Need to write fault ? */
120         if ((pfn_req_flags & HMM_PFN_REQ_WRITE) &&
121             !(cpu_flags & HMM_PFN_WRITE))
122                 return HMM_NEED_FAULT | HMM_NEED_WRITE_FAULT;
123
124         /* If CPU page table is not valid then we need to fault */
125         if (!(cpu_flags & HMM_PFN_VALID))
126                 return HMM_NEED_FAULT;
127         return 0;
128 }
129
130 static unsigned int
131 hmm_range_need_fault(const struct hmm_vma_walk *hmm_vma_walk,
132                      const unsigned long hmm_pfns[], unsigned long npages,
133                      unsigned long cpu_flags)
134 {
135         struct hmm_range *range = hmm_vma_walk->range;
136         unsigned int required_fault = 0;
137         unsigned long i;
138
139         /*
140          * If the default flags do not request to fault pages, and the mask does
141          * not allow for individual pages to be faulted, then
142          * hmm_pte_need_fault() will always return 0.
143          */
144         if (!((range->default_flags | range->pfn_flags_mask) &
145               HMM_PFN_REQ_FAULT))
146                 return 0;
147
148         for (i = 0; i < npages; ++i) {
149                 required_fault |= hmm_pte_need_fault(hmm_vma_walk, hmm_pfns[i],
150                                                      cpu_flags);
151                 if (required_fault == HMM_NEED_ALL_BITS)
152                         return required_fault;
153         }
154         return required_fault;
155 }
156
157 static int hmm_vma_walk_hole(unsigned long addr, unsigned long end,
158                              __always_unused int depth, struct mm_walk *walk)
159 {
160         struct hmm_vma_walk *hmm_vma_walk = walk->private;
161         struct hmm_range *range = hmm_vma_walk->range;
162         unsigned int required_fault;
163         unsigned long i, npages;
164         unsigned long *hmm_pfns;
165
166         i = (addr - range->start) >> PAGE_SHIFT;
167         npages = (end - addr) >> PAGE_SHIFT;
168         hmm_pfns = &range->hmm_pfns[i];
169         required_fault =
170                 hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0);
171         if (!walk->vma) {
172                 if (required_fault)
173                         return -EFAULT;
174                 return hmm_pfns_fill(addr, end, range, HMM_PFN_ERROR);
175         }
176         if (required_fault)
177                 return hmm_vma_fault(addr, end, required_fault, walk);
178         return hmm_pfns_fill(addr, end, range, 0);
179 }
180
181 static inline unsigned long hmm_pfn_flags_order(unsigned long order)
182 {
183         return order << HMM_PFN_ORDER_SHIFT;
184 }
185
186 static inline unsigned long pmd_to_hmm_pfn_flags(struct hmm_range *range,
187                                                  pmd_t pmd)
188 {
189         if (pmd_protnone(pmd))
190                 return 0;
191         return (pmd_write(pmd) ? (HMM_PFN_VALID | HMM_PFN_WRITE) :
192                                  HMM_PFN_VALID) |
193                hmm_pfn_flags_order(PMD_SHIFT - PAGE_SHIFT);
194 }
195
196 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
197 static int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,
198                               unsigned long end, unsigned long hmm_pfns[],
199                               pmd_t pmd)
200 {
201         struct hmm_vma_walk *hmm_vma_walk = walk->private;
202         struct hmm_range *range = hmm_vma_walk->range;
203         unsigned long pfn, npages, i;
204         unsigned int required_fault;
205         unsigned long cpu_flags;
206
207         npages = (end - addr) >> PAGE_SHIFT;
208         cpu_flags = pmd_to_hmm_pfn_flags(range, pmd);
209         required_fault =
210                 hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, cpu_flags);
211         if (required_fault)
212                 return hmm_vma_fault(addr, end, required_fault, walk);
213
214         pfn = pmd_pfn(pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
215         for (i = 0; addr < end; addr += PAGE_SIZE, i++, pfn++) {
216                 hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
217                 hmm_pfns[i] |= pfn | cpu_flags;
218         }
219         return 0;
220 }
221 #else /* CONFIG_TRANSPARENT_HUGEPAGE */
222 /* stub to allow the code below to compile */
223 int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,
224                 unsigned long end, unsigned long hmm_pfns[], pmd_t pmd);
225 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
226
227 static inline unsigned long pte_to_hmm_pfn_flags(struct hmm_range *range,
228                                                  pte_t pte)
229 {
230         if (pte_none(pte) || !pte_present(pte) || pte_protnone(pte))
231                 return 0;
232         return pte_write(pte) ? (HMM_PFN_VALID | HMM_PFN_WRITE) : HMM_PFN_VALID;
233 }
234
235 static int hmm_vma_handle_pte(struct mm_walk *walk, unsigned long addr,
236                               unsigned long end, pmd_t *pmdp, pte_t *ptep,
237                               unsigned long *hmm_pfn)
238 {
239         struct hmm_vma_walk *hmm_vma_walk = walk->private;
240         struct hmm_range *range = hmm_vma_walk->range;
241         unsigned int required_fault;
242         unsigned long cpu_flags;
243         pte_t pte = ptep_get(ptep);
244         uint64_t pfn_req_flags = *hmm_pfn;
245         uint64_t new_pfn_flags = 0;
246
247         if (pte_none_mostly(pte)) {
248                 required_fault =
249                         hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, 0);
250                 if (required_fault)
251                         goto fault;
252                 goto out;
253         }
254
255         if (!pte_present(pte)) {
256                 swp_entry_t entry = pte_to_swp_entry(pte);
257
258                 /*
259                  * Don't fault in device private pages owned by the caller,
260                  * just report the PFN.
261                  */
262                 if (is_device_private_entry(entry) &&
263                     page_pgmap(pfn_swap_entry_to_page(entry))->owner ==
264                     range->dev_private_owner) {
265                         cpu_flags = HMM_PFN_VALID;
266                         if (is_writable_device_private_entry(entry))
267                                 cpu_flags |= HMM_PFN_WRITE;
268                         new_pfn_flags = swp_offset_pfn(entry) | cpu_flags;
269                         goto out;
270                 }
271
272                 required_fault =
273                         hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, 0);
274                 if (!required_fault)
275                         goto out;
276
277                 if (!non_swap_entry(entry))
278                         goto fault;
279
280                 if (is_device_private_entry(entry))
281                         goto fault;
282
283                 if (is_device_exclusive_entry(entry))
284                         goto fault;
285
286                 if (is_migration_entry(entry)) {
287                         pte_unmap(ptep);
288                         hmm_vma_walk->last = addr;
289                         migration_entry_wait(walk->mm, pmdp, addr);
290                         return -EBUSY;
291                 }
292
293                 /* Report error for everything else */
294                 pte_unmap(ptep);
295                 return -EFAULT;
296         }
297
298         cpu_flags = pte_to_hmm_pfn_flags(range, pte);
299         required_fault =
300                 hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, cpu_flags);
301         if (required_fault)
302                 goto fault;
303
304         /*
305          * Bypass devmap pte such as DAX page when all pfn requested
306          * flags(pfn_req_flags) are fulfilled.
307          * Since each architecture defines a struct page for the zero page, just
308          * fall through and treat it like a normal page.
309          */
310         if (!vm_normal_page(walk->vma, addr, pte) &&
311             !pte_devmap(pte) &&
312             !is_zero_pfn(pte_pfn(pte))) {
313                 if (hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, 0)) {
314                         pte_unmap(ptep);
315                         return -EFAULT;
316                 }
317                 new_pfn_flags = HMM_PFN_ERROR;
318                 goto out;
319         }
320
321         new_pfn_flags = pte_pfn(pte) | cpu_flags;
322 out:
323         *hmm_pfn = (*hmm_pfn & HMM_PFN_INOUT_FLAGS) | new_pfn_flags;
324         return 0;
325
326 fault:
327         pte_unmap(ptep);
328         /* Fault any virtual address we were asked to fault */
329         return hmm_vma_fault(addr, end, required_fault, walk);
330 }
331
332 static int hmm_vma_walk_pmd(pmd_t *pmdp,
333                             unsigned long start,
334                             unsigned long end,
335                             struct mm_walk *walk)
336 {
337         struct hmm_vma_walk *hmm_vma_walk = walk->private;
338         struct hmm_range *range = hmm_vma_walk->range;
339         unsigned long *hmm_pfns =
340                 &range->hmm_pfns[(start - range->start) >> PAGE_SHIFT];
341         unsigned long npages = (end - start) >> PAGE_SHIFT;
342         unsigned long addr = start;
343         pte_t *ptep;
344         pmd_t pmd;
345
346 again:
347         pmd = pmdp_get_lockless(pmdp);
348         if (pmd_none(pmd))
349                 return hmm_vma_walk_hole(start, end, -1, walk);
350
351         if (thp_migration_supported() && is_pmd_migration_entry(pmd)) {
352                 if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0)) {
353                         hmm_vma_walk->last = addr;
354                         pmd_migration_entry_wait(walk->mm, pmdp);
355                         return -EBUSY;
356                 }
357                 return hmm_pfns_fill(start, end, range, 0);
358         }
359
360         if (!pmd_present(pmd)) {
361                 if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0))
362                         return -EFAULT;
363                 return hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
364         }
365
366         if (pmd_devmap(pmd) || pmd_trans_huge(pmd)) {
367                 /*
368                  * No need to take pmd_lock here, even if some other thread
369                  * is splitting the huge pmd we will get that event through
370                  * mmu_notifier callback.
371                  *
372                  * So just read pmd value and check again it's a transparent
373                  * huge or device mapping one and compute corresponding pfn
374                  * values.
375                  */
376                 pmd = pmdp_get_lockless(pmdp);
377                 if (!pmd_devmap(pmd) && !pmd_trans_huge(pmd))
378                         goto again;
379
380                 return hmm_vma_handle_pmd(walk, addr, end, hmm_pfns, pmd);
381         }
382
383         /*
384          * We have handled all the valid cases above ie either none, migration,
385          * huge or transparent huge. At this point either it is a valid pmd
386          * entry pointing to pte directory or it is a bad pmd that will not
387          * recover.
388          */
389         if (pmd_bad(pmd)) {
390                 if (hmm_range_need_fault(hmm_vma_walk, hmm_pfns, npages, 0))
391                         return -EFAULT;
392                 return hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
393         }
394
395         ptep = pte_offset_map(pmdp, addr);
396         if (!ptep)
397                 goto again;
398         for (; addr < end; addr += PAGE_SIZE, ptep++, hmm_pfns++) {
399                 int r;
400
401                 r = hmm_vma_handle_pte(walk, addr, end, pmdp, ptep, hmm_pfns);
402                 if (r) {
403                         /* hmm_vma_handle_pte() did pte_unmap() */
404                         return r;
405                 }
406         }
407         pte_unmap(ptep - 1);
408         return 0;
409 }
410
411 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && \
412     defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
413 static inline unsigned long pud_to_hmm_pfn_flags(struct hmm_range *range,
414                                                  pud_t pud)
415 {
416         if (!pud_present(pud))
417                 return 0;
418         return (pud_write(pud) ? (HMM_PFN_VALID | HMM_PFN_WRITE) :
419                                  HMM_PFN_VALID) |
420                hmm_pfn_flags_order(PUD_SHIFT - PAGE_SHIFT);
421 }
422
423 static int hmm_vma_walk_pud(pud_t *pudp, unsigned long start, unsigned long end,
424                 struct mm_walk *walk)
425 {
426         struct hmm_vma_walk *hmm_vma_walk = walk->private;
427         struct hmm_range *range = hmm_vma_walk->range;
428         unsigned long addr = start;
429         pud_t pud;
430         spinlock_t *ptl = pud_trans_huge_lock(pudp, walk->vma);
431
432         if (!ptl)
433                 return 0;
434
435         /* Normally we don't want to split the huge page */
436         walk->action = ACTION_CONTINUE;
437
438         pud = READ_ONCE(*pudp);
439         if (!pud_present(pud)) {
440                 spin_unlock(ptl);
441                 return hmm_vma_walk_hole(start, end, -1, walk);
442         }
443
444         if (pud_leaf(pud) && pud_devmap(pud)) {
445                 unsigned long i, npages, pfn;
446                 unsigned int required_fault;
447                 unsigned long *hmm_pfns;
448                 unsigned long cpu_flags;
449
450                 i = (addr - range->start) >> PAGE_SHIFT;
451                 npages = (end - addr) >> PAGE_SHIFT;
452                 hmm_pfns = &range->hmm_pfns[i];
453
454                 cpu_flags = pud_to_hmm_pfn_flags(range, pud);
455                 required_fault = hmm_range_need_fault(hmm_vma_walk, hmm_pfns,
456                                                       npages, cpu_flags);
457                 if (required_fault) {
458                         spin_unlock(ptl);
459                         return hmm_vma_fault(addr, end, required_fault, walk);
460                 }
461
462                 pfn = pud_pfn(pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
463                 for (i = 0; i < npages; ++i, ++pfn) {
464                         hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
465                         hmm_pfns[i] |= pfn | cpu_flags;
466                 }
467                 goto out_unlock;
468         }
469
470         /* Ask for the PUD to be split */
471         walk->action = ACTION_SUBTREE;
472
473 out_unlock:
474         spin_unlock(ptl);
475         return 0;
476 }
477 #else
478 #define hmm_vma_walk_pud        NULL
479 #endif
480
481 #ifdef CONFIG_HUGETLB_PAGE
482 static int hmm_vma_walk_hugetlb_entry(pte_t *pte, unsigned long hmask,
483                                       unsigned long start, unsigned long end,
484                                       struct mm_walk *walk)
485 {
486         unsigned long addr = start, i, pfn;
487         struct hmm_vma_walk *hmm_vma_walk = walk->private;
488         struct hmm_range *range = hmm_vma_walk->range;
489         struct vm_area_struct *vma = walk->vma;
490         unsigned int required_fault;
491         unsigned long pfn_req_flags;
492         unsigned long cpu_flags;
493         spinlock_t *ptl;
494         pte_t entry;
495
496         ptl = huge_pte_lock(hstate_vma(vma), walk->mm, pte);
497         entry = huge_ptep_get(walk->mm, addr, pte);
498
499         i = (start - range->start) >> PAGE_SHIFT;
500         pfn_req_flags = range->hmm_pfns[i];
501         cpu_flags = pte_to_hmm_pfn_flags(range, entry) |
502                     hmm_pfn_flags_order(huge_page_order(hstate_vma(vma)));
503         required_fault =
504                 hmm_pte_need_fault(hmm_vma_walk, pfn_req_flags, cpu_flags);
505         if (required_fault) {
506                 int ret;
507
508                 spin_unlock(ptl);
509                 hugetlb_vma_unlock_read(vma);
510                 /*
511                  * Avoid deadlock: drop the vma lock before calling
512                  * hmm_vma_fault(), which will itself potentially take and
513                  * drop the vma lock. This is also correct from a
514                  * protection point of view, because there is no further
515                  * use here of either pte or ptl after dropping the vma
516                  * lock.
517                  */
518                 ret = hmm_vma_fault(addr, end, required_fault, walk);
519                 hugetlb_vma_lock_read(vma);
520                 return ret;
521         }
522
523         pfn = pte_pfn(entry) + ((start & ~hmask) >> PAGE_SHIFT);
524         for (; addr < end; addr += PAGE_SIZE, i++, pfn++) {
525                 range->hmm_pfns[i] &= HMM_PFN_INOUT_FLAGS;
526                 range->hmm_pfns[i] |= pfn | cpu_flags;
527         }
528
529         spin_unlock(ptl);
530         return 0;
531 }
532 #else
533 #define hmm_vma_walk_hugetlb_entry NULL
534 #endif /* CONFIG_HUGETLB_PAGE */
535
536 static int hmm_vma_walk_test(unsigned long start, unsigned long end,
537                              struct mm_walk *walk)
538 {
539         struct hmm_vma_walk *hmm_vma_walk = walk->private;
540         struct hmm_range *range = hmm_vma_walk->range;
541         struct vm_area_struct *vma = walk->vma;
542
543         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)) &&
544             vma->vm_flags & VM_READ)
545                 return 0;
546
547         /*
548          * vma ranges that don't have struct page backing them or map I/O
549          * devices directly cannot be handled by hmm_range_fault().
550          *
551          * If the vma does not allow read access, then assume that it does not
552          * allow write access either. HMM does not support architectures that
553          * allow write without read.
554          *
555          * If a fault is requested for an unsupported range then it is a hard
556          * failure.
557          */
558         if (hmm_range_need_fault(hmm_vma_walk,
559                                  range->hmm_pfns +
560                                          ((start - range->start) >> PAGE_SHIFT),
561                                  (end - start) >> PAGE_SHIFT, 0))
562                 return -EFAULT;
563
564         hmm_pfns_fill(start, end, range, HMM_PFN_ERROR);
565
566         /* Skip this vma and continue processing the next vma. */
567         return 1;
568 }
569
570 static const struct mm_walk_ops hmm_walk_ops = {
571         .pud_entry      = hmm_vma_walk_pud,
572         .pmd_entry      = hmm_vma_walk_pmd,
573         .pte_hole       = hmm_vma_walk_hole,
574         .hugetlb_entry  = hmm_vma_walk_hugetlb_entry,
575         .test_walk      = hmm_vma_walk_test,
576         .walk_lock      = PGWALK_RDLOCK,
577 };
578
579 /**
580  * hmm_range_fault - try to fault some address in a virtual address range
581  * @range:      argument structure
582  *
583  * Returns 0 on success or one of the following error codes:
584  *
585  * -EINVAL:     Invalid arguments or mm or virtual address is in an invalid vma
586  *              (e.g., device file vma).
587  * -ENOMEM:     Out of memory.
588  * -EPERM:      Invalid permission (e.g., asking for write and range is read
589  *              only).
590  * -EBUSY:      The range has been invalidated and the caller needs to wait for
591  *              the invalidation to finish.
592  * -EFAULT:     A page was requested to be valid and could not be made valid
593  *              ie it has no backing VMA or it is illegal to access
594  *
595  * This is similar to get_user_pages(), except that it can read the page tables
596  * without mutating them (ie causing faults).
597  */
598 int hmm_range_fault(struct hmm_range *range)
599 {
600         struct hmm_vma_walk hmm_vma_walk = {
601                 .range = range,
602                 .last = range->start,
603         };
604         struct mm_struct *mm = range->notifier->mm;
605         int ret;
606
607         mmap_assert_locked(mm);
608
609         do {
610                 /* If range is no longer valid force retry. */
611                 if (mmu_interval_check_retry(range->notifier,
612                                              range->notifier_seq))
613                         return -EBUSY;
614                 ret = walk_page_range(mm, hmm_vma_walk.last, range->end,
615                                       &hmm_walk_ops, &hmm_vma_walk);
616                 /*
617                  * When -EBUSY is returned the loop restarts with
618                  * hmm_vma_walk.last set to an address that has not been stored
619                  * in pfns. All entries < last in the pfn array are set to their
620                  * output, and all >= are still at their input values.
621                  */
622         } while (ret == -EBUSY);
623         return ret;
624 }
625 EXPORT_SYMBOL(hmm_range_fault);
626
627 /**
628  * hmm_dma_map_alloc - Allocate HMM map structure
629  * @dev: device to allocate structure for
630  * @map: HMM map to allocate
631  * @nr_entries: number of entries in the map
632  * @dma_entry_size: size of the DMA entry in the map
633  *
634  * Allocate the HMM map structure and all the lists it contains.
635  * Return 0 on success, -ENOMEM on failure.
636  */
637 int hmm_dma_map_alloc(struct device *dev, struct hmm_dma_map *map,
638                       size_t nr_entries, size_t dma_entry_size)
639 {
640         bool dma_need_sync = false;
641         bool use_iova;
642
643         WARN_ON_ONCE(!(nr_entries * PAGE_SIZE / dma_entry_size));
644
645         /*
646          * The HMM API violates our normal DMA buffer ownership rules and can't
647          * transfer buffer ownership.  The dma_addressing_limited() check is a
648          * best approximation to ensure no swiotlb buffering happens.
649          */
650 #ifdef CONFIG_DMA_NEED_SYNC
651         dma_need_sync = !dev->dma_skip_sync;
652 #endif /* CONFIG_DMA_NEED_SYNC */
653         if (dma_need_sync || dma_addressing_limited(dev))
654                 return -EOPNOTSUPP;
655
656         map->dma_entry_size = dma_entry_size;
657         map->pfn_list = kvcalloc(nr_entries, sizeof(*map->pfn_list),
658                                  GFP_KERNEL | __GFP_NOWARN);
659         if (!map->pfn_list)
660                 return -ENOMEM;
661
662         use_iova = dma_iova_try_alloc(dev, &map->state, 0,
663                         nr_entries * PAGE_SIZE);
664         if (!use_iova && dma_need_unmap(dev)) {
665                 map->dma_list = kvcalloc(nr_entries, sizeof(*map->dma_list),
666                                          GFP_KERNEL | __GFP_NOWARN);
667                 if (!map->dma_list)
668                         goto err_dma;
669         }
670         return 0;
671
672 err_dma:
673         kvfree(map->pfn_list);
674         return -ENOMEM;
675 }
676 EXPORT_SYMBOL_GPL(hmm_dma_map_alloc);
677
678 /**
679  * hmm_dma_map_free - iFree HMM map structure
680  * @dev: device to free structure from
681  * @map: HMM map containing the various lists and state
682  *
683  * Free the HMM map structure and all the lists it contains.
684  */
685 void hmm_dma_map_free(struct device *dev, struct hmm_dma_map *map)
686 {
687         if (dma_use_iova(&map->state))
688                 dma_iova_free(dev, &map->state);
689         kvfree(map->pfn_list);
690         kvfree(map->dma_list);
691 }
692 EXPORT_SYMBOL_GPL(hmm_dma_map_free);
693
694 /**
695  * hmm_dma_map_pfn - Map a physical HMM page to DMA address
696  * @dev: Device to map the page for
697  * @map: HMM map
698  * @idx: Index into the PFN and dma address arrays
699  * @p2pdma_state: PCI P2P state.
700  *
701  * dma_alloc_iova() allocates IOVA based on the size specified by their use in
702  * iova->size. Call this function after IOVA allocation to link whole @page
703  * to get the DMA address. Note that very first call to this function
704  * will have @offset set to 0 in the IOVA space allocated from
705  * dma_alloc_iova(). For subsequent calls to this function on same @iova,
706  * @offset needs to be advanced by the caller with the size of previous
707  * page that was linked + DMA address returned for the previous page that was
708  * linked by this function.
709  */
710 dma_addr_t hmm_dma_map_pfn(struct device *dev, struct hmm_dma_map *map,
711                            size_t idx,
712                            struct pci_p2pdma_map_state *p2pdma_state)
713 {
714         struct dma_iova_state *state = &map->state;
715         dma_addr_t *dma_addrs = map->dma_list;
716         unsigned long *pfns = map->pfn_list;
717         struct page *page = hmm_pfn_to_page(pfns[idx]);
718         phys_addr_t paddr = hmm_pfn_to_phys(pfns[idx]);
719         size_t offset = idx * map->dma_entry_size;
720         unsigned long attrs = 0;
721         dma_addr_t dma_addr;
722         int ret;
723
724         if ((pfns[idx] & HMM_PFN_DMA_MAPPED) &&
725             !(pfns[idx] & HMM_PFN_P2PDMA_BUS)) {
726                 /*
727                  * We are in this flow when there is a need to resync flags,
728                  * for example when page was already linked in prefetch call
729                  * with READ flag and now we need to add WRITE flag
730                  *
731                  * This page was already programmed to HW and we don't want/need
732                  * to unlink and link it again just to resync flags.
733                  */
734                 if (dma_use_iova(state))
735                         return state->addr + offset;
736
737                 /*
738                  * Without dma_need_unmap, the dma_addrs array is NULL, thus we
739                  * need to regenerate the address below even if there already
740                  * was a mapping. But !dma_need_unmap implies that the
741                  * mapping stateless, so this is fine.
742                  */
743                 if (dma_need_unmap(dev))
744                         return dma_addrs[idx];
745
746                 /* Continue to remapping */
747         }
748
749         switch (pci_p2pdma_state(p2pdma_state, dev, page)) {
750         case PCI_P2PDMA_MAP_NONE:
751                 break;
752         case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
753                 attrs |= DMA_ATTR_SKIP_CPU_SYNC;
754                 pfns[idx] |= HMM_PFN_P2PDMA;
755                 break;
756         case PCI_P2PDMA_MAP_BUS_ADDR:
757                 pfns[idx] |= HMM_PFN_P2PDMA_BUS | HMM_PFN_DMA_MAPPED;
758                 return pci_p2pdma_bus_addr_map(p2pdma_state, paddr);
759         default:
760                 return DMA_MAPPING_ERROR;
761         }
762
763         if (dma_use_iova(state)) {
764                 ret = dma_iova_link(dev, state, paddr, offset,
765                                     map->dma_entry_size, DMA_BIDIRECTIONAL,
766                                     attrs);
767                 if (ret)
768                         goto error;
769
770                 ret = dma_iova_sync(dev, state, offset, map->dma_entry_size);
771                 if (ret) {
772                         dma_iova_unlink(dev, state, offset, map->dma_entry_size,
773                                         DMA_BIDIRECTIONAL, attrs);
774                         goto error;
775                 }
776
777                 dma_addr = state->addr + offset;
778         } else {
779                 if (WARN_ON_ONCE(dma_need_unmap(dev) && !dma_addrs))
780                         goto error;
781
782                 dma_addr = dma_map_page(dev, page, 0, map->dma_entry_size,
783                                         DMA_BIDIRECTIONAL);
784                 if (dma_mapping_error(dev, dma_addr))
785                         goto error;
786
787                 if (dma_need_unmap(dev))
788                         dma_addrs[idx] = dma_addr;
789         }
790         pfns[idx] |= HMM_PFN_DMA_MAPPED;
791         return dma_addr;
792 error:
793         pfns[idx] &= ~HMM_PFN_P2PDMA;
794         return DMA_MAPPING_ERROR;
795
796 }
797 EXPORT_SYMBOL_GPL(hmm_dma_map_pfn);
798
799 /**
800  * hmm_dma_unmap_pfn - Unmap a physical HMM page from DMA address
801  * @dev: Device to unmap the page from
802  * @map: HMM map
803  * @idx: Index of the PFN to unmap
804  *
805  * Returns true if the PFN was mapped and has been unmapped, false otherwise.
806  */
807 bool hmm_dma_unmap_pfn(struct device *dev, struct hmm_dma_map *map, size_t idx)
808 {
809         const unsigned long valid_dma = HMM_PFN_VALID | HMM_PFN_DMA_MAPPED;
810         struct dma_iova_state *state = &map->state;
811         dma_addr_t *dma_addrs = map->dma_list;
812         unsigned long *pfns = map->pfn_list;
813         unsigned long attrs = 0;
814
815         if ((pfns[idx] & valid_dma) != valid_dma)
816                 return false;
817
818         if (pfns[idx] & HMM_PFN_P2PDMA_BUS)
819                 ; /* no need to unmap bus address P2P mappings */
820         else if (dma_use_iova(state)) {
821                 if (pfns[idx] & HMM_PFN_P2PDMA)
822                         attrs |= DMA_ATTR_SKIP_CPU_SYNC;
823                 dma_iova_unlink(dev, state, idx * map->dma_entry_size,
824                                 map->dma_entry_size, DMA_BIDIRECTIONAL, attrs);
825         } else if (dma_need_unmap(dev))
826                 dma_unmap_page(dev, dma_addrs[idx], map->dma_entry_size,
827                                DMA_BIDIRECTIONAL);
828
829         pfns[idx] &=
830                 ~(HMM_PFN_DMA_MAPPED | HMM_PFN_P2PDMA | HMM_PFN_P2PDMA_BUS);
831         return true;
832 }
833 EXPORT_SYMBOL_GPL(hmm_dma_unmap_pfn);