lib: test_hmm add ioctl to get zone device type
[linux.git] / lib / test_hmm.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This is a module to test the HMM (Heterogeneous Memory Management)
4  * mirror and zone device private memory migration APIs of the kernel.
5  * Userspace programs can register with the driver to mirror their own address
6  * space and can use the device to read/write any valid virtual address.
7  */
8 #include <linux/init.h>
9 #include <linux/fs.h>
10 #include <linux/mm.h>
11 #include <linux/module.h>
12 #include <linux/kernel.h>
13 #include <linux/cdev.h>
14 #include <linux/device.h>
15 #include <linux/memremap.h>
16 #include <linux/mutex.h>
17 #include <linux/rwsem.h>
18 #include <linux/sched.h>
19 #include <linux/slab.h>
20 #include <linux/highmem.h>
21 #include <linux/delay.h>
22 #include <linux/pagemap.h>
23 #include <linux/hmm.h>
24 #include <linux/vmalloc.h>
25 #include <linux/swap.h>
26 #include <linux/swapops.h>
27 #include <linux/sched/mm.h>
28 #include <linux/platform_device.h>
29 #include <linux/rmap.h>
30 #include <linux/mmu_notifier.h>
31 #include <linux/migrate.h>
32
33 #include "test_hmm_uapi.h"
34
35 #define DMIRROR_NDEVICES                2
36 #define DMIRROR_RANGE_FAULT_TIMEOUT     1000
37 #define DEVMEM_CHUNK_SIZE               (256 * 1024 * 1024U)
38 #define DEVMEM_CHUNKS_RESERVE           16
39
40 static const struct dev_pagemap_ops dmirror_devmem_ops;
41 static const struct mmu_interval_notifier_ops dmirror_min_ops;
42 static dev_t dmirror_dev;
43
44 struct dmirror_device;
45
46 struct dmirror_bounce {
47         void                    *ptr;
48         unsigned long           size;
49         unsigned long           addr;
50         unsigned long           cpages;
51 };
52
53 #define DPT_XA_TAG_ATOMIC 1UL
54 #define DPT_XA_TAG_WRITE 3UL
55
56 /*
57  * Data structure to track address ranges and register for mmu interval
58  * notifier updates.
59  */
60 struct dmirror_interval {
61         struct mmu_interval_notifier    notifier;
62         struct dmirror                  *dmirror;
63 };
64
65 /*
66  * Data attached to the open device file.
67  * Note that it might be shared after a fork().
68  */
69 struct dmirror {
70         struct dmirror_device           *mdevice;
71         struct xarray                   pt;
72         struct mmu_interval_notifier    notifier;
73         struct mutex                    mutex;
74 };
75
76 /*
77  * ZONE_DEVICE pages for migration and simulating device memory.
78  */
79 struct dmirror_chunk {
80         struct dev_pagemap      pagemap;
81         struct dmirror_device   *mdevice;
82 };
83
84 /*
85  * Per device data.
86  */
87 struct dmirror_device {
88         struct cdev             cdevice;
89         struct hmm_devmem       *devmem;
90         unsigned int            zone_device_type;
91
92         unsigned int            devmem_capacity;
93         unsigned int            devmem_count;
94         struct dmirror_chunk    **devmem_chunks;
95         struct mutex            devmem_lock;    /* protects the above */
96
97         unsigned long           calloc;
98         unsigned long           cfree;
99         struct page             *free_pages;
100         spinlock_t              lock;           /* protects the above */
101 };
102
103 static struct dmirror_device dmirror_devices[DMIRROR_NDEVICES];
104
105 static int dmirror_bounce_init(struct dmirror_bounce *bounce,
106                                unsigned long addr,
107                                unsigned long size)
108 {
109         bounce->addr = addr;
110         bounce->size = size;
111         bounce->cpages = 0;
112         bounce->ptr = vmalloc(size);
113         if (!bounce->ptr)
114                 return -ENOMEM;
115         return 0;
116 }
117
118 static void dmirror_bounce_fini(struct dmirror_bounce *bounce)
119 {
120         vfree(bounce->ptr);
121 }
122
123 static int dmirror_fops_open(struct inode *inode, struct file *filp)
124 {
125         struct cdev *cdev = inode->i_cdev;
126         struct dmirror *dmirror;
127         int ret;
128
129         /* Mirror this process address space */
130         dmirror = kzalloc(sizeof(*dmirror), GFP_KERNEL);
131         if (dmirror == NULL)
132                 return -ENOMEM;
133
134         dmirror->mdevice = container_of(cdev, struct dmirror_device, cdevice);
135         mutex_init(&dmirror->mutex);
136         xa_init(&dmirror->pt);
137
138         ret = mmu_interval_notifier_insert(&dmirror->notifier, current->mm,
139                                 0, ULONG_MAX & PAGE_MASK, &dmirror_min_ops);
140         if (ret) {
141                 kfree(dmirror);
142                 return ret;
143         }
144
145         filp->private_data = dmirror;
146         return 0;
147 }
148
149 static int dmirror_fops_release(struct inode *inode, struct file *filp)
150 {
151         struct dmirror *dmirror = filp->private_data;
152
153         mmu_interval_notifier_remove(&dmirror->notifier);
154         xa_destroy(&dmirror->pt);
155         kfree(dmirror);
156         return 0;
157 }
158
159 static struct dmirror_device *dmirror_page_to_device(struct page *page)
160
161 {
162         return container_of(page->pgmap, struct dmirror_chunk,
163                             pagemap)->mdevice;
164 }
165
166 static int dmirror_do_fault(struct dmirror *dmirror, struct hmm_range *range)
167 {
168         unsigned long *pfns = range->hmm_pfns;
169         unsigned long pfn;
170
171         for (pfn = (range->start >> PAGE_SHIFT);
172              pfn < (range->end >> PAGE_SHIFT);
173              pfn++, pfns++) {
174                 struct page *page;
175                 void *entry;
176
177                 /*
178                  * Since we asked for hmm_range_fault() to populate pages,
179                  * it shouldn't return an error entry on success.
180                  */
181                 WARN_ON(*pfns & HMM_PFN_ERROR);
182                 WARN_ON(!(*pfns & HMM_PFN_VALID));
183
184                 page = hmm_pfn_to_page(*pfns);
185                 WARN_ON(!page);
186
187                 entry = page;
188                 if (*pfns & HMM_PFN_WRITE)
189                         entry = xa_tag_pointer(entry, DPT_XA_TAG_WRITE);
190                 else if (WARN_ON(range->default_flags & HMM_PFN_WRITE))
191                         return -EFAULT;
192                 entry = xa_store(&dmirror->pt, pfn, entry, GFP_ATOMIC);
193                 if (xa_is_err(entry))
194                         return xa_err(entry);
195         }
196
197         return 0;
198 }
199
200 static void dmirror_do_update(struct dmirror *dmirror, unsigned long start,
201                               unsigned long end)
202 {
203         unsigned long pfn;
204         void *entry;
205
206         /*
207          * The XArray doesn't hold references to pages since it relies on
208          * the mmu notifier to clear page pointers when they become stale.
209          * Therefore, it is OK to just clear the entry.
210          */
211         xa_for_each_range(&dmirror->pt, pfn, entry, start >> PAGE_SHIFT,
212                           end >> PAGE_SHIFT)
213                 xa_erase(&dmirror->pt, pfn);
214 }
215
216 static bool dmirror_interval_invalidate(struct mmu_interval_notifier *mni,
217                                 const struct mmu_notifier_range *range,
218                                 unsigned long cur_seq)
219 {
220         struct dmirror *dmirror = container_of(mni, struct dmirror, notifier);
221
222         /*
223          * Ignore invalidation callbacks for device private pages since
224          * the invalidation is handled as part of the migration process.
225          */
226         if (range->event == MMU_NOTIFY_MIGRATE &&
227             range->owner == dmirror->mdevice)
228                 return true;
229
230         if (mmu_notifier_range_blockable(range))
231                 mutex_lock(&dmirror->mutex);
232         else if (!mutex_trylock(&dmirror->mutex))
233                 return false;
234
235         mmu_interval_set_seq(mni, cur_seq);
236         dmirror_do_update(dmirror, range->start, range->end);
237
238         mutex_unlock(&dmirror->mutex);
239         return true;
240 }
241
242 static const struct mmu_interval_notifier_ops dmirror_min_ops = {
243         .invalidate = dmirror_interval_invalidate,
244 };
245
246 static int dmirror_range_fault(struct dmirror *dmirror,
247                                 struct hmm_range *range)
248 {
249         struct mm_struct *mm = dmirror->notifier.mm;
250         unsigned long timeout =
251                 jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
252         int ret;
253
254         while (true) {
255                 if (time_after(jiffies, timeout)) {
256                         ret = -EBUSY;
257                         goto out;
258                 }
259
260                 range->notifier_seq = mmu_interval_read_begin(range->notifier);
261                 mmap_read_lock(mm);
262                 ret = hmm_range_fault(range);
263                 mmap_read_unlock(mm);
264                 if (ret) {
265                         if (ret == -EBUSY)
266                                 continue;
267                         goto out;
268                 }
269
270                 mutex_lock(&dmirror->mutex);
271                 if (mmu_interval_read_retry(range->notifier,
272                                             range->notifier_seq)) {
273                         mutex_unlock(&dmirror->mutex);
274                         continue;
275                 }
276                 break;
277         }
278
279         ret = dmirror_do_fault(dmirror, range);
280
281         mutex_unlock(&dmirror->mutex);
282 out:
283         return ret;
284 }
285
286 static int dmirror_fault(struct dmirror *dmirror, unsigned long start,
287                          unsigned long end, bool write)
288 {
289         struct mm_struct *mm = dmirror->notifier.mm;
290         unsigned long addr;
291         unsigned long pfns[64];
292         struct hmm_range range = {
293                 .notifier = &dmirror->notifier,
294                 .hmm_pfns = pfns,
295                 .pfn_flags_mask = 0,
296                 .default_flags =
297                         HMM_PFN_REQ_FAULT | (write ? HMM_PFN_REQ_WRITE : 0),
298                 .dev_private_owner = dmirror->mdevice,
299         };
300         int ret = 0;
301
302         /* Since the mm is for the mirrored process, get a reference first. */
303         if (!mmget_not_zero(mm))
304                 return 0;
305
306         for (addr = start; addr < end; addr = range.end) {
307                 range.start = addr;
308                 range.end = min(addr + (ARRAY_SIZE(pfns) << PAGE_SHIFT), end);
309
310                 ret = dmirror_range_fault(dmirror, &range);
311                 if (ret)
312                         break;
313         }
314
315         mmput(mm);
316         return ret;
317 }
318
319 static int dmirror_do_read(struct dmirror *dmirror, unsigned long start,
320                            unsigned long end, struct dmirror_bounce *bounce)
321 {
322         unsigned long pfn;
323         void *ptr;
324
325         ptr = bounce->ptr + ((start - bounce->addr) & PAGE_MASK);
326
327         for (pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++) {
328                 void *entry;
329                 struct page *page;
330                 void *tmp;
331
332                 entry = xa_load(&dmirror->pt, pfn);
333                 page = xa_untag_pointer(entry);
334                 if (!page)
335                         return -ENOENT;
336
337                 tmp = kmap(page);
338                 memcpy(ptr, tmp, PAGE_SIZE);
339                 kunmap(page);
340
341                 ptr += PAGE_SIZE;
342                 bounce->cpages++;
343         }
344
345         return 0;
346 }
347
348 static int dmirror_read(struct dmirror *dmirror, struct hmm_dmirror_cmd *cmd)
349 {
350         struct dmirror_bounce bounce;
351         unsigned long start, end;
352         unsigned long size = cmd->npages << PAGE_SHIFT;
353         int ret;
354
355         start = cmd->addr;
356         end = start + size;
357         if (end < start)
358                 return -EINVAL;
359
360         ret = dmirror_bounce_init(&bounce, start, size);
361         if (ret)
362                 return ret;
363
364         while (1) {
365                 mutex_lock(&dmirror->mutex);
366                 ret = dmirror_do_read(dmirror, start, end, &bounce);
367                 mutex_unlock(&dmirror->mutex);
368                 if (ret != -ENOENT)
369                         break;
370
371                 start = cmd->addr + (bounce.cpages << PAGE_SHIFT);
372                 ret = dmirror_fault(dmirror, start, end, false);
373                 if (ret)
374                         break;
375                 cmd->faults++;
376         }
377
378         if (ret == 0) {
379                 if (copy_to_user(u64_to_user_ptr(cmd->ptr), bounce.ptr,
380                                  bounce.size))
381                         ret = -EFAULT;
382         }
383         cmd->cpages = bounce.cpages;
384         dmirror_bounce_fini(&bounce);
385         return ret;
386 }
387
388 static int dmirror_do_write(struct dmirror *dmirror, unsigned long start,
389                             unsigned long end, struct dmirror_bounce *bounce)
390 {
391         unsigned long pfn;
392         void *ptr;
393
394         ptr = bounce->ptr + ((start - bounce->addr) & PAGE_MASK);
395
396         for (pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++) {
397                 void *entry;
398                 struct page *page;
399                 void *tmp;
400
401                 entry = xa_load(&dmirror->pt, pfn);
402                 page = xa_untag_pointer(entry);
403                 if (!page || xa_pointer_tag(entry) != DPT_XA_TAG_WRITE)
404                         return -ENOENT;
405
406                 tmp = kmap(page);
407                 memcpy(tmp, ptr, PAGE_SIZE);
408                 kunmap(page);
409
410                 ptr += PAGE_SIZE;
411                 bounce->cpages++;
412         }
413
414         return 0;
415 }
416
417 static int dmirror_write(struct dmirror *dmirror, struct hmm_dmirror_cmd *cmd)
418 {
419         struct dmirror_bounce bounce;
420         unsigned long start, end;
421         unsigned long size = cmd->npages << PAGE_SHIFT;
422         int ret;
423
424         start = cmd->addr;
425         end = start + size;
426         if (end < start)
427                 return -EINVAL;
428
429         ret = dmirror_bounce_init(&bounce, start, size);
430         if (ret)
431                 return ret;
432         if (copy_from_user(bounce.ptr, u64_to_user_ptr(cmd->ptr),
433                            bounce.size)) {
434                 ret = -EFAULT;
435                 goto fini;
436         }
437
438         while (1) {
439                 mutex_lock(&dmirror->mutex);
440                 ret = dmirror_do_write(dmirror, start, end, &bounce);
441                 mutex_unlock(&dmirror->mutex);
442                 if (ret != -ENOENT)
443                         break;
444
445                 start = cmd->addr + (bounce.cpages << PAGE_SHIFT);
446                 ret = dmirror_fault(dmirror, start, end, true);
447                 if (ret)
448                         break;
449                 cmd->faults++;
450         }
451
452 fini:
453         cmd->cpages = bounce.cpages;
454         dmirror_bounce_fini(&bounce);
455         return ret;
456 }
457
458 static bool dmirror_allocate_chunk(struct dmirror_device *mdevice,
459                                    struct page **ppage)
460 {
461         struct dmirror_chunk *devmem;
462         struct resource *res;
463         unsigned long pfn;
464         unsigned long pfn_first;
465         unsigned long pfn_last;
466         void *ptr;
467
468         devmem = kzalloc(sizeof(*devmem), GFP_KERNEL);
469         if (!devmem)
470                 return false;
471
472         res = request_free_mem_region(&iomem_resource, DEVMEM_CHUNK_SIZE,
473                                       "hmm_dmirror");
474         if (IS_ERR(res))
475                 goto err_devmem;
476
477         devmem->pagemap.type = MEMORY_DEVICE_PRIVATE;
478         devmem->pagemap.range.start = res->start;
479         devmem->pagemap.range.end = res->end;
480         devmem->pagemap.nr_range = 1;
481         devmem->pagemap.ops = &dmirror_devmem_ops;
482         devmem->pagemap.owner = mdevice;
483
484         mutex_lock(&mdevice->devmem_lock);
485
486         if (mdevice->devmem_count == mdevice->devmem_capacity) {
487                 struct dmirror_chunk **new_chunks;
488                 unsigned int new_capacity;
489
490                 new_capacity = mdevice->devmem_capacity +
491                                 DEVMEM_CHUNKS_RESERVE;
492                 new_chunks = krealloc(mdevice->devmem_chunks,
493                                 sizeof(new_chunks[0]) * new_capacity,
494                                 GFP_KERNEL);
495                 if (!new_chunks)
496                         goto err_release;
497                 mdevice->devmem_capacity = new_capacity;
498                 mdevice->devmem_chunks = new_chunks;
499         }
500
501         ptr = memremap_pages(&devmem->pagemap, numa_node_id());
502         if (IS_ERR(ptr))
503                 goto err_release;
504
505         devmem->mdevice = mdevice;
506         pfn_first = devmem->pagemap.range.start >> PAGE_SHIFT;
507         pfn_last = pfn_first + (range_len(&devmem->pagemap.range) >> PAGE_SHIFT);
508         mdevice->devmem_chunks[mdevice->devmem_count++] = devmem;
509
510         mutex_unlock(&mdevice->devmem_lock);
511
512         pr_info("added new %u MB chunk (total %u chunks, %u MB) PFNs [0x%lx 0x%lx)\n",
513                 DEVMEM_CHUNK_SIZE / (1024 * 1024),
514                 mdevice->devmem_count,
515                 mdevice->devmem_count * (DEVMEM_CHUNK_SIZE / (1024 * 1024)),
516                 pfn_first, pfn_last);
517
518         spin_lock(&mdevice->lock);
519         for (pfn = pfn_first; pfn < pfn_last; pfn++) {
520                 struct page *page = pfn_to_page(pfn);
521
522                 page->zone_device_data = mdevice->free_pages;
523                 mdevice->free_pages = page;
524         }
525         if (ppage) {
526                 *ppage = mdevice->free_pages;
527                 mdevice->free_pages = (*ppage)->zone_device_data;
528                 mdevice->calloc++;
529         }
530         spin_unlock(&mdevice->lock);
531
532         return true;
533
534 err_release:
535         mutex_unlock(&mdevice->devmem_lock);
536         release_mem_region(devmem->pagemap.range.start, range_len(&devmem->pagemap.range));
537 err_devmem:
538         kfree(devmem);
539
540         return false;
541 }
542
543 static struct page *dmirror_devmem_alloc_page(struct dmirror_device *mdevice)
544 {
545         struct page *dpage = NULL;
546         struct page *rpage;
547
548         /*
549          * This is a fake device so we alloc real system memory to store
550          * our device memory.
551          */
552         rpage = alloc_page(GFP_HIGHUSER);
553         if (!rpage)
554                 return NULL;
555
556         spin_lock(&mdevice->lock);
557
558         if (mdevice->free_pages) {
559                 dpage = mdevice->free_pages;
560                 mdevice->free_pages = dpage->zone_device_data;
561                 mdevice->calloc++;
562                 spin_unlock(&mdevice->lock);
563         } else {
564                 spin_unlock(&mdevice->lock);
565                 if (!dmirror_allocate_chunk(mdevice, &dpage))
566                         goto error;
567         }
568
569         dpage->zone_device_data = rpage;
570         lock_page(dpage);
571         return dpage;
572
573 error:
574         __free_page(rpage);
575         return NULL;
576 }
577
578 static void dmirror_migrate_alloc_and_copy(struct migrate_vma *args,
579                                            struct dmirror *dmirror)
580 {
581         struct dmirror_device *mdevice = dmirror->mdevice;
582         const unsigned long *src = args->src;
583         unsigned long *dst = args->dst;
584         unsigned long addr;
585
586         for (addr = args->start; addr < args->end; addr += PAGE_SIZE,
587                                                    src++, dst++) {
588                 struct page *spage;
589                 struct page *dpage;
590                 struct page *rpage;
591
592                 if (!(*src & MIGRATE_PFN_MIGRATE))
593                         continue;
594
595                 /*
596                  * Note that spage might be NULL which is OK since it is an
597                  * unallocated pte_none() or read-only zero page.
598                  */
599                 spage = migrate_pfn_to_page(*src);
600
601                 dpage = dmirror_devmem_alloc_page(mdevice);
602                 if (!dpage)
603                         continue;
604
605                 rpage = dpage->zone_device_data;
606                 if (spage)
607                         copy_highpage(rpage, spage);
608                 else
609                         clear_highpage(rpage);
610
611                 /*
612                  * Normally, a device would use the page->zone_device_data to
613                  * point to the mirror but here we use it to hold the page for
614                  * the simulated device memory and that page holds the pointer
615                  * to the mirror.
616                  */
617                 rpage->zone_device_data = dmirror;
618
619                 *dst = migrate_pfn(page_to_pfn(dpage));
620                 if ((*src & MIGRATE_PFN_WRITE) ||
621                     (!spage && args->vma->vm_flags & VM_WRITE))
622                         *dst |= MIGRATE_PFN_WRITE;
623         }
624 }
625
626 static int dmirror_check_atomic(struct dmirror *dmirror, unsigned long start,
627                              unsigned long end)
628 {
629         unsigned long pfn;
630
631         for (pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++) {
632                 void *entry;
633
634                 entry = xa_load(&dmirror->pt, pfn);
635                 if (xa_pointer_tag(entry) == DPT_XA_TAG_ATOMIC)
636                         return -EPERM;
637         }
638
639         return 0;
640 }
641
642 static int dmirror_atomic_map(unsigned long start, unsigned long end,
643                               struct page **pages, struct dmirror *dmirror)
644 {
645         unsigned long pfn, mapped = 0;
646         int i;
647
648         /* Map the migrated pages into the device's page tables. */
649         mutex_lock(&dmirror->mutex);
650
651         for (i = 0, pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++, i++) {
652                 void *entry;
653
654                 if (!pages[i])
655                         continue;
656
657                 entry = pages[i];
658                 entry = xa_tag_pointer(entry, DPT_XA_TAG_ATOMIC);
659                 entry = xa_store(&dmirror->pt, pfn, entry, GFP_ATOMIC);
660                 if (xa_is_err(entry)) {
661                         mutex_unlock(&dmirror->mutex);
662                         return xa_err(entry);
663                 }
664
665                 mapped++;
666         }
667
668         mutex_unlock(&dmirror->mutex);
669         return mapped;
670 }
671
672 static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
673                                             struct dmirror *dmirror)
674 {
675         unsigned long start = args->start;
676         unsigned long end = args->end;
677         const unsigned long *src = args->src;
678         const unsigned long *dst = args->dst;
679         unsigned long pfn;
680
681         /* Map the migrated pages into the device's page tables. */
682         mutex_lock(&dmirror->mutex);
683
684         for (pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++,
685                                                                 src++, dst++) {
686                 struct page *dpage;
687                 void *entry;
688
689                 if (!(*src & MIGRATE_PFN_MIGRATE))
690                         continue;
691
692                 dpage = migrate_pfn_to_page(*dst);
693                 if (!dpage)
694                         continue;
695
696                 /*
697                  * Store the page that holds the data so the page table
698                  * doesn't have to deal with ZONE_DEVICE private pages.
699                  */
700                 entry = dpage->zone_device_data;
701                 if (*dst & MIGRATE_PFN_WRITE)
702                         entry = xa_tag_pointer(entry, DPT_XA_TAG_WRITE);
703                 entry = xa_store(&dmirror->pt, pfn, entry, GFP_ATOMIC);
704                 if (xa_is_err(entry)) {
705                         mutex_unlock(&dmirror->mutex);
706                         return xa_err(entry);
707                 }
708         }
709
710         mutex_unlock(&dmirror->mutex);
711         return 0;
712 }
713
714 static int dmirror_exclusive(struct dmirror *dmirror,
715                              struct hmm_dmirror_cmd *cmd)
716 {
717         unsigned long start, end, addr;
718         unsigned long size = cmd->npages << PAGE_SHIFT;
719         struct mm_struct *mm = dmirror->notifier.mm;
720         struct page *pages[64];
721         struct dmirror_bounce bounce;
722         unsigned long next;
723         int ret;
724
725         start = cmd->addr;
726         end = start + size;
727         if (end < start)
728                 return -EINVAL;
729
730         /* Since the mm is for the mirrored process, get a reference first. */
731         if (!mmget_not_zero(mm))
732                 return -EINVAL;
733
734         mmap_read_lock(mm);
735         for (addr = start; addr < end; addr = next) {
736                 unsigned long mapped = 0;
737                 int i;
738
739                 if (end < addr + (ARRAY_SIZE(pages) << PAGE_SHIFT))
740                         next = end;
741                 else
742                         next = addr + (ARRAY_SIZE(pages) << PAGE_SHIFT);
743
744                 ret = make_device_exclusive_range(mm, addr, next, pages, NULL);
745                 /*
746                  * Do dmirror_atomic_map() iff all pages are marked for
747                  * exclusive access to avoid accessing uninitialized
748                  * fields of pages.
749                  */
750                 if (ret == (next - addr) >> PAGE_SHIFT)
751                         mapped = dmirror_atomic_map(addr, next, pages, dmirror);
752                 for (i = 0; i < ret; i++) {
753                         if (pages[i]) {
754                                 unlock_page(pages[i]);
755                                 put_page(pages[i]);
756                         }
757                 }
758
759                 if (addr + (mapped << PAGE_SHIFT) < next) {
760                         mmap_read_unlock(mm);
761                         mmput(mm);
762                         return -EBUSY;
763                 }
764         }
765         mmap_read_unlock(mm);
766         mmput(mm);
767
768         /* Return the migrated data for verification. */
769         ret = dmirror_bounce_init(&bounce, start, size);
770         if (ret)
771                 return ret;
772         mutex_lock(&dmirror->mutex);
773         ret = dmirror_do_read(dmirror, start, end, &bounce);
774         mutex_unlock(&dmirror->mutex);
775         if (ret == 0) {
776                 if (copy_to_user(u64_to_user_ptr(cmd->ptr), bounce.ptr,
777                                  bounce.size))
778                         ret = -EFAULT;
779         }
780
781         cmd->cpages = bounce.cpages;
782         dmirror_bounce_fini(&bounce);
783         return ret;
784 }
785
786 static int dmirror_migrate(struct dmirror *dmirror,
787                            struct hmm_dmirror_cmd *cmd)
788 {
789         unsigned long start, end, addr;
790         unsigned long size = cmd->npages << PAGE_SHIFT;
791         struct mm_struct *mm = dmirror->notifier.mm;
792         struct vm_area_struct *vma;
793         unsigned long src_pfns[64];
794         unsigned long dst_pfns[64];
795         struct dmirror_bounce bounce;
796         struct migrate_vma args;
797         unsigned long next;
798         int ret;
799
800         start = cmd->addr;
801         end = start + size;
802         if (end < start)
803                 return -EINVAL;
804
805         /* Since the mm is for the mirrored process, get a reference first. */
806         if (!mmget_not_zero(mm))
807                 return -EINVAL;
808
809         mmap_read_lock(mm);
810         for (addr = start; addr < end; addr = next) {
811                 vma = vma_lookup(mm, addr);
812                 if (!vma || !(vma->vm_flags & VM_READ)) {
813                         ret = -EINVAL;
814                         goto out;
815                 }
816                 next = min(end, addr + (ARRAY_SIZE(src_pfns) << PAGE_SHIFT));
817                 if (next > vma->vm_end)
818                         next = vma->vm_end;
819
820                 args.vma = vma;
821                 args.src = src_pfns;
822                 args.dst = dst_pfns;
823                 args.start = addr;
824                 args.end = next;
825                 args.pgmap_owner = dmirror->mdevice;
826                 args.flags = MIGRATE_VMA_SELECT_SYSTEM;
827                 ret = migrate_vma_setup(&args);
828                 if (ret)
829                         goto out;
830
831                 dmirror_migrate_alloc_and_copy(&args, dmirror);
832                 migrate_vma_pages(&args);
833                 dmirror_migrate_finalize_and_map(&args, dmirror);
834                 migrate_vma_finalize(&args);
835         }
836         mmap_read_unlock(mm);
837         mmput(mm);
838
839         /* Return the migrated data for verification. */
840         ret = dmirror_bounce_init(&bounce, start, size);
841         if (ret)
842                 return ret;
843         mutex_lock(&dmirror->mutex);
844         ret = dmirror_do_read(dmirror, start, end, &bounce);
845         mutex_unlock(&dmirror->mutex);
846         if (ret == 0) {
847                 if (copy_to_user(u64_to_user_ptr(cmd->ptr), bounce.ptr,
848                                  bounce.size))
849                         ret = -EFAULT;
850         }
851         cmd->cpages = bounce.cpages;
852         dmirror_bounce_fini(&bounce);
853         return ret;
854
855 out:
856         mmap_read_unlock(mm);
857         mmput(mm);
858         return ret;
859 }
860
861 static void dmirror_mkentry(struct dmirror *dmirror, struct hmm_range *range,
862                             unsigned char *perm, unsigned long entry)
863 {
864         struct page *page;
865
866         if (entry & HMM_PFN_ERROR) {
867                 *perm = HMM_DMIRROR_PROT_ERROR;
868                 return;
869         }
870         if (!(entry & HMM_PFN_VALID)) {
871                 *perm = HMM_DMIRROR_PROT_NONE;
872                 return;
873         }
874
875         page = hmm_pfn_to_page(entry);
876         if (is_device_private_page(page)) {
877                 /* Is the page migrated to this device or some other? */
878                 if (dmirror->mdevice == dmirror_page_to_device(page))
879                         *perm = HMM_DMIRROR_PROT_DEV_PRIVATE_LOCAL;
880                 else
881                         *perm = HMM_DMIRROR_PROT_DEV_PRIVATE_REMOTE;
882         } else if (is_zero_pfn(page_to_pfn(page)))
883                 *perm = HMM_DMIRROR_PROT_ZERO;
884         else
885                 *perm = HMM_DMIRROR_PROT_NONE;
886         if (entry & HMM_PFN_WRITE)
887                 *perm |= HMM_DMIRROR_PROT_WRITE;
888         else
889                 *perm |= HMM_DMIRROR_PROT_READ;
890         if (hmm_pfn_to_map_order(entry) + PAGE_SHIFT == PMD_SHIFT)
891                 *perm |= HMM_DMIRROR_PROT_PMD;
892         else if (hmm_pfn_to_map_order(entry) + PAGE_SHIFT == PUD_SHIFT)
893                 *perm |= HMM_DMIRROR_PROT_PUD;
894 }
895
896 static bool dmirror_snapshot_invalidate(struct mmu_interval_notifier *mni,
897                                 const struct mmu_notifier_range *range,
898                                 unsigned long cur_seq)
899 {
900         struct dmirror_interval *dmi =
901                 container_of(mni, struct dmirror_interval, notifier);
902         struct dmirror *dmirror = dmi->dmirror;
903
904         if (mmu_notifier_range_blockable(range))
905                 mutex_lock(&dmirror->mutex);
906         else if (!mutex_trylock(&dmirror->mutex))
907                 return false;
908
909         /*
910          * Snapshots only need to set the sequence number since any
911          * invalidation in the interval invalidates the whole snapshot.
912          */
913         mmu_interval_set_seq(mni, cur_seq);
914
915         mutex_unlock(&dmirror->mutex);
916         return true;
917 }
918
919 static const struct mmu_interval_notifier_ops dmirror_mrn_ops = {
920         .invalidate = dmirror_snapshot_invalidate,
921 };
922
923 static int dmirror_range_snapshot(struct dmirror *dmirror,
924                                   struct hmm_range *range,
925                                   unsigned char *perm)
926 {
927         struct mm_struct *mm = dmirror->notifier.mm;
928         struct dmirror_interval notifier;
929         unsigned long timeout =
930                 jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
931         unsigned long i;
932         unsigned long n;
933         int ret = 0;
934
935         notifier.dmirror = dmirror;
936         range->notifier = &notifier.notifier;
937
938         ret = mmu_interval_notifier_insert(range->notifier, mm,
939                         range->start, range->end - range->start,
940                         &dmirror_mrn_ops);
941         if (ret)
942                 return ret;
943
944         while (true) {
945                 if (time_after(jiffies, timeout)) {
946                         ret = -EBUSY;
947                         goto out;
948                 }
949
950                 range->notifier_seq = mmu_interval_read_begin(range->notifier);
951
952                 mmap_read_lock(mm);
953                 ret = hmm_range_fault(range);
954                 mmap_read_unlock(mm);
955                 if (ret) {
956                         if (ret == -EBUSY)
957                                 continue;
958                         goto out;
959                 }
960
961                 mutex_lock(&dmirror->mutex);
962                 if (mmu_interval_read_retry(range->notifier,
963                                             range->notifier_seq)) {
964                         mutex_unlock(&dmirror->mutex);
965                         continue;
966                 }
967                 break;
968         }
969
970         n = (range->end - range->start) >> PAGE_SHIFT;
971         for (i = 0; i < n; i++)
972                 dmirror_mkentry(dmirror, range, perm + i, range->hmm_pfns[i]);
973
974         mutex_unlock(&dmirror->mutex);
975 out:
976         mmu_interval_notifier_remove(range->notifier);
977         return ret;
978 }
979
980 static int dmirror_snapshot(struct dmirror *dmirror,
981                             struct hmm_dmirror_cmd *cmd)
982 {
983         struct mm_struct *mm = dmirror->notifier.mm;
984         unsigned long start, end;
985         unsigned long size = cmd->npages << PAGE_SHIFT;
986         unsigned long addr;
987         unsigned long next;
988         unsigned long pfns[64];
989         unsigned char perm[64];
990         char __user *uptr;
991         struct hmm_range range = {
992                 .hmm_pfns = pfns,
993                 .dev_private_owner = dmirror->mdevice,
994         };
995         int ret = 0;
996
997         start = cmd->addr;
998         end = start + size;
999         if (end < start)
1000                 return -EINVAL;
1001
1002         /* Since the mm is for the mirrored process, get a reference first. */
1003         if (!mmget_not_zero(mm))
1004                 return -EINVAL;
1005
1006         /*
1007          * Register a temporary notifier to detect invalidations even if it
1008          * overlaps with other mmu_interval_notifiers.
1009          */
1010         uptr = u64_to_user_ptr(cmd->ptr);
1011         for (addr = start; addr < end; addr = next) {
1012                 unsigned long n;
1013
1014                 next = min(addr + (ARRAY_SIZE(pfns) << PAGE_SHIFT), end);
1015                 range.start = addr;
1016                 range.end = next;
1017
1018                 ret = dmirror_range_snapshot(dmirror, &range, perm);
1019                 if (ret)
1020                         break;
1021
1022                 n = (range.end - range.start) >> PAGE_SHIFT;
1023                 if (copy_to_user(uptr, perm, n)) {
1024                         ret = -EFAULT;
1025                         break;
1026                 }
1027
1028                 cmd->cpages += n;
1029                 uptr += n;
1030         }
1031         mmput(mm);
1032
1033         return ret;
1034 }
1035
1036 static long dmirror_fops_unlocked_ioctl(struct file *filp,
1037                                         unsigned int command,
1038                                         unsigned long arg)
1039 {
1040         void __user *uarg = (void __user *)arg;
1041         struct hmm_dmirror_cmd cmd;
1042         struct dmirror *dmirror;
1043         int ret;
1044
1045         dmirror = filp->private_data;
1046         if (!dmirror)
1047                 return -EINVAL;
1048
1049         if (copy_from_user(&cmd, uarg, sizeof(cmd)))
1050                 return -EFAULT;
1051
1052         if (cmd.addr & ~PAGE_MASK)
1053                 return -EINVAL;
1054         if (cmd.addr >= (cmd.addr + (cmd.npages << PAGE_SHIFT)))
1055                 return -EINVAL;
1056
1057         cmd.cpages = 0;
1058         cmd.faults = 0;
1059
1060         switch (command) {
1061         case HMM_DMIRROR_READ:
1062                 ret = dmirror_read(dmirror, &cmd);
1063                 break;
1064
1065         case HMM_DMIRROR_WRITE:
1066                 ret = dmirror_write(dmirror, &cmd);
1067                 break;
1068
1069         case HMM_DMIRROR_MIGRATE:
1070                 ret = dmirror_migrate(dmirror, &cmd);
1071                 break;
1072
1073         case HMM_DMIRROR_EXCLUSIVE:
1074                 ret = dmirror_exclusive(dmirror, &cmd);
1075                 break;
1076
1077         case HMM_DMIRROR_CHECK_EXCLUSIVE:
1078                 ret = dmirror_check_atomic(dmirror, cmd.addr,
1079                                         cmd.addr + (cmd.npages << PAGE_SHIFT));
1080                 break;
1081
1082         case HMM_DMIRROR_SNAPSHOT:
1083                 ret = dmirror_snapshot(dmirror, &cmd);
1084                 break;
1085
1086         default:
1087                 return -EINVAL;
1088         }
1089         if (ret)
1090                 return ret;
1091
1092         if (copy_to_user(uarg, &cmd, sizeof(cmd)))
1093                 return -EFAULT;
1094
1095         return 0;
1096 }
1097
1098 static int dmirror_fops_mmap(struct file *file, struct vm_area_struct *vma)
1099 {
1100         unsigned long addr;
1101
1102         for (addr = vma->vm_start; addr < vma->vm_end; addr += PAGE_SIZE) {
1103                 struct page *page;
1104                 int ret;
1105
1106                 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1107                 if (!page)
1108                         return -ENOMEM;
1109
1110                 ret = vm_insert_page(vma, addr, page);
1111                 if (ret) {
1112                         __free_page(page);
1113                         return ret;
1114                 }
1115                 put_page(page);
1116         }
1117
1118         return 0;
1119 }
1120
1121 static const struct file_operations dmirror_fops = {
1122         .open           = dmirror_fops_open,
1123         .release        = dmirror_fops_release,
1124         .mmap           = dmirror_fops_mmap,
1125         .unlocked_ioctl = dmirror_fops_unlocked_ioctl,
1126         .llseek         = default_llseek,
1127         .owner          = THIS_MODULE,
1128 };
1129
1130 static void dmirror_devmem_free(struct page *page)
1131 {
1132         struct page *rpage = page->zone_device_data;
1133         struct dmirror_device *mdevice;
1134
1135         if (rpage)
1136                 __free_page(rpage);
1137
1138         mdevice = dmirror_page_to_device(page);
1139
1140         spin_lock(&mdevice->lock);
1141         mdevice->cfree++;
1142         page->zone_device_data = mdevice->free_pages;
1143         mdevice->free_pages = page;
1144         spin_unlock(&mdevice->lock);
1145 }
1146
1147 static vm_fault_t dmirror_devmem_fault_alloc_and_copy(struct migrate_vma *args,
1148                                                       struct dmirror *dmirror)
1149 {
1150         const unsigned long *src = args->src;
1151         unsigned long *dst = args->dst;
1152         unsigned long start = args->start;
1153         unsigned long end = args->end;
1154         unsigned long addr;
1155
1156         for (addr = start; addr < end; addr += PAGE_SIZE,
1157                                        src++, dst++) {
1158                 struct page *dpage, *spage;
1159
1160                 spage = migrate_pfn_to_page(*src);
1161                 if (!spage || !(*src & MIGRATE_PFN_MIGRATE))
1162                         continue;
1163                 spage = spage->zone_device_data;
1164
1165                 dpage = alloc_page_vma(GFP_HIGHUSER_MOVABLE, args->vma, addr);
1166                 if (!dpage)
1167                         continue;
1168
1169                 lock_page(dpage);
1170                 xa_erase(&dmirror->pt, addr >> PAGE_SHIFT);
1171                 copy_highpage(dpage, spage);
1172                 *dst = migrate_pfn(page_to_pfn(dpage));
1173                 if (*src & MIGRATE_PFN_WRITE)
1174                         *dst |= MIGRATE_PFN_WRITE;
1175         }
1176         return 0;
1177 }
1178
1179 static vm_fault_t dmirror_devmem_fault(struct vm_fault *vmf)
1180 {
1181         struct migrate_vma args;
1182         unsigned long src_pfns;
1183         unsigned long dst_pfns;
1184         struct page *rpage;
1185         struct dmirror *dmirror;
1186         vm_fault_t ret;
1187
1188         /*
1189          * Normally, a device would use the page->zone_device_data to point to
1190          * the mirror but here we use it to hold the page for the simulated
1191          * device memory and that page holds the pointer to the mirror.
1192          */
1193         rpage = vmf->page->zone_device_data;
1194         dmirror = rpage->zone_device_data;
1195
1196         /* FIXME demonstrate how we can adjust migrate range */
1197         args.vma = vmf->vma;
1198         args.start = vmf->address;
1199         args.end = args.start + PAGE_SIZE;
1200         args.src = &src_pfns;
1201         args.dst = &dst_pfns;
1202         args.pgmap_owner = dmirror->mdevice;
1203         args.flags = MIGRATE_VMA_SELECT_DEVICE_PRIVATE;
1204
1205         if (migrate_vma_setup(&args))
1206                 return VM_FAULT_SIGBUS;
1207
1208         ret = dmirror_devmem_fault_alloc_and_copy(&args, dmirror);
1209         if (ret)
1210                 return ret;
1211         migrate_vma_pages(&args);
1212         /*
1213          * No device finalize step is needed since
1214          * dmirror_devmem_fault_alloc_and_copy() will have already
1215          * invalidated the device page table.
1216          */
1217         migrate_vma_finalize(&args);
1218         return 0;
1219 }
1220
1221 static const struct dev_pagemap_ops dmirror_devmem_ops = {
1222         .page_free      = dmirror_devmem_free,
1223         .migrate_to_ram = dmirror_devmem_fault,
1224 };
1225
1226 static int dmirror_device_init(struct dmirror_device *mdevice, int id)
1227 {
1228         dev_t dev;
1229         int ret;
1230
1231         dev = MKDEV(MAJOR(dmirror_dev), id);
1232         mutex_init(&mdevice->devmem_lock);
1233         spin_lock_init(&mdevice->lock);
1234
1235         cdev_init(&mdevice->cdevice, &dmirror_fops);
1236         mdevice->cdevice.owner = THIS_MODULE;
1237         ret = cdev_add(&mdevice->cdevice, dev, 1);
1238         if (ret)
1239                 return ret;
1240
1241         /* Build a list of free ZONE_DEVICE private struct pages */
1242         dmirror_allocate_chunk(mdevice, NULL);
1243
1244         return 0;
1245 }
1246
1247 static void dmirror_device_remove(struct dmirror_device *mdevice)
1248 {
1249         unsigned int i;
1250
1251         if (mdevice->devmem_chunks) {
1252                 for (i = 0; i < mdevice->devmem_count; i++) {
1253                         struct dmirror_chunk *devmem =
1254                                 mdevice->devmem_chunks[i];
1255
1256                         memunmap_pages(&devmem->pagemap);
1257                         release_mem_region(devmem->pagemap.range.start,
1258                                            range_len(&devmem->pagemap.range));
1259                         kfree(devmem);
1260                 }
1261                 kfree(mdevice->devmem_chunks);
1262         }
1263
1264         cdev_del(&mdevice->cdevice);
1265 }
1266
1267 static int __init hmm_dmirror_init(void)
1268 {
1269         int ret;
1270         int id = 0;
1271         int ndevices = 0;
1272
1273         ret = alloc_chrdev_region(&dmirror_dev, 0, DMIRROR_NDEVICES,
1274                                   "HMM_DMIRROR");
1275         if (ret)
1276                 goto err_unreg;
1277
1278         memset(dmirror_devices, 0, DMIRROR_NDEVICES * sizeof(dmirror_devices[0]));
1279         dmirror_devices[ndevices++].zone_device_type =
1280                                 HMM_DMIRROR_MEMORY_DEVICE_PRIVATE;
1281         dmirror_devices[ndevices++].zone_device_type =
1282                                 HMM_DMIRROR_MEMORY_DEVICE_PRIVATE;
1283         for (id = 0; id < ndevices; id++) {
1284                 ret = dmirror_device_init(dmirror_devices + id, id);
1285                 if (ret)
1286                         goto err_chrdev;
1287         }
1288
1289         pr_info("HMM test module loaded. This is only for testing HMM.\n");
1290         return 0;
1291
1292 err_chrdev:
1293         while (--id >= 0)
1294                 dmirror_device_remove(dmirror_devices + id);
1295         unregister_chrdev_region(dmirror_dev, DMIRROR_NDEVICES);
1296 err_unreg:
1297         return ret;
1298 }
1299
1300 static void __exit hmm_dmirror_exit(void)
1301 {
1302         int id;
1303
1304         for (id = 0; id < DMIRROR_NDEVICES; id++)
1305                 dmirror_device_remove(dmirror_devices + id);
1306         unregister_chrdev_region(dmirror_dev, DMIRROR_NDEVICES);
1307 }
1308
1309 module_init(hmm_dmirror_init);
1310 module_exit(hmm_dmirror_exit);
1311 MODULE_LICENSE("GPL");