include/linux/relay.h: fix percpu annotation in struct rchan
[linux] / mm / migrate.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Memory Migration functionality - linux/mm/migrate.c
4  *
5  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
6  *
7  * Page migration was first developed in the context of the memory hotplug
8  * project. The main authors of the migration code are:
9  *
10  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
11  * Hirokazu Takahashi <taka@valinux.co.jp>
12  * Dave Hansen <haveblue@us.ibm.com>
13  * Christoph Lameter
14  */
15
16 #include <linux/migrate.h>
17 #include <linux/export.h>
18 #include <linux/swap.h>
19 #include <linux/swapops.h>
20 #include <linux/pagemap.h>
21 #include <linux/buffer_head.h>
22 #include <linux/mm_inline.h>
23 #include <linux/nsproxy.h>
24 #include <linux/pagevec.h>
25 #include <linux/ksm.h>
26 #include <linux/rmap.h>
27 #include <linux/topology.h>
28 #include <linux/cpu.h>
29 #include <linux/cpuset.h>
30 #include <linux/writeback.h>
31 #include <linux/mempolicy.h>
32 #include <linux/vmalloc.h>
33 #include <linux/security.h>
34 #include <linux/backing-dev.h>
35 #include <linux/compaction.h>
36 #include <linux/syscalls.h>
37 #include <linux/compat.h>
38 #include <linux/hugetlb.h>
39 #include <linux/hugetlb_cgroup.h>
40 #include <linux/gfp.h>
41 #include <linux/pfn_t.h>
42 #include <linux/memremap.h>
43 #include <linux/userfaultfd_k.h>
44 #include <linux/balloon_compaction.h>
45 #include <linux/mmu_notifier.h>
46 #include <linux/page_idle.h>
47 #include <linux/page_owner.h>
48 #include <linux/sched/mm.h>
49 #include <linux/ptrace.h>
50
51 #include <asm/tlbflush.h>
52
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/migrate.h>
55
56 #include "internal.h"
57
58 /*
59  * migrate_prep() needs to be called before we start compiling a list of pages
60  * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
61  * undesirable, use migrate_prep_local()
62  */
63 int migrate_prep(void)
64 {
65         /*
66          * Clear the LRU lists so pages can be isolated.
67          * Note that pages may be moved off the LRU after we have
68          * drained them. Those pages will fail to migrate like other
69          * pages that may be busy.
70          */
71         lru_add_drain_all();
72
73         return 0;
74 }
75
76 /* Do the necessary work of migrate_prep but not if it involves other CPUs */
77 int migrate_prep_local(void)
78 {
79         lru_add_drain();
80
81         return 0;
82 }
83
84 int isolate_movable_page(struct page *page, isolate_mode_t mode)
85 {
86         struct address_space *mapping;
87
88         /*
89          * Avoid burning cycles with pages that are yet under __free_pages(),
90          * or just got freed under us.
91          *
92          * In case we 'win' a race for a movable page being freed under us and
93          * raise its refcount preventing __free_pages() from doing its job
94          * the put_page() at the end of this block will take care of
95          * release this page, thus avoiding a nasty leakage.
96          */
97         if (unlikely(!get_page_unless_zero(page)))
98                 goto out;
99
100         /*
101          * Check PageMovable before holding a PG_lock because page's owner
102          * assumes anybody doesn't touch PG_lock of newly allocated page
103          * so unconditionally grabbing the lock ruins page's owner side.
104          */
105         if (unlikely(!__PageMovable(page)))
106                 goto out_putpage;
107         /*
108          * As movable pages are not isolated from LRU lists, concurrent
109          * compaction threads can race against page migration functions
110          * as well as race against the releasing a page.
111          *
112          * In order to avoid having an already isolated movable page
113          * being (wrongly) re-isolated while it is under migration,
114          * or to avoid attempting to isolate pages being released,
115          * lets be sure we have the page lock
116          * before proceeding with the movable page isolation steps.
117          */
118         if (unlikely(!trylock_page(page)))
119                 goto out_putpage;
120
121         if (!PageMovable(page) || PageIsolated(page))
122                 goto out_no_isolated;
123
124         mapping = page_mapping(page);
125         VM_BUG_ON_PAGE(!mapping, page);
126
127         if (!mapping->a_ops->isolate_page(page, mode))
128                 goto out_no_isolated;
129
130         /* Driver shouldn't use PG_isolated bit of page->flags */
131         WARN_ON_ONCE(PageIsolated(page));
132         __SetPageIsolated(page);
133         unlock_page(page);
134
135         return 0;
136
137 out_no_isolated:
138         unlock_page(page);
139 out_putpage:
140         put_page(page);
141 out:
142         return -EBUSY;
143 }
144
145 /* It should be called on page which is PG_movable */
146 void putback_movable_page(struct page *page)
147 {
148         struct address_space *mapping;
149
150         VM_BUG_ON_PAGE(!PageLocked(page), page);
151         VM_BUG_ON_PAGE(!PageMovable(page), page);
152         VM_BUG_ON_PAGE(!PageIsolated(page), page);
153
154         mapping = page_mapping(page);
155         mapping->a_ops->putback_page(page);
156         __ClearPageIsolated(page);
157 }
158
159 /*
160  * Put previously isolated pages back onto the appropriate lists
161  * from where they were once taken off for compaction/migration.
162  *
163  * This function shall be used whenever the isolated pageset has been
164  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
165  * and isolate_huge_page().
166  */
167 void putback_movable_pages(struct list_head *l)
168 {
169         struct page *page;
170         struct page *page2;
171
172         list_for_each_entry_safe(page, page2, l, lru) {
173                 if (unlikely(PageHuge(page))) {
174                         putback_active_hugepage(page);
175                         continue;
176                 }
177                 list_del(&page->lru);
178                 /*
179                  * We isolated non-lru movable page so here we can use
180                  * __PageMovable because LRU page's mapping cannot have
181                  * PAGE_MAPPING_MOVABLE.
182                  */
183                 if (unlikely(__PageMovable(page))) {
184                         VM_BUG_ON_PAGE(!PageIsolated(page), page);
185                         lock_page(page);
186                         if (PageMovable(page))
187                                 putback_movable_page(page);
188                         else
189                                 __ClearPageIsolated(page);
190                         unlock_page(page);
191                         put_page(page);
192                 } else {
193                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
194                                         page_is_file_cache(page), -hpage_nr_pages(page));
195                         putback_lru_page(page);
196                 }
197         }
198 }
199
200 /*
201  * Restore a potential migration pte to a working pte entry
202  */
203 static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma,
204                                  unsigned long addr, void *old)
205 {
206         struct page_vma_mapped_walk pvmw = {
207                 .page = old,
208                 .vma = vma,
209                 .address = addr,
210                 .flags = PVMW_SYNC | PVMW_MIGRATION,
211         };
212         struct page *new;
213         pte_t pte;
214         swp_entry_t entry;
215
216         VM_BUG_ON_PAGE(PageTail(page), page);
217         while (page_vma_mapped_walk(&pvmw)) {
218                 if (PageKsm(page))
219                         new = page;
220                 else
221                         new = page - pvmw.page->index +
222                                 linear_page_index(vma, pvmw.address);
223
224 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
225                 /* PMD-mapped THP migration entry */
226                 if (!pvmw.pte) {
227                         VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
228                         remove_migration_pmd(&pvmw, new);
229                         continue;
230                 }
231 #endif
232
233                 get_page(new);
234                 pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot)));
235                 if (pte_swp_soft_dirty(*pvmw.pte))
236                         pte = pte_mksoft_dirty(pte);
237
238                 /*
239                  * Recheck VMA as permissions can change since migration started
240                  */
241                 entry = pte_to_swp_entry(*pvmw.pte);
242                 if (is_write_migration_entry(entry))
243                         pte = maybe_mkwrite(pte, vma);
244
245                 if (unlikely(is_zone_device_page(new))) {
246                         if (is_device_private_page(new)) {
247                                 entry = make_device_private_entry(new, pte_write(pte));
248                                 pte = swp_entry_to_pte(entry);
249                         } else if (is_device_public_page(new)) {
250                                 pte = pte_mkdevmap(pte);
251                                 flush_dcache_page(new);
252                         }
253                 } else
254                         flush_dcache_page(new);
255
256 #ifdef CONFIG_HUGETLB_PAGE
257                 if (PageHuge(new)) {
258                         pte = pte_mkhuge(pte);
259                         pte = arch_make_huge_pte(pte, vma, new, 0);
260                         set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
261                         if (PageAnon(new))
262                                 hugepage_add_anon_rmap(new, vma, pvmw.address);
263                         else
264                                 page_dup_rmap(new, true);
265                 } else
266 #endif
267                 {
268                         set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
269
270                         if (PageAnon(new))
271                                 page_add_anon_rmap(new, vma, pvmw.address, false);
272                         else
273                                 page_add_file_rmap(new, false);
274                 }
275                 if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new))
276                         mlock_vma_page(new);
277
278                 if (PageTransHuge(page) && PageMlocked(page))
279                         clear_page_mlock(page);
280
281                 /* No need to invalidate - it was non-present before */
282                 update_mmu_cache(vma, pvmw.address, pvmw.pte);
283         }
284
285         return true;
286 }
287
288 /*
289  * Get rid of all migration entries and replace them by
290  * references to the indicated page.
291  */
292 void remove_migration_ptes(struct page *old, struct page *new, bool locked)
293 {
294         struct rmap_walk_control rwc = {
295                 .rmap_one = remove_migration_pte,
296                 .arg = old,
297         };
298
299         if (locked)
300                 rmap_walk_locked(new, &rwc);
301         else
302                 rmap_walk(new, &rwc);
303 }
304
305 /*
306  * Something used the pte of a page under migration. We need to
307  * get to the page and wait until migration is finished.
308  * When we return from this function the fault will be retried.
309  */
310 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
311                                 spinlock_t *ptl)
312 {
313         pte_t pte;
314         swp_entry_t entry;
315         struct page *page;
316
317         spin_lock(ptl);
318         pte = *ptep;
319         if (!is_swap_pte(pte))
320                 goto out;
321
322         entry = pte_to_swp_entry(pte);
323         if (!is_migration_entry(entry))
324                 goto out;
325
326         page = migration_entry_to_page(entry);
327
328         /*
329          * Once page cache replacement of page migration started, page_count
330          * is zero; but we must not call put_and_wait_on_page_locked() without
331          * a ref. Use get_page_unless_zero(), and just fault again if it fails.
332          */
333         if (!get_page_unless_zero(page))
334                 goto out;
335         pte_unmap_unlock(ptep, ptl);
336         put_and_wait_on_page_locked(page);
337         return;
338 out:
339         pte_unmap_unlock(ptep, ptl);
340 }
341
342 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
343                                 unsigned long address)
344 {
345         spinlock_t *ptl = pte_lockptr(mm, pmd);
346         pte_t *ptep = pte_offset_map(pmd, address);
347         __migration_entry_wait(mm, ptep, ptl);
348 }
349
350 void migration_entry_wait_huge(struct vm_area_struct *vma,
351                 struct mm_struct *mm, pte_t *pte)
352 {
353         spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
354         __migration_entry_wait(mm, pte, ptl);
355 }
356
357 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
358 void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
359 {
360         spinlock_t *ptl;
361         struct page *page;
362
363         ptl = pmd_lock(mm, pmd);
364         if (!is_pmd_migration_entry(*pmd))
365                 goto unlock;
366         page = migration_entry_to_page(pmd_to_swp_entry(*pmd));
367         if (!get_page_unless_zero(page))
368                 goto unlock;
369         spin_unlock(ptl);
370         put_and_wait_on_page_locked(page);
371         return;
372 unlock:
373         spin_unlock(ptl);
374 }
375 #endif
376
377 static int expected_page_refs(struct page *page)
378 {
379         int expected_count = 1;
380
381         /*
382          * Device public or private pages have an extra refcount as they are
383          * ZONE_DEVICE pages.
384          */
385         expected_count += is_device_private_page(page);
386         expected_count += is_device_public_page(page);
387         if (page_mapping(page))
388                 expected_count += hpage_nr_pages(page) + page_has_private(page);
389
390         return expected_count;
391 }
392
393 /*
394  * Replace the page in the mapping.
395  *
396  * The number of remaining references must be:
397  * 1 for anonymous pages without a mapping
398  * 2 for pages with a mapping
399  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
400  */
401 int migrate_page_move_mapping(struct address_space *mapping,
402                 struct page *newpage, struct page *page, enum migrate_mode mode,
403                 int extra_count)
404 {
405         XA_STATE(xas, &mapping->i_pages, page_index(page));
406         struct zone *oldzone, *newzone;
407         int dirty;
408         int expected_count = expected_page_refs(page) + extra_count;
409
410         if (!mapping) {
411                 /* Anonymous page without mapping */
412                 if (page_count(page) != expected_count)
413                         return -EAGAIN;
414
415                 /* No turning back from here */
416                 newpage->index = page->index;
417                 newpage->mapping = page->mapping;
418                 if (PageSwapBacked(page))
419                         __SetPageSwapBacked(newpage);
420
421                 return MIGRATEPAGE_SUCCESS;
422         }
423
424         oldzone = page_zone(page);
425         newzone = page_zone(newpage);
426
427         xas_lock_irq(&xas);
428         if (page_count(page) != expected_count || xas_load(&xas) != page) {
429                 xas_unlock_irq(&xas);
430                 return -EAGAIN;
431         }
432
433         if (!page_ref_freeze(page, expected_count)) {
434                 xas_unlock_irq(&xas);
435                 return -EAGAIN;
436         }
437
438         /*
439          * Now we know that no one else is looking at the page:
440          * no turning back from here.
441          */
442         newpage->index = page->index;
443         newpage->mapping = page->mapping;
444         page_ref_add(newpage, hpage_nr_pages(page)); /* add cache reference */
445         if (PageSwapBacked(page)) {
446                 __SetPageSwapBacked(newpage);
447                 if (PageSwapCache(page)) {
448                         SetPageSwapCache(newpage);
449                         set_page_private(newpage, page_private(page));
450                 }
451         } else {
452                 VM_BUG_ON_PAGE(PageSwapCache(page), page);
453         }
454
455         /* Move dirty while page refs frozen and newpage not yet exposed */
456         dirty = PageDirty(page);
457         if (dirty) {
458                 ClearPageDirty(page);
459                 SetPageDirty(newpage);
460         }
461
462         xas_store(&xas, newpage);
463         if (PageTransHuge(page)) {
464                 int i;
465
466                 for (i = 1; i < HPAGE_PMD_NR; i++) {
467                         xas_next(&xas);
468                         xas_store(&xas, newpage + i);
469                 }
470         }
471
472         /*
473          * Drop cache reference from old page by unfreezing
474          * to one less reference.
475          * We know this isn't the last reference.
476          */
477         page_ref_unfreeze(page, expected_count - hpage_nr_pages(page));
478
479         xas_unlock(&xas);
480         /* Leave irq disabled to prevent preemption while updating stats */
481
482         /*
483          * If moved to a different zone then also account
484          * the page for that zone. Other VM counters will be
485          * taken care of when we establish references to the
486          * new page and drop references to the old page.
487          *
488          * Note that anonymous pages are accounted for
489          * via NR_FILE_PAGES and NR_ANON_MAPPED if they
490          * are mapped to swap space.
491          */
492         if (newzone != oldzone) {
493                 __dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES);
494                 __inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES);
495                 if (PageSwapBacked(page) && !PageSwapCache(page)) {
496                         __dec_node_state(oldzone->zone_pgdat, NR_SHMEM);
497                         __inc_node_state(newzone->zone_pgdat, NR_SHMEM);
498                 }
499                 if (dirty && mapping_cap_account_dirty(mapping)) {
500                         __dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY);
501                         __dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING);
502                         __inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY);
503                         __inc_zone_state(newzone, NR_ZONE_WRITE_PENDING);
504                 }
505         }
506         local_irq_enable();
507
508         return MIGRATEPAGE_SUCCESS;
509 }
510 EXPORT_SYMBOL(migrate_page_move_mapping);
511
512 /*
513  * The expected number of remaining references is the same as that
514  * of migrate_page_move_mapping().
515  */
516 int migrate_huge_page_move_mapping(struct address_space *mapping,
517                                    struct page *newpage, struct page *page)
518 {
519         XA_STATE(xas, &mapping->i_pages, page_index(page));
520         int expected_count;
521
522         xas_lock_irq(&xas);
523         expected_count = 2 + page_has_private(page);
524         if (page_count(page) != expected_count || xas_load(&xas) != page) {
525                 xas_unlock_irq(&xas);
526                 return -EAGAIN;
527         }
528
529         if (!page_ref_freeze(page, expected_count)) {
530                 xas_unlock_irq(&xas);
531                 return -EAGAIN;
532         }
533
534         newpage->index = page->index;
535         newpage->mapping = page->mapping;
536
537         get_page(newpage);
538
539         xas_store(&xas, newpage);
540
541         page_ref_unfreeze(page, expected_count - 1);
542
543         xas_unlock_irq(&xas);
544
545         return MIGRATEPAGE_SUCCESS;
546 }
547
548 /*
549  * Gigantic pages are so large that we do not guarantee that page++ pointer
550  * arithmetic will work across the entire page.  We need something more
551  * specialized.
552  */
553 static void __copy_gigantic_page(struct page *dst, struct page *src,
554                                 int nr_pages)
555 {
556         int i;
557         struct page *dst_base = dst;
558         struct page *src_base = src;
559
560         for (i = 0; i < nr_pages; ) {
561                 cond_resched();
562                 copy_highpage(dst, src);
563
564                 i++;
565                 dst = mem_map_next(dst, dst_base, i);
566                 src = mem_map_next(src, src_base, i);
567         }
568 }
569
570 static void copy_huge_page(struct page *dst, struct page *src)
571 {
572         int i;
573         int nr_pages;
574
575         if (PageHuge(src)) {
576                 /* hugetlbfs page */
577                 struct hstate *h = page_hstate(src);
578                 nr_pages = pages_per_huge_page(h);
579
580                 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) {
581                         __copy_gigantic_page(dst, src, nr_pages);
582                         return;
583                 }
584         } else {
585                 /* thp page */
586                 BUG_ON(!PageTransHuge(src));
587                 nr_pages = hpage_nr_pages(src);
588         }
589
590         for (i = 0; i < nr_pages; i++) {
591                 cond_resched();
592                 copy_highpage(dst + i, src + i);
593         }
594 }
595
596 /*
597  * Copy the page to its new location
598  */
599 void migrate_page_states(struct page *newpage, struct page *page)
600 {
601         int cpupid;
602
603         if (PageError(page))
604                 SetPageError(newpage);
605         if (PageReferenced(page))
606                 SetPageReferenced(newpage);
607         if (PageUptodate(page))
608                 SetPageUptodate(newpage);
609         if (TestClearPageActive(page)) {
610                 VM_BUG_ON_PAGE(PageUnevictable(page), page);
611                 SetPageActive(newpage);
612         } else if (TestClearPageUnevictable(page))
613                 SetPageUnevictable(newpage);
614         if (PageWorkingset(page))
615                 SetPageWorkingset(newpage);
616         if (PageChecked(page))
617                 SetPageChecked(newpage);
618         if (PageMappedToDisk(page))
619                 SetPageMappedToDisk(newpage);
620
621         /* Move dirty on pages not done by migrate_page_move_mapping() */
622         if (PageDirty(page))
623                 SetPageDirty(newpage);
624
625         if (page_is_young(page))
626                 set_page_young(newpage);
627         if (page_is_idle(page))
628                 set_page_idle(newpage);
629
630         /*
631          * Copy NUMA information to the new page, to prevent over-eager
632          * future migrations of this same page.
633          */
634         cpupid = page_cpupid_xchg_last(page, -1);
635         page_cpupid_xchg_last(newpage, cpupid);
636
637         ksm_migrate_page(newpage, page);
638         /*
639          * Please do not reorder this without considering how mm/ksm.c's
640          * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
641          */
642         if (PageSwapCache(page))
643                 ClearPageSwapCache(page);
644         /*
645          * Unlikely, but PagePrivate and page_private could potentially
646          * contain information needed at hugetlb free page time.
647          */
648         if (!PageHuge(page)) {
649                 ClearPagePrivate(page);
650                 set_page_private(page, 0);
651         }
652
653         /*
654          * If any waiters have accumulated on the new page then
655          * wake them up.
656          */
657         if (PageWriteback(newpage))
658                 end_page_writeback(newpage);
659
660         copy_page_owner(page, newpage);
661
662         mem_cgroup_migrate(page, newpage);
663 }
664 EXPORT_SYMBOL(migrate_page_states);
665
666 void migrate_page_copy(struct page *newpage, struct page *page)
667 {
668         if (PageHuge(page) || PageTransHuge(page))
669                 copy_huge_page(newpage, page);
670         else
671                 copy_highpage(newpage, page);
672
673         migrate_page_states(newpage, page);
674 }
675 EXPORT_SYMBOL(migrate_page_copy);
676
677 /************************************************************
678  *                    Migration functions
679  ***********************************************************/
680
681 /*
682  * Common logic to directly migrate a single LRU page suitable for
683  * pages that do not use PagePrivate/PagePrivate2.
684  *
685  * Pages are locked upon entry and exit.
686  */
687 int migrate_page(struct address_space *mapping,
688                 struct page *newpage, struct page *page,
689                 enum migrate_mode mode)
690 {
691         int rc;
692
693         BUG_ON(PageWriteback(page));    /* Writeback must be complete */
694
695         rc = migrate_page_move_mapping(mapping, newpage, page, mode, 0);
696
697         if (rc != MIGRATEPAGE_SUCCESS)
698                 return rc;
699
700         if (mode != MIGRATE_SYNC_NO_COPY)
701                 migrate_page_copy(newpage, page);
702         else
703                 migrate_page_states(newpage, page);
704         return MIGRATEPAGE_SUCCESS;
705 }
706 EXPORT_SYMBOL(migrate_page);
707
708 #ifdef CONFIG_BLOCK
709 /* Returns true if all buffers are successfully locked */
710 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
711                                                         enum migrate_mode mode)
712 {
713         struct buffer_head *bh = head;
714
715         /* Simple case, sync compaction */
716         if (mode != MIGRATE_ASYNC) {
717                 do {
718                         lock_buffer(bh);
719                         bh = bh->b_this_page;
720
721                 } while (bh != head);
722
723                 return true;
724         }
725
726         /* async case, we cannot block on lock_buffer so use trylock_buffer */
727         do {
728                 if (!trylock_buffer(bh)) {
729                         /*
730                          * We failed to lock the buffer and cannot stall in
731                          * async migration. Release the taken locks
732                          */
733                         struct buffer_head *failed_bh = bh;
734                         bh = head;
735                         while (bh != failed_bh) {
736                                 unlock_buffer(bh);
737                                 bh = bh->b_this_page;
738                         }
739                         return false;
740                 }
741
742                 bh = bh->b_this_page;
743         } while (bh != head);
744         return true;
745 }
746
747 static int __buffer_migrate_page(struct address_space *mapping,
748                 struct page *newpage, struct page *page, enum migrate_mode mode,
749                 bool check_refs)
750 {
751         struct buffer_head *bh, *head;
752         int rc;
753         int expected_count;
754
755         if (!page_has_buffers(page))
756                 return migrate_page(mapping, newpage, page, mode);
757
758         /* Check whether page does not have extra refs before we do more work */
759         expected_count = expected_page_refs(page);
760         if (page_count(page) != expected_count)
761                 return -EAGAIN;
762
763         head = page_buffers(page);
764         if (!buffer_migrate_lock_buffers(head, mode))
765                 return -EAGAIN;
766
767         if (check_refs) {
768                 bool busy;
769                 bool invalidated = false;
770
771 recheck_buffers:
772                 busy = false;
773                 spin_lock(&mapping->private_lock);
774                 bh = head;
775                 do {
776                         if (atomic_read(&bh->b_count)) {
777                                 busy = true;
778                                 break;
779                         }
780                         bh = bh->b_this_page;
781                 } while (bh != head);
782                 spin_unlock(&mapping->private_lock);
783                 if (busy) {
784                         if (invalidated) {
785                                 rc = -EAGAIN;
786                                 goto unlock_buffers;
787                         }
788                         invalidate_bh_lrus();
789                         invalidated = true;
790                         goto recheck_buffers;
791                 }
792         }
793
794         rc = migrate_page_move_mapping(mapping, newpage, page, mode, 0);
795         if (rc != MIGRATEPAGE_SUCCESS)
796                 goto unlock_buffers;
797
798         ClearPagePrivate(page);
799         set_page_private(newpage, page_private(page));
800         set_page_private(page, 0);
801         put_page(page);
802         get_page(newpage);
803
804         bh = head;
805         do {
806                 set_bh_page(bh, newpage, bh_offset(bh));
807                 bh = bh->b_this_page;
808
809         } while (bh != head);
810
811         SetPagePrivate(newpage);
812
813         if (mode != MIGRATE_SYNC_NO_COPY)
814                 migrate_page_copy(newpage, page);
815         else
816                 migrate_page_states(newpage, page);
817
818         rc = MIGRATEPAGE_SUCCESS;
819 unlock_buffers:
820         bh = head;
821         do {
822                 unlock_buffer(bh);
823                 bh = bh->b_this_page;
824
825         } while (bh != head);
826
827         return rc;
828 }
829
830 /*
831  * Migration function for pages with buffers. This function can only be used
832  * if the underlying filesystem guarantees that no other references to "page"
833  * exist. For example attached buffer heads are accessed only under page lock.
834  */
835 int buffer_migrate_page(struct address_space *mapping,
836                 struct page *newpage, struct page *page, enum migrate_mode mode)
837 {
838         return __buffer_migrate_page(mapping, newpage, page, mode, false);
839 }
840 EXPORT_SYMBOL(buffer_migrate_page);
841
842 /*
843  * Same as above except that this variant is more careful and checks that there
844  * are also no buffer head references. This function is the right one for
845  * mappings where buffer heads are directly looked up and referenced (such as
846  * block device mappings).
847  */
848 int buffer_migrate_page_norefs(struct address_space *mapping,
849                 struct page *newpage, struct page *page, enum migrate_mode mode)
850 {
851         return __buffer_migrate_page(mapping, newpage, page, mode, true);
852 }
853 #endif
854
855 /*
856  * Writeback a page to clean the dirty state
857  */
858 static int writeout(struct address_space *mapping, struct page *page)
859 {
860         struct writeback_control wbc = {
861                 .sync_mode = WB_SYNC_NONE,
862                 .nr_to_write = 1,
863                 .range_start = 0,
864                 .range_end = LLONG_MAX,
865                 .for_reclaim = 1
866         };
867         int rc;
868
869         if (!mapping->a_ops->writepage)
870                 /* No write method for the address space */
871                 return -EINVAL;
872
873         if (!clear_page_dirty_for_io(page))
874                 /* Someone else already triggered a write */
875                 return -EAGAIN;
876
877         /*
878          * A dirty page may imply that the underlying filesystem has
879          * the page on some queue. So the page must be clean for
880          * migration. Writeout may mean we loose the lock and the
881          * page state is no longer what we checked for earlier.
882          * At this point we know that the migration attempt cannot
883          * be successful.
884          */
885         remove_migration_ptes(page, page, false);
886
887         rc = mapping->a_ops->writepage(page, &wbc);
888
889         if (rc != AOP_WRITEPAGE_ACTIVATE)
890                 /* unlocked. Relock */
891                 lock_page(page);
892
893         return (rc < 0) ? -EIO : -EAGAIN;
894 }
895
896 /*
897  * Default handling if a filesystem does not provide a migration function.
898  */
899 static int fallback_migrate_page(struct address_space *mapping,
900         struct page *newpage, struct page *page, enum migrate_mode mode)
901 {
902         if (PageDirty(page)) {
903                 /* Only writeback pages in full synchronous migration */
904                 switch (mode) {
905                 case MIGRATE_SYNC:
906                 case MIGRATE_SYNC_NO_COPY:
907                         break;
908                 default:
909                         return -EBUSY;
910                 }
911                 return writeout(mapping, page);
912         }
913
914         /*
915          * Buffers may be managed in a filesystem specific way.
916          * We must have no buffers or drop them.
917          */
918         if (page_has_private(page) &&
919             !try_to_release_page(page, GFP_KERNEL))
920                 return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
921
922         return migrate_page(mapping, newpage, page, mode);
923 }
924
925 /*
926  * Move a page to a newly allocated page
927  * The page is locked and all ptes have been successfully removed.
928  *
929  * The new page will have replaced the old page if this function
930  * is successful.
931  *
932  * Return value:
933  *   < 0 - error code
934  *  MIGRATEPAGE_SUCCESS - success
935  */
936 static int move_to_new_page(struct page *newpage, struct page *page,
937                                 enum migrate_mode mode)
938 {
939         struct address_space *mapping;
940         int rc = -EAGAIN;
941         bool is_lru = !__PageMovable(page);
942
943         VM_BUG_ON_PAGE(!PageLocked(page), page);
944         VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
945
946         mapping = page_mapping(page);
947
948         if (likely(is_lru)) {
949                 if (!mapping)
950                         rc = migrate_page(mapping, newpage, page, mode);
951                 else if (mapping->a_ops->migratepage)
952                         /*
953                          * Most pages have a mapping and most filesystems
954                          * provide a migratepage callback. Anonymous pages
955                          * are part of swap space which also has its own
956                          * migratepage callback. This is the most common path
957                          * for page migration.
958                          */
959                         rc = mapping->a_ops->migratepage(mapping, newpage,
960                                                         page, mode);
961                 else
962                         rc = fallback_migrate_page(mapping, newpage,
963                                                         page, mode);
964         } else {
965                 /*
966                  * In case of non-lru page, it could be released after
967                  * isolation step. In that case, we shouldn't try migration.
968                  */
969                 VM_BUG_ON_PAGE(!PageIsolated(page), page);
970                 if (!PageMovable(page)) {
971                         rc = MIGRATEPAGE_SUCCESS;
972                         __ClearPageIsolated(page);
973                         goto out;
974                 }
975
976                 rc = mapping->a_ops->migratepage(mapping, newpage,
977                                                 page, mode);
978                 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
979                         !PageIsolated(page));
980         }
981
982         /*
983          * When successful, old pagecache page->mapping must be cleared before
984          * page is freed; but stats require that PageAnon be left as PageAnon.
985          */
986         if (rc == MIGRATEPAGE_SUCCESS) {
987                 if (__PageMovable(page)) {
988                         VM_BUG_ON_PAGE(!PageIsolated(page), page);
989
990                         /*
991                          * We clear PG_movable under page_lock so any compactor
992                          * cannot try to migrate this page.
993                          */
994                         __ClearPageIsolated(page);
995                 }
996
997                 /*
998                  * Anonymous and movable page->mapping will be cleard by
999                  * free_pages_prepare so don't reset it here for keeping
1000                  * the type to work PageAnon, for example.
1001                  */
1002                 if (!PageMappingFlags(page))
1003                         page->mapping = NULL;
1004         }
1005 out:
1006         return rc;
1007 }
1008
1009 static int __unmap_and_move(struct page *page, struct page *newpage,
1010                                 int force, enum migrate_mode mode)
1011 {
1012         int rc = -EAGAIN;
1013         int page_was_mapped = 0;
1014         struct anon_vma *anon_vma = NULL;
1015         bool is_lru = !__PageMovable(page);
1016
1017         if (!trylock_page(page)) {
1018                 if (!force || mode == MIGRATE_ASYNC)
1019                         goto out;
1020
1021                 /*
1022                  * It's not safe for direct compaction to call lock_page.
1023                  * For example, during page readahead pages are added locked
1024                  * to the LRU. Later, when the IO completes the pages are
1025                  * marked uptodate and unlocked. However, the queueing
1026                  * could be merging multiple pages for one bio (e.g.
1027                  * mpage_readpages). If an allocation happens for the
1028                  * second or third page, the process can end up locking
1029                  * the same page twice and deadlocking. Rather than
1030                  * trying to be clever about what pages can be locked,
1031                  * avoid the use of lock_page for direct compaction
1032                  * altogether.
1033                  */
1034                 if (current->flags & PF_MEMALLOC)
1035                         goto out;
1036
1037                 lock_page(page);
1038         }
1039
1040         if (PageWriteback(page)) {
1041                 /*
1042                  * Only in the case of a full synchronous migration is it
1043                  * necessary to wait for PageWriteback. In the async case,
1044                  * the retry loop is too short and in the sync-light case,
1045                  * the overhead of stalling is too much
1046                  */
1047                 switch (mode) {
1048                 case MIGRATE_SYNC:
1049                 case MIGRATE_SYNC_NO_COPY:
1050                         break;
1051                 default:
1052                         rc = -EBUSY;
1053                         goto out_unlock;
1054                 }
1055                 if (!force)
1056                         goto out_unlock;
1057                 wait_on_page_writeback(page);
1058         }
1059
1060         /*
1061          * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
1062          * we cannot notice that anon_vma is freed while we migrates a page.
1063          * This get_anon_vma() delays freeing anon_vma pointer until the end
1064          * of migration. File cache pages are no problem because of page_lock()
1065          * File Caches may use write_page() or lock_page() in migration, then,
1066          * just care Anon page here.
1067          *
1068          * Only page_get_anon_vma() understands the subtleties of
1069          * getting a hold on an anon_vma from outside one of its mms.
1070          * But if we cannot get anon_vma, then we won't need it anyway,
1071          * because that implies that the anon page is no longer mapped
1072          * (and cannot be remapped so long as we hold the page lock).
1073          */
1074         if (PageAnon(page) && !PageKsm(page))
1075                 anon_vma = page_get_anon_vma(page);
1076
1077         /*
1078          * Block others from accessing the new page when we get around to
1079          * establishing additional references. We are usually the only one
1080          * holding a reference to newpage at this point. We used to have a BUG
1081          * here if trylock_page(newpage) fails, but would like to allow for
1082          * cases where there might be a race with the previous use of newpage.
1083          * This is much like races on refcount of oldpage: just don't BUG().
1084          */
1085         if (unlikely(!trylock_page(newpage)))
1086                 goto out_unlock;
1087
1088         if (unlikely(!is_lru)) {
1089                 rc = move_to_new_page(newpage, page, mode);
1090                 goto out_unlock_both;
1091         }
1092
1093         /*
1094          * Corner case handling:
1095          * 1. When a new swap-cache page is read into, it is added to the LRU
1096          * and treated as swapcache but it has no rmap yet.
1097          * Calling try_to_unmap() against a page->mapping==NULL page will
1098          * trigger a BUG.  So handle it here.
1099          * 2. An orphaned page (see truncate_complete_page) might have
1100          * fs-private metadata. The page can be picked up due to memory
1101          * offlining.  Everywhere else except page reclaim, the page is
1102          * invisible to the vm, so the page can not be migrated.  So try to
1103          * free the metadata, so the page can be freed.
1104          */
1105         if (!page->mapping) {
1106                 VM_BUG_ON_PAGE(PageAnon(page), page);
1107                 if (page_has_private(page)) {
1108                         try_to_free_buffers(page);
1109                         goto out_unlock_both;
1110                 }
1111         } else if (page_mapped(page)) {
1112                 /* Establish migration ptes */
1113                 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1114                                 page);
1115                 try_to_unmap(page,
1116                         TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1117                 page_was_mapped = 1;
1118         }
1119
1120         if (!page_mapped(page))
1121                 rc = move_to_new_page(newpage, page, mode);
1122
1123         if (page_was_mapped)
1124                 remove_migration_ptes(page,
1125                         rc == MIGRATEPAGE_SUCCESS ? newpage : page, false);
1126
1127 out_unlock_both:
1128         unlock_page(newpage);
1129 out_unlock:
1130         /* Drop an anon_vma reference if we took one */
1131         if (anon_vma)
1132                 put_anon_vma(anon_vma);
1133         unlock_page(page);
1134 out:
1135         /*
1136          * If migration is successful, decrease refcount of the newpage
1137          * which will not free the page because new page owner increased
1138          * refcounter. As well, if it is LRU page, add the page to LRU
1139          * list in here. Use the old state of the isolated source page to
1140          * determine if we migrated a LRU page. newpage was already unlocked
1141          * and possibly modified by its owner - don't rely on the page
1142          * state.
1143          */
1144         if (rc == MIGRATEPAGE_SUCCESS) {
1145                 if (unlikely(!is_lru))
1146                         put_page(newpage);
1147                 else
1148                         putback_lru_page(newpage);
1149         }
1150
1151         return rc;
1152 }
1153
1154 /*
1155  * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move().  Work
1156  * around it.
1157  */
1158 #if defined(CONFIG_ARM) && \
1159         defined(GCC_VERSION) && GCC_VERSION < 40900 && GCC_VERSION >= 40700
1160 #define ICE_noinline noinline
1161 #else
1162 #define ICE_noinline
1163 #endif
1164
1165 /*
1166  * Obtain the lock on page, remove all ptes and migrate the page
1167  * to the newly allocated page in newpage.
1168  */
1169 static ICE_noinline int unmap_and_move(new_page_t get_new_page,
1170                                    free_page_t put_new_page,
1171                                    unsigned long private, struct page *page,
1172                                    int force, enum migrate_mode mode,
1173                                    enum migrate_reason reason)
1174 {
1175         int rc = MIGRATEPAGE_SUCCESS;
1176         struct page *newpage;
1177
1178         if (!thp_migration_supported() && PageTransHuge(page))
1179                 return -ENOMEM;
1180
1181         newpage = get_new_page(page, private);
1182         if (!newpage)
1183                 return -ENOMEM;
1184
1185         if (page_count(page) == 1) {
1186                 /* page was freed from under us. So we are done. */
1187                 ClearPageActive(page);
1188                 ClearPageUnevictable(page);
1189                 if (unlikely(__PageMovable(page))) {
1190                         lock_page(page);
1191                         if (!PageMovable(page))
1192                                 __ClearPageIsolated(page);
1193                         unlock_page(page);
1194                 }
1195                 if (put_new_page)
1196                         put_new_page(newpage, private);
1197                 else
1198                         put_page(newpage);
1199                 goto out;
1200         }
1201
1202         rc = __unmap_and_move(page, newpage, force, mode);
1203         if (rc == MIGRATEPAGE_SUCCESS)
1204                 set_page_owner_migrate_reason(newpage, reason);
1205
1206 out:
1207         if (rc != -EAGAIN) {
1208                 /*
1209                  * A page that has been migrated has all references
1210                  * removed and will be freed. A page that has not been
1211                  * migrated will have kepts its references and be
1212                  * restored.
1213                  */
1214                 list_del(&page->lru);
1215
1216                 /*
1217                  * Compaction can migrate also non-LRU pages which are
1218                  * not accounted to NR_ISOLATED_*. They can be recognized
1219                  * as __PageMovable
1220                  */
1221                 if (likely(!__PageMovable(page)))
1222                         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON +
1223                                         page_is_file_cache(page), -hpage_nr_pages(page));
1224         }
1225
1226         /*
1227          * If migration is successful, releases reference grabbed during
1228          * isolation. Otherwise, restore the page to right list unless
1229          * we want to retry.
1230          */
1231         if (rc == MIGRATEPAGE_SUCCESS) {
1232                 put_page(page);
1233                 if (reason == MR_MEMORY_FAILURE) {
1234                         /*
1235                          * Set PG_HWPoison on just freed page
1236                          * intentionally. Although it's rather weird,
1237                          * it's how HWPoison flag works at the moment.
1238                          */
1239                         if (set_hwpoison_free_buddy_page(page))
1240                                 num_poisoned_pages_inc();
1241                 }
1242         } else {
1243                 if (rc != -EAGAIN) {
1244                         if (likely(!__PageMovable(page))) {
1245                                 putback_lru_page(page);
1246                                 goto put_new;
1247                         }
1248
1249                         lock_page(page);
1250                         if (PageMovable(page))
1251                                 putback_movable_page(page);
1252                         else
1253                                 __ClearPageIsolated(page);
1254                         unlock_page(page);
1255                         put_page(page);
1256                 }
1257 put_new:
1258                 if (put_new_page)
1259                         put_new_page(newpage, private);
1260                 else
1261                         put_page(newpage);
1262         }
1263
1264         return rc;
1265 }
1266
1267 /*
1268  * Counterpart of unmap_and_move_page() for hugepage migration.
1269  *
1270  * This function doesn't wait the completion of hugepage I/O
1271  * because there is no race between I/O and migration for hugepage.
1272  * Note that currently hugepage I/O occurs only in direct I/O
1273  * where no lock is held and PG_writeback is irrelevant,
1274  * and writeback status of all subpages are counted in the reference
1275  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1276  * under direct I/O, the reference of the head page is 512 and a bit more.)
1277  * This means that when we try to migrate hugepage whose subpages are
1278  * doing direct I/O, some references remain after try_to_unmap() and
1279  * hugepage migration fails without data corruption.
1280  *
1281  * There is also no race when direct I/O is issued on the page under migration,
1282  * because then pte is replaced with migration swap entry and direct I/O code
1283  * will wait in the page fault for migration to complete.
1284  */
1285 static int unmap_and_move_huge_page(new_page_t get_new_page,
1286                                 free_page_t put_new_page, unsigned long private,
1287                                 struct page *hpage, int force,
1288                                 enum migrate_mode mode, int reason)
1289 {
1290         int rc = -EAGAIN;
1291         int page_was_mapped = 0;
1292         struct page *new_hpage;
1293         struct anon_vma *anon_vma = NULL;
1294
1295         /*
1296          * Migratability of hugepages depends on architectures and their size.
1297          * This check is necessary because some callers of hugepage migration
1298          * like soft offline and memory hotremove don't walk through page
1299          * tables or check whether the hugepage is pmd-based or not before
1300          * kicking migration.
1301          */
1302         if (!hugepage_migration_supported(page_hstate(hpage))) {
1303                 putback_active_hugepage(hpage);
1304                 return -ENOSYS;
1305         }
1306
1307         new_hpage = get_new_page(hpage, private);
1308         if (!new_hpage)
1309                 return -ENOMEM;
1310
1311         if (!trylock_page(hpage)) {
1312                 if (!force)
1313                         goto out;
1314                 switch (mode) {
1315                 case MIGRATE_SYNC:
1316                 case MIGRATE_SYNC_NO_COPY:
1317                         break;
1318                 default:
1319                         goto out;
1320                 }
1321                 lock_page(hpage);
1322         }
1323
1324         if (PageAnon(hpage))
1325                 anon_vma = page_get_anon_vma(hpage);
1326
1327         if (unlikely(!trylock_page(new_hpage)))
1328                 goto put_anon;
1329
1330         if (page_mapped(hpage)) {
1331                 try_to_unmap(hpage,
1332                         TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
1333                 page_was_mapped = 1;
1334         }
1335
1336         if (!page_mapped(hpage))
1337                 rc = move_to_new_page(new_hpage, hpage, mode);
1338
1339         if (page_was_mapped)
1340                 remove_migration_ptes(hpage,
1341                         rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false);
1342
1343         unlock_page(new_hpage);
1344
1345 put_anon:
1346         if (anon_vma)
1347                 put_anon_vma(anon_vma);
1348
1349         if (rc == MIGRATEPAGE_SUCCESS) {
1350                 move_hugetlb_state(hpage, new_hpage, reason);
1351                 put_new_page = NULL;
1352         }
1353
1354         unlock_page(hpage);
1355 out:
1356         if (rc != -EAGAIN)
1357                 putback_active_hugepage(hpage);
1358
1359         /*
1360          * If migration was not successful and there's a freeing callback, use
1361          * it.  Otherwise, put_page() will drop the reference grabbed during
1362          * isolation.
1363          */
1364         if (put_new_page)
1365                 put_new_page(new_hpage, private);
1366         else
1367                 putback_active_hugepage(new_hpage);
1368
1369         return rc;
1370 }
1371
1372 /*
1373  * migrate_pages - migrate the pages specified in a list, to the free pages
1374  *                 supplied as the target for the page migration
1375  *
1376  * @from:               The list of pages to be migrated.
1377  * @get_new_page:       The function used to allocate free pages to be used
1378  *                      as the target of the page migration.
1379  * @put_new_page:       The function used to free target pages if migration
1380  *                      fails, or NULL if no special handling is necessary.
1381  * @private:            Private data to be passed on to get_new_page()
1382  * @mode:               The migration mode that specifies the constraints for
1383  *                      page migration, if any.
1384  * @reason:             The reason for page migration.
1385  *
1386  * The function returns after 10 attempts or if no pages are movable any more
1387  * because the list has become empty or no retryable pages exist any more.
1388  * The caller should call putback_movable_pages() to return pages to the LRU
1389  * or free list only if ret != 0.
1390  *
1391  * Returns the number of pages that were not migrated, or an error code.
1392  */
1393 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1394                 free_page_t put_new_page, unsigned long private,
1395                 enum migrate_mode mode, int reason)
1396 {
1397         int retry = 1;
1398         int nr_failed = 0;
1399         int nr_succeeded = 0;
1400         int pass = 0;
1401         struct page *page;
1402         struct page *page2;
1403         int swapwrite = current->flags & PF_SWAPWRITE;
1404         int rc;
1405
1406         if (!swapwrite)
1407                 current->flags |= PF_SWAPWRITE;
1408
1409         for(pass = 0; pass < 10 && retry; pass++) {
1410                 retry = 0;
1411
1412                 list_for_each_entry_safe(page, page2, from, lru) {
1413 retry:
1414                         cond_resched();
1415
1416                         if (PageHuge(page))
1417                                 rc = unmap_and_move_huge_page(get_new_page,
1418                                                 put_new_page, private, page,
1419                                                 pass > 2, mode, reason);
1420                         else
1421                                 rc = unmap_and_move(get_new_page, put_new_page,
1422                                                 private, page, pass > 2, mode,
1423                                                 reason);
1424
1425                         switch(rc) {
1426                         case -ENOMEM:
1427                                 /*
1428                                  * THP migration might be unsupported or the
1429                                  * allocation could've failed so we should
1430                                  * retry on the same page with the THP split
1431                                  * to base pages.
1432                                  *
1433                                  * Head page is retried immediately and tail
1434                                  * pages are added to the tail of the list so
1435                                  * we encounter them after the rest of the list
1436                                  * is processed.
1437                                  */
1438                                 if (PageTransHuge(page) && !PageHuge(page)) {
1439                                         lock_page(page);
1440                                         rc = split_huge_page_to_list(page, from);
1441                                         unlock_page(page);
1442                                         if (!rc) {
1443                                                 list_safe_reset_next(page, page2, lru);
1444                                                 goto retry;
1445                                         }
1446                                 }
1447                                 nr_failed++;
1448                                 goto out;
1449                         case -EAGAIN:
1450                                 retry++;
1451                                 break;
1452                         case MIGRATEPAGE_SUCCESS:
1453                                 nr_succeeded++;
1454                                 break;
1455                         default:
1456                                 /*
1457                                  * Permanent failure (-EBUSY, -ENOSYS, etc.):
1458                                  * unlike -EAGAIN case, the failed page is
1459                                  * removed from migration page list and not
1460                                  * retried in the next outer loop.
1461                                  */
1462                                 nr_failed++;
1463                                 break;
1464                         }
1465                 }
1466         }
1467         nr_failed += retry;
1468         rc = nr_failed;
1469 out:
1470         if (nr_succeeded)
1471                 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1472         if (nr_failed)
1473                 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1474         trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
1475
1476         if (!swapwrite)
1477                 current->flags &= ~PF_SWAPWRITE;
1478
1479         return rc;
1480 }
1481
1482 #ifdef CONFIG_NUMA
1483
1484 static int store_status(int __user *status, int start, int value, int nr)
1485 {
1486         while (nr-- > 0) {
1487                 if (put_user(value, status + start))
1488                         return -EFAULT;
1489                 start++;
1490         }
1491
1492         return 0;
1493 }
1494
1495 static int do_move_pages_to_node(struct mm_struct *mm,
1496                 struct list_head *pagelist, int node)
1497 {
1498         int err;
1499
1500         if (list_empty(pagelist))
1501                 return 0;
1502
1503         err = migrate_pages(pagelist, alloc_new_node_page, NULL, node,
1504                         MIGRATE_SYNC, MR_SYSCALL);
1505         if (err)
1506                 putback_movable_pages(pagelist);
1507         return err;
1508 }
1509
1510 /*
1511  * Resolves the given address to a struct page, isolates it from the LRU and
1512  * puts it to the given pagelist.
1513  * Returns -errno if the page cannot be found/isolated or 0 when it has been
1514  * queued or the page doesn't need to be migrated because it is already on
1515  * the target node
1516  */
1517 static int add_page_for_migration(struct mm_struct *mm, unsigned long addr,
1518                 int node, struct list_head *pagelist, bool migrate_all)
1519 {
1520         struct vm_area_struct *vma;
1521         struct page *page;
1522         unsigned int follflags;
1523         int err;
1524
1525         down_read(&mm->mmap_sem);
1526         err = -EFAULT;
1527         vma = find_vma(mm, addr);
1528         if (!vma || addr < vma->vm_start || !vma_migratable(vma))
1529                 goto out;
1530
1531         /* FOLL_DUMP to ignore special (like zero) pages */
1532         follflags = FOLL_GET | FOLL_DUMP;
1533         page = follow_page(vma, addr, follflags);
1534
1535         err = PTR_ERR(page);
1536         if (IS_ERR(page))
1537                 goto out;
1538
1539         err = -ENOENT;
1540         if (!page)
1541                 goto out;
1542
1543         err = 0;
1544         if (page_to_nid(page) == node)
1545                 goto out_putpage;
1546
1547         err = -EACCES;
1548         if (page_mapcount(page) > 1 && !migrate_all)
1549                 goto out_putpage;
1550
1551         if (PageHuge(page)) {
1552                 if (PageHead(page)) {
1553                         isolate_huge_page(page, pagelist);
1554                         err = 0;
1555                 }
1556         } else {
1557                 struct page *head;
1558
1559                 head = compound_head(page);
1560                 err = isolate_lru_page(head);
1561                 if (err)
1562                         goto out_putpage;
1563
1564                 err = 0;
1565                 list_add_tail(&head->lru, pagelist);
1566                 mod_node_page_state(page_pgdat(head),
1567                         NR_ISOLATED_ANON + page_is_file_cache(head),
1568                         hpage_nr_pages(head));
1569         }
1570 out_putpage:
1571         /*
1572          * Either remove the duplicate refcount from
1573          * isolate_lru_page() or drop the page ref if it was
1574          * not isolated.
1575          */
1576         put_page(page);
1577 out:
1578         up_read(&mm->mmap_sem);
1579         return err;
1580 }
1581
1582 /*
1583  * Migrate an array of page address onto an array of nodes and fill
1584  * the corresponding array of status.
1585  */
1586 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1587                          unsigned long nr_pages,
1588                          const void __user * __user *pages,
1589                          const int __user *nodes,
1590                          int __user *status, int flags)
1591 {
1592         int current_node = NUMA_NO_NODE;
1593         LIST_HEAD(pagelist);
1594         int start, i;
1595         int err = 0, err1;
1596
1597         migrate_prep();
1598
1599         for (i = start = 0; i < nr_pages; i++) {
1600                 const void __user *p;
1601                 unsigned long addr;
1602                 int node;
1603
1604                 err = -EFAULT;
1605                 if (get_user(p, pages + i))
1606                         goto out_flush;
1607                 if (get_user(node, nodes + i))
1608                         goto out_flush;
1609                 addr = (unsigned long)p;
1610
1611                 err = -ENODEV;
1612                 if (node < 0 || node >= MAX_NUMNODES)
1613                         goto out_flush;
1614                 if (!node_state(node, N_MEMORY))
1615                         goto out_flush;
1616
1617                 err = -EACCES;
1618                 if (!node_isset(node, task_nodes))
1619                         goto out_flush;
1620
1621                 if (current_node == NUMA_NO_NODE) {
1622                         current_node = node;
1623                         start = i;
1624                 } else if (node != current_node) {
1625                         err = do_move_pages_to_node(mm, &pagelist, current_node);
1626                         if (err)
1627                                 goto out;
1628                         err = store_status(status, start, current_node, i - start);
1629                         if (err)
1630                                 goto out;
1631                         start = i;
1632                         current_node = node;
1633                 }
1634
1635                 /*
1636                  * Errors in the page lookup or isolation are not fatal and we simply
1637                  * report them via status
1638                  */
1639                 err = add_page_for_migration(mm, addr, current_node,
1640                                 &pagelist, flags & MPOL_MF_MOVE_ALL);
1641                 if (!err)
1642                         continue;
1643
1644                 err = store_status(status, i, err, 1);
1645                 if (err)
1646                         goto out_flush;
1647
1648                 err = do_move_pages_to_node(mm, &pagelist, current_node);
1649                 if (err)
1650                         goto out;
1651                 if (i > start) {
1652                         err = store_status(status, start, current_node, i - start);
1653                         if (err)
1654                                 goto out;
1655                 }
1656                 current_node = NUMA_NO_NODE;
1657         }
1658 out_flush:
1659         if (list_empty(&pagelist))
1660                 return err;
1661
1662         /* Make sure we do not overwrite the existing error */
1663         err1 = do_move_pages_to_node(mm, &pagelist, current_node);
1664         if (!err1)
1665                 err1 = store_status(status, start, current_node, i - start);
1666         if (!err)
1667                 err = err1;
1668 out:
1669         return err;
1670 }
1671
1672 /*
1673  * Determine the nodes of an array of pages and store it in an array of status.
1674  */
1675 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1676                                 const void __user **pages, int *status)
1677 {
1678         unsigned long i;
1679
1680         down_read(&mm->mmap_sem);
1681
1682         for (i = 0; i < nr_pages; i++) {
1683                 unsigned long addr = (unsigned long)(*pages);
1684                 struct vm_area_struct *vma;
1685                 struct page *page;
1686                 int err = -EFAULT;
1687
1688                 vma = find_vma(mm, addr);
1689                 if (!vma || addr < vma->vm_start)
1690                         goto set_status;
1691
1692                 /* FOLL_DUMP to ignore special (like zero) pages */
1693                 page = follow_page(vma, addr, FOLL_DUMP);
1694
1695                 err = PTR_ERR(page);
1696                 if (IS_ERR(page))
1697                         goto set_status;
1698
1699                 err = page ? page_to_nid(page) : -ENOENT;
1700 set_status:
1701                 *status = err;
1702
1703                 pages++;
1704                 status++;
1705         }
1706
1707         up_read(&mm->mmap_sem);
1708 }
1709
1710 /*
1711  * Determine the nodes of a user array of pages and store it in
1712  * a user array of status.
1713  */
1714 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1715                          const void __user * __user *pages,
1716                          int __user *status)
1717 {
1718 #define DO_PAGES_STAT_CHUNK_NR 16
1719         const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1720         int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1721
1722         while (nr_pages) {
1723                 unsigned long chunk_nr;
1724
1725                 chunk_nr = nr_pages;
1726                 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1727                         chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1728
1729                 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1730                         break;
1731
1732                 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1733
1734                 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1735                         break;
1736
1737                 pages += chunk_nr;
1738                 status += chunk_nr;
1739                 nr_pages -= chunk_nr;
1740         }
1741         return nr_pages ? -EFAULT : 0;
1742 }
1743
1744 /*
1745  * Move a list of pages in the address space of the currently executing
1746  * process.
1747  */
1748 static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
1749                              const void __user * __user *pages,
1750                              const int __user *nodes,
1751                              int __user *status, int flags)
1752 {
1753         struct task_struct *task;
1754         struct mm_struct *mm;
1755         int err;
1756         nodemask_t task_nodes;
1757
1758         /* Check flags */
1759         if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1760                 return -EINVAL;
1761
1762         if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1763                 return -EPERM;
1764
1765         /* Find the mm_struct */
1766         rcu_read_lock();
1767         task = pid ? find_task_by_vpid(pid) : current;
1768         if (!task) {
1769                 rcu_read_unlock();
1770                 return -ESRCH;
1771         }
1772         get_task_struct(task);
1773
1774         /*
1775          * Check if this process has the right to modify the specified
1776          * process. Use the regular "ptrace_may_access()" checks.
1777          */
1778         if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1779                 rcu_read_unlock();
1780                 err = -EPERM;
1781                 goto out;
1782         }
1783         rcu_read_unlock();
1784
1785         err = security_task_movememory(task);
1786         if (err)
1787                 goto out;
1788
1789         task_nodes = cpuset_mems_allowed(task);
1790         mm = get_task_mm(task);
1791         put_task_struct(task);
1792
1793         if (!mm)
1794                 return -EINVAL;
1795
1796         if (nodes)
1797                 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1798                                     nodes, status, flags);
1799         else
1800                 err = do_pages_stat(mm, nr_pages, pages, status);
1801
1802         mmput(mm);
1803         return err;
1804
1805 out:
1806         put_task_struct(task);
1807         return err;
1808 }
1809
1810 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1811                 const void __user * __user *, pages,
1812                 const int __user *, nodes,
1813                 int __user *, status, int, flags)
1814 {
1815         return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1816 }
1817
1818 #ifdef CONFIG_COMPAT
1819 COMPAT_SYSCALL_DEFINE6(move_pages, pid_t, pid, compat_ulong_t, nr_pages,
1820                        compat_uptr_t __user *, pages32,
1821                        const int __user *, nodes,
1822                        int __user *, status,
1823                        int, flags)
1824 {
1825         const void __user * __user *pages;
1826         int i;
1827
1828         pages = compat_alloc_user_space(nr_pages * sizeof(void *));
1829         for (i = 0; i < nr_pages; i++) {
1830                 compat_uptr_t p;
1831
1832                 if (get_user(p, pages32 + i) ||
1833                         put_user(compat_ptr(p), pages + i))
1834                         return -EFAULT;
1835         }
1836         return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
1837 }
1838 #endif /* CONFIG_COMPAT */
1839
1840 #ifdef CONFIG_NUMA_BALANCING
1841 /*
1842  * Returns true if this is a safe migration target node for misplaced NUMA
1843  * pages. Currently it only checks the watermarks which crude
1844  */
1845 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1846                                    unsigned long nr_migrate_pages)
1847 {
1848         int z;
1849
1850         for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1851                 struct zone *zone = pgdat->node_zones + z;
1852
1853                 if (!populated_zone(zone))
1854                         continue;
1855
1856                 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1857                 if (!zone_watermark_ok(zone, 0,
1858                                        high_wmark_pages(zone) +
1859                                        nr_migrate_pages,
1860                                        0, 0))
1861                         continue;
1862                 return true;
1863         }
1864         return false;
1865 }
1866
1867 static struct page *alloc_misplaced_dst_page(struct page *page,
1868                                            unsigned long data)
1869 {
1870         int nid = (int) data;
1871         struct page *newpage;
1872
1873         newpage = __alloc_pages_node(nid,
1874                                          (GFP_HIGHUSER_MOVABLE |
1875                                           __GFP_THISNODE | __GFP_NOMEMALLOC |
1876                                           __GFP_NORETRY | __GFP_NOWARN) &
1877                                          ~__GFP_RECLAIM, 0);
1878
1879         return newpage;
1880 }
1881
1882 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
1883 {
1884         int page_lru;
1885
1886         VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
1887
1888         /* Avoid migrating to a node that is nearly full */
1889         if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
1890                 return 0;
1891
1892         if (isolate_lru_page(page))
1893                 return 0;
1894
1895         /*
1896          * migrate_misplaced_transhuge_page() skips page migration's usual
1897          * check on page_count(), so we must do it here, now that the page
1898          * has been isolated: a GUP pin, or any other pin, prevents migration.
1899          * The expected page count is 3: 1 for page's mapcount and 1 for the
1900          * caller's pin and 1 for the reference taken by isolate_lru_page().
1901          */
1902         if (PageTransHuge(page) && page_count(page) != 3) {
1903                 putback_lru_page(page);
1904                 return 0;
1905         }
1906
1907         page_lru = page_is_file_cache(page);
1908         mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru,
1909                                 hpage_nr_pages(page));
1910
1911         /*
1912          * Isolating the page has taken another reference, so the
1913          * caller's reference can be safely dropped without the page
1914          * disappearing underneath us during migration.
1915          */
1916         put_page(page);
1917         return 1;
1918 }
1919
1920 bool pmd_trans_migrating(pmd_t pmd)
1921 {
1922         struct page *page = pmd_page(pmd);
1923         return PageLocked(page);
1924 }
1925
1926 /*
1927  * Attempt to migrate a misplaced page to the specified destination
1928  * node. Caller is expected to have an elevated reference count on
1929  * the page that will be dropped by this function before returning.
1930  */
1931 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
1932                            int node)
1933 {
1934         pg_data_t *pgdat = NODE_DATA(node);
1935         int isolated;
1936         int nr_remaining;
1937         LIST_HEAD(migratepages);
1938
1939         /*
1940          * Don't migrate file pages that are mapped in multiple processes
1941          * with execute permissions as they are probably shared libraries.
1942          */
1943         if (page_mapcount(page) != 1 && page_is_file_cache(page) &&
1944             (vma->vm_flags & VM_EXEC))
1945                 goto out;
1946
1947         /*
1948          * Also do not migrate dirty pages as not all filesystems can move
1949          * dirty pages in MIGRATE_ASYNC mode which is a waste of cycles.
1950          */
1951         if (page_is_file_cache(page) && PageDirty(page))
1952                 goto out;
1953
1954         isolated = numamigrate_isolate_page(pgdat, page);
1955         if (!isolated)
1956                 goto out;
1957
1958         list_add(&page->lru, &migratepages);
1959         nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
1960                                      NULL, node, MIGRATE_ASYNC,
1961                                      MR_NUMA_MISPLACED);
1962         if (nr_remaining) {
1963                 if (!list_empty(&migratepages)) {
1964                         list_del(&page->lru);
1965                         dec_node_page_state(page, NR_ISOLATED_ANON +
1966                                         page_is_file_cache(page));
1967                         putback_lru_page(page);
1968                 }
1969                 isolated = 0;
1970         } else
1971                 count_vm_numa_event(NUMA_PAGE_MIGRATE);
1972         BUG_ON(!list_empty(&migratepages));
1973         return isolated;
1974
1975 out:
1976         put_page(page);
1977         return 0;
1978 }
1979 #endif /* CONFIG_NUMA_BALANCING */
1980
1981 #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1982 /*
1983  * Migrates a THP to a given target node. page must be locked and is unlocked
1984  * before returning.
1985  */
1986 int migrate_misplaced_transhuge_page(struct mm_struct *mm,
1987                                 struct vm_area_struct *vma,
1988                                 pmd_t *pmd, pmd_t entry,
1989                                 unsigned long address,
1990                                 struct page *page, int node)
1991 {
1992         spinlock_t *ptl;
1993         pg_data_t *pgdat = NODE_DATA(node);
1994         int isolated = 0;
1995         struct page *new_page = NULL;
1996         int page_lru = page_is_file_cache(page);
1997         unsigned long start = address & HPAGE_PMD_MASK;
1998
1999         new_page = alloc_pages_node(node,
2000                 (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),
2001                 HPAGE_PMD_ORDER);
2002         if (!new_page)
2003                 goto out_fail;
2004         prep_transhuge_page(new_page);
2005
2006         isolated = numamigrate_isolate_page(pgdat, page);
2007         if (!isolated) {
2008                 put_page(new_page);
2009                 goto out_fail;
2010         }
2011
2012         /* Prepare a page as a migration target */
2013         __SetPageLocked(new_page);
2014         if (PageSwapBacked(page))
2015                 __SetPageSwapBacked(new_page);
2016
2017         /* anon mapping, we can simply copy page->mapping to the new page: */
2018         new_page->mapping = page->mapping;
2019         new_page->index = page->index;
2020         /* flush the cache before copying using the kernel virtual address */
2021         flush_cache_range(vma, start, start + HPAGE_PMD_SIZE);
2022         migrate_page_copy(new_page, page);
2023         WARN_ON(PageLRU(new_page));
2024
2025         /* Recheck the target PMD */
2026         ptl = pmd_lock(mm, pmd);
2027         if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) {
2028                 spin_unlock(ptl);
2029
2030                 /* Reverse changes made by migrate_page_copy() */
2031                 if (TestClearPageActive(new_page))
2032                         SetPageActive(page);
2033                 if (TestClearPageUnevictable(new_page))
2034                         SetPageUnevictable(page);
2035
2036                 unlock_page(new_page);
2037                 put_page(new_page);             /* Free it */
2038
2039                 /* Retake the callers reference and putback on LRU */
2040                 get_page(page);
2041                 putback_lru_page(page);
2042                 mod_node_page_state(page_pgdat(page),
2043                          NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
2044
2045                 goto out_unlock;
2046         }
2047
2048         entry = mk_huge_pmd(new_page, vma->vm_page_prot);
2049         entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
2050
2051         /*
2052          * Overwrite the old entry under pagetable lock and establish
2053          * the new PTE. Any parallel GUP will either observe the old
2054          * page blocking on the page lock, block on the page table
2055          * lock or observe the new page. The SetPageUptodate on the
2056          * new page and page_add_new_anon_rmap guarantee the copy is
2057          * visible before the pagetable update.
2058          */
2059         page_add_anon_rmap(new_page, vma, start, true);
2060         /*
2061          * At this point the pmd is numa/protnone (i.e. non present) and the TLB
2062          * has already been flushed globally.  So no TLB can be currently
2063          * caching this non present pmd mapping.  There's no need to clear the
2064          * pmd before doing set_pmd_at(), nor to flush the TLB after
2065          * set_pmd_at().  Clearing the pmd here would introduce a race
2066          * condition against MADV_DONTNEED, because MADV_DONTNEED only holds the
2067          * mmap_sem for reading.  If the pmd is set to NULL at any given time,
2068          * MADV_DONTNEED won't wait on the pmd lock and it'll skip clearing this
2069          * pmd.
2070          */
2071         set_pmd_at(mm, start, pmd, entry);
2072         update_mmu_cache_pmd(vma, address, &entry);
2073
2074         page_ref_unfreeze(page, 2);
2075         mlock_migrate_page(new_page, page);
2076         page_remove_rmap(page, true);
2077         set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED);
2078
2079         spin_unlock(ptl);
2080
2081         /* Take an "isolate" reference and put new page on the LRU. */
2082         get_page(new_page);
2083         putback_lru_page(new_page);
2084
2085         unlock_page(new_page);
2086         unlock_page(page);
2087         put_page(page);                 /* Drop the rmap reference */
2088         put_page(page);                 /* Drop the LRU isolation reference */
2089
2090         count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
2091         count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
2092
2093         mod_node_page_state(page_pgdat(page),
2094                         NR_ISOLATED_ANON + page_lru,
2095                         -HPAGE_PMD_NR);
2096         return isolated;
2097
2098 out_fail:
2099         count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
2100         ptl = pmd_lock(mm, pmd);
2101         if (pmd_same(*pmd, entry)) {
2102                 entry = pmd_modify(entry, vma->vm_page_prot);
2103                 set_pmd_at(mm, start, pmd, entry);
2104                 update_mmu_cache_pmd(vma, address, &entry);
2105         }
2106         spin_unlock(ptl);
2107
2108 out_unlock:
2109         unlock_page(page);
2110         put_page(page);
2111         return 0;
2112 }
2113 #endif /* CONFIG_NUMA_BALANCING */
2114
2115 #endif /* CONFIG_NUMA */
2116
2117 #if defined(CONFIG_MIGRATE_VMA_HELPER)
2118 struct migrate_vma {
2119         struct vm_area_struct   *vma;
2120         unsigned long           *dst;
2121         unsigned long           *src;
2122         unsigned long           cpages;
2123         unsigned long           npages;
2124         unsigned long           start;
2125         unsigned long           end;
2126 };
2127
2128 static int migrate_vma_collect_hole(unsigned long start,
2129                                     unsigned long end,
2130                                     struct mm_walk *walk)
2131 {
2132         struct migrate_vma *migrate = walk->private;
2133         unsigned long addr;
2134
2135         for (addr = start & PAGE_MASK; addr < end; addr += PAGE_SIZE) {
2136                 migrate->src[migrate->npages] = MIGRATE_PFN_MIGRATE;
2137                 migrate->dst[migrate->npages] = 0;
2138                 migrate->npages++;
2139                 migrate->cpages++;
2140         }
2141
2142         return 0;
2143 }
2144
2145 static int migrate_vma_collect_skip(unsigned long start,
2146                                     unsigned long end,
2147                                     struct mm_walk *walk)
2148 {
2149         struct migrate_vma *migrate = walk->private;
2150         unsigned long addr;
2151
2152         for (addr = start & PAGE_MASK; addr < end; addr += PAGE_SIZE) {
2153                 migrate->dst[migrate->npages] = 0;
2154                 migrate->src[migrate->npages++] = 0;
2155         }
2156
2157         return 0;
2158 }
2159
2160 static int migrate_vma_collect_pmd(pmd_t *pmdp,
2161                                    unsigned long start,
2162                                    unsigned long end,
2163                                    struct mm_walk *walk)
2164 {
2165         struct migrate_vma *migrate = walk->private;
2166         struct vm_area_struct *vma = walk->vma;
2167         struct mm_struct *mm = vma->vm_mm;
2168         unsigned long addr = start, unmapped = 0;
2169         spinlock_t *ptl;
2170         pte_t *ptep;
2171
2172 again:
2173         if (pmd_none(*pmdp))
2174                 return migrate_vma_collect_hole(start, end, walk);
2175
2176         if (pmd_trans_huge(*pmdp)) {
2177                 struct page *page;
2178
2179                 ptl = pmd_lock(mm, pmdp);
2180                 if (unlikely(!pmd_trans_huge(*pmdp))) {
2181                         spin_unlock(ptl);
2182                         goto again;
2183                 }
2184
2185                 page = pmd_page(*pmdp);
2186                 if (is_huge_zero_page(page)) {
2187                         spin_unlock(ptl);
2188                         split_huge_pmd(vma, pmdp, addr);
2189                         if (pmd_trans_unstable(pmdp))
2190                                 return migrate_vma_collect_skip(start, end,
2191                                                                 walk);
2192                 } else {
2193                         int ret;
2194
2195                         get_page(page);
2196                         spin_unlock(ptl);
2197                         if (unlikely(!trylock_page(page)))
2198                                 return migrate_vma_collect_skip(start, end,
2199                                                                 walk);
2200                         ret = split_huge_page(page);
2201                         unlock_page(page);
2202                         put_page(page);
2203                         if (ret)
2204                                 return migrate_vma_collect_skip(start, end,
2205                                                                 walk);
2206                         if (pmd_none(*pmdp))
2207                                 return migrate_vma_collect_hole(start, end,
2208                                                                 walk);
2209                 }
2210         }
2211
2212         if (unlikely(pmd_bad(*pmdp)))
2213                 return migrate_vma_collect_skip(start, end, walk);
2214
2215         ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2216         arch_enter_lazy_mmu_mode();
2217
2218         for (; addr < end; addr += PAGE_SIZE, ptep++) {
2219                 unsigned long mpfn, pfn;
2220                 struct page *page;
2221                 swp_entry_t entry;
2222                 pte_t pte;
2223
2224                 pte = *ptep;
2225                 pfn = pte_pfn(pte);
2226
2227                 if (pte_none(pte)) {
2228                         mpfn = MIGRATE_PFN_MIGRATE;
2229                         migrate->cpages++;
2230                         pfn = 0;
2231                         goto next;
2232                 }
2233
2234                 if (!pte_present(pte)) {
2235                         mpfn = pfn = 0;
2236
2237                         /*
2238                          * Only care about unaddressable device page special
2239                          * page table entry. Other special swap entries are not
2240                          * migratable, and we ignore regular swapped page.
2241                          */
2242                         entry = pte_to_swp_entry(pte);
2243                         if (!is_device_private_entry(entry))
2244                                 goto next;
2245
2246                         page = device_private_entry_to_page(entry);
2247                         mpfn = migrate_pfn(page_to_pfn(page))|
2248                                 MIGRATE_PFN_DEVICE | MIGRATE_PFN_MIGRATE;
2249                         if (is_write_device_private_entry(entry))
2250                                 mpfn |= MIGRATE_PFN_WRITE;
2251                 } else {
2252                         if (is_zero_pfn(pfn)) {
2253                                 mpfn = MIGRATE_PFN_MIGRATE;
2254                                 migrate->cpages++;
2255                                 pfn = 0;
2256                                 goto next;
2257                         }
2258                         page = _vm_normal_page(migrate->vma, addr, pte, true);
2259                         mpfn = migrate_pfn(pfn) | MIGRATE_PFN_MIGRATE;
2260                         mpfn |= pte_write(pte) ? MIGRATE_PFN_WRITE : 0;
2261                 }
2262
2263                 /* FIXME support THP */
2264                 if (!page || !page->mapping || PageTransCompound(page)) {
2265                         mpfn = pfn = 0;
2266                         goto next;
2267                 }
2268                 pfn = page_to_pfn(page);
2269
2270                 /*
2271                  * By getting a reference on the page we pin it and that blocks
2272                  * any kind of migration. Side effect is that it "freezes" the
2273                  * pte.
2274                  *
2275                  * We drop this reference after isolating the page from the lru
2276                  * for non device page (device page are not on the lru and thus
2277                  * can't be dropped from it).
2278                  */
2279                 get_page(page);
2280                 migrate->cpages++;
2281
2282                 /*
2283                  * Optimize for the common case where page is only mapped once
2284                  * in one process. If we can lock the page, then we can safely
2285                  * set up a special migration page table entry now.
2286                  */
2287                 if (trylock_page(page)) {
2288                         pte_t swp_pte;
2289
2290                         mpfn |= MIGRATE_PFN_LOCKED;
2291                         ptep_get_and_clear(mm, addr, ptep);
2292
2293                         /* Setup special migration page table entry */
2294                         entry = make_migration_entry(page, mpfn &
2295                                                      MIGRATE_PFN_WRITE);
2296                         swp_pte = swp_entry_to_pte(entry);
2297                         if (pte_soft_dirty(pte))
2298                                 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2299                         set_pte_at(mm, addr, ptep, swp_pte);
2300
2301                         /*
2302                          * This is like regular unmap: we remove the rmap and
2303                          * drop page refcount. Page won't be freed, as we took
2304                          * a reference just above.
2305                          */
2306                         page_remove_rmap(page, false);
2307                         put_page(page);
2308
2309                         if (pte_present(pte))
2310                                 unmapped++;
2311                 }
2312
2313 next:
2314                 migrate->dst[migrate->npages] = 0;
2315                 migrate->src[migrate->npages++] = mpfn;
2316         }
2317         arch_leave_lazy_mmu_mode();
2318         pte_unmap_unlock(ptep - 1, ptl);
2319
2320         /* Only flush the TLB if we actually modified any entries */
2321         if (unmapped)
2322                 flush_tlb_range(walk->vma, start, end);
2323
2324         return 0;
2325 }
2326
2327 /*
2328  * migrate_vma_collect() - collect pages over a range of virtual addresses
2329  * @migrate: migrate struct containing all migration information
2330  *
2331  * This will walk the CPU page table. For each virtual address backed by a
2332  * valid page, it updates the src array and takes a reference on the page, in
2333  * order to pin the page until we lock it and unmap it.
2334  */
2335 static void migrate_vma_collect(struct migrate_vma *migrate)
2336 {
2337         struct mmu_notifier_range range;
2338         struct mm_walk mm_walk;
2339
2340         mm_walk.pmd_entry = migrate_vma_collect_pmd;
2341         mm_walk.pte_entry = NULL;
2342         mm_walk.pte_hole = migrate_vma_collect_hole;
2343         mm_walk.hugetlb_entry = NULL;
2344         mm_walk.test_walk = NULL;
2345         mm_walk.vma = migrate->vma;
2346         mm_walk.mm = migrate->vma->vm_mm;
2347         mm_walk.private = migrate;
2348
2349         mmu_notifier_range_init(&range, mm_walk.mm, migrate->start,
2350                                 migrate->end);
2351         mmu_notifier_invalidate_range_start(&range);
2352         walk_page_range(migrate->start, migrate->end, &mm_walk);
2353         mmu_notifier_invalidate_range_end(&range);
2354
2355         migrate->end = migrate->start + (migrate->npages << PAGE_SHIFT);
2356 }
2357
2358 /*
2359  * migrate_vma_check_page() - check if page is pinned or not
2360  * @page: struct page to check
2361  *
2362  * Pinned pages cannot be migrated. This is the same test as in
2363  * migrate_page_move_mapping(), except that here we allow migration of a
2364  * ZONE_DEVICE page.
2365  */
2366 static bool migrate_vma_check_page(struct page *page)
2367 {
2368         /*
2369          * One extra ref because caller holds an extra reference, either from
2370          * isolate_lru_page() for a regular page, or migrate_vma_collect() for
2371          * a device page.
2372          */
2373         int extra = 1;
2374
2375         /*
2376          * FIXME support THP (transparent huge page), it is bit more complex to
2377          * check them than regular pages, because they can be mapped with a pmd
2378          * or with a pte (split pte mapping).
2379          */
2380         if (PageCompound(page))
2381                 return false;
2382
2383         /* Page from ZONE_DEVICE have one extra reference */
2384         if (is_zone_device_page(page)) {
2385                 /*
2386                  * Private page can never be pin as they have no valid pte and
2387                  * GUP will fail for those. Yet if there is a pending migration
2388                  * a thread might try to wait on the pte migration entry and
2389                  * will bump the page reference count. Sadly there is no way to
2390                  * differentiate a regular pin from migration wait. Hence to
2391                  * avoid 2 racing thread trying to migrate back to CPU to enter
2392                  * infinite loop (one stoping migration because the other is
2393                  * waiting on pte migration entry). We always return true here.
2394                  *
2395                  * FIXME proper solution is to rework migration_entry_wait() so
2396                  * it does not need to take a reference on page.
2397                  */
2398                 if (is_device_private_page(page))
2399                         return true;
2400
2401                 /*
2402                  * Only allow device public page to be migrated and account for
2403                  * the extra reference count imply by ZONE_DEVICE pages.
2404                  */
2405                 if (!is_device_public_page(page))
2406                         return false;
2407                 extra++;
2408         }
2409
2410         /* For file back page */
2411         if (page_mapping(page))
2412                 extra += 1 + page_has_private(page);
2413
2414         if ((page_count(page) - extra) > page_mapcount(page))
2415                 return false;
2416
2417         return true;
2418 }
2419
2420 /*
2421  * migrate_vma_prepare() - lock pages and isolate them from the lru
2422  * @migrate: migrate struct containing all migration information
2423  *
2424  * This locks pages that have been collected by migrate_vma_collect(). Once each
2425  * page is locked it is isolated from the lru (for non-device pages). Finally,
2426  * the ref taken by migrate_vma_collect() is dropped, as locked pages cannot be
2427  * migrated by concurrent kernel threads.
2428  */
2429 static void migrate_vma_prepare(struct migrate_vma *migrate)
2430 {
2431         const unsigned long npages = migrate->npages;
2432         const unsigned long start = migrate->start;
2433         unsigned long addr, i, restore = 0;
2434         bool allow_drain = true;
2435
2436         lru_add_drain();
2437
2438         for (i = 0; (i < npages) && migrate->cpages; i++) {
2439                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2440                 bool remap = true;
2441
2442                 if (!page)
2443                         continue;
2444
2445                 if (!(migrate->src[i] & MIGRATE_PFN_LOCKED)) {
2446                         /*
2447                          * Because we are migrating several pages there can be
2448                          * a deadlock between 2 concurrent migration where each
2449                          * are waiting on each other page lock.
2450                          *
2451                          * Make migrate_vma() a best effort thing and backoff
2452                          * for any page we can not lock right away.
2453                          */
2454                         if (!trylock_page(page)) {
2455                                 migrate->src[i] = 0;
2456                                 migrate->cpages--;
2457                                 put_page(page);
2458                                 continue;
2459                         }
2460                         remap = false;
2461                         migrate->src[i] |= MIGRATE_PFN_LOCKED;
2462                 }
2463
2464                 /* ZONE_DEVICE pages are not on LRU */
2465                 if (!is_zone_device_page(page)) {
2466                         if (!PageLRU(page) && allow_drain) {
2467                                 /* Drain CPU's pagevec */
2468                                 lru_add_drain_all();
2469                                 allow_drain = false;
2470                         }
2471
2472                         if (isolate_lru_page(page)) {
2473                                 if (remap) {
2474                                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2475                                         migrate->cpages--;
2476                                         restore++;
2477                                 } else {
2478                                         migrate->src[i] = 0;
2479                                         unlock_page(page);
2480                                         migrate->cpages--;
2481                                         put_page(page);
2482                                 }
2483                                 continue;
2484                         }
2485
2486                         /* Drop the reference we took in collect */
2487                         put_page(page);
2488                 }
2489
2490                 if (!migrate_vma_check_page(page)) {
2491                         if (remap) {
2492                                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2493                                 migrate->cpages--;
2494                                 restore++;
2495
2496                                 if (!is_zone_device_page(page)) {
2497                                         get_page(page);
2498                                         putback_lru_page(page);
2499                                 }
2500                         } else {
2501                                 migrate->src[i] = 0;
2502                                 unlock_page(page);
2503                                 migrate->cpages--;
2504
2505                                 if (!is_zone_device_page(page))
2506                                         putback_lru_page(page);
2507                                 else
2508                                         put_page(page);
2509                         }
2510                 }
2511         }
2512
2513         for (i = 0, addr = start; i < npages && restore; i++, addr += PAGE_SIZE) {
2514                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2515
2516                 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2517                         continue;
2518
2519                 remove_migration_pte(page, migrate->vma, addr, page);
2520
2521                 migrate->src[i] = 0;
2522                 unlock_page(page);
2523                 put_page(page);
2524                 restore--;
2525         }
2526 }
2527
2528 /*
2529  * migrate_vma_unmap() - replace page mapping with special migration pte entry
2530  * @migrate: migrate struct containing all migration information
2531  *
2532  * Replace page mapping (CPU page table pte) with a special migration pte entry
2533  * and check again if it has been pinned. Pinned pages are restored because we
2534  * cannot migrate them.
2535  *
2536  * This is the last step before we call the device driver callback to allocate
2537  * destination memory and copy contents of original page over to new page.
2538  */
2539 static void migrate_vma_unmap(struct migrate_vma *migrate)
2540 {
2541         int flags = TTU_MIGRATION | TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS;
2542         const unsigned long npages = migrate->npages;
2543         const unsigned long start = migrate->start;
2544         unsigned long addr, i, restore = 0;
2545
2546         for (i = 0; i < npages; i++) {
2547                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2548
2549                 if (!page || !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
2550                         continue;
2551
2552                 if (page_mapped(page)) {
2553                         try_to_unmap(page, flags);
2554                         if (page_mapped(page))
2555                                 goto restore;
2556                 }
2557
2558                 if (migrate_vma_check_page(page))
2559                         continue;
2560
2561 restore:
2562                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2563                 migrate->cpages--;
2564                 restore++;
2565         }
2566
2567         for (addr = start, i = 0; i < npages && restore; addr += PAGE_SIZE, i++) {
2568                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2569
2570                 if (!page || (migrate->src[i] & MIGRATE_PFN_MIGRATE))
2571                         continue;
2572
2573                 remove_migration_ptes(page, page, false);
2574
2575                 migrate->src[i] = 0;
2576                 unlock_page(page);
2577                 restore--;
2578
2579                 if (is_zone_device_page(page))
2580                         put_page(page);
2581                 else
2582                         putback_lru_page(page);
2583         }
2584 }
2585
2586 static void migrate_vma_insert_page(struct migrate_vma *migrate,
2587                                     unsigned long addr,
2588                                     struct page *page,
2589                                     unsigned long *src,
2590                                     unsigned long *dst)
2591 {
2592         struct vm_area_struct *vma = migrate->vma;
2593         struct mm_struct *mm = vma->vm_mm;
2594         struct mem_cgroup *memcg;
2595         bool flush = false;
2596         spinlock_t *ptl;
2597         pte_t entry;
2598         pgd_t *pgdp;
2599         p4d_t *p4dp;
2600         pud_t *pudp;
2601         pmd_t *pmdp;
2602         pte_t *ptep;
2603
2604         /* Only allow populating anonymous memory */
2605         if (!vma_is_anonymous(vma))
2606                 goto abort;
2607
2608         pgdp = pgd_offset(mm, addr);
2609         p4dp = p4d_alloc(mm, pgdp, addr);
2610         if (!p4dp)
2611                 goto abort;
2612         pudp = pud_alloc(mm, p4dp, addr);
2613         if (!pudp)
2614                 goto abort;
2615         pmdp = pmd_alloc(mm, pudp, addr);
2616         if (!pmdp)
2617                 goto abort;
2618
2619         if (pmd_trans_huge(*pmdp) || pmd_devmap(*pmdp))
2620                 goto abort;
2621
2622         /*
2623          * Use pte_alloc() instead of pte_alloc_map().  We can't run
2624          * pte_offset_map() on pmds where a huge pmd might be created
2625          * from a different thread.
2626          *
2627          * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
2628          * parallel threads are excluded by other means.
2629          *
2630          * Here we only have down_read(mmap_sem).
2631          */
2632         if (pte_alloc(mm, pmdp))
2633                 goto abort;
2634
2635         /* See the comment in pte_alloc_one_map() */
2636         if (unlikely(pmd_trans_unstable(pmdp)))
2637                 goto abort;
2638
2639         if (unlikely(anon_vma_prepare(vma)))
2640                 goto abort;
2641         if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
2642                 goto abort;
2643
2644         /*
2645          * The memory barrier inside __SetPageUptodate makes sure that
2646          * preceding stores to the page contents become visible before
2647          * the set_pte_at() write.
2648          */
2649         __SetPageUptodate(page);
2650
2651         if (is_zone_device_page(page)) {
2652                 if (is_device_private_page(page)) {
2653                         swp_entry_t swp_entry;
2654
2655                         swp_entry = make_device_private_entry(page, vma->vm_flags & VM_WRITE);
2656                         entry = swp_entry_to_pte(swp_entry);
2657                 } else if (is_device_public_page(page)) {
2658                         entry = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
2659                         if (vma->vm_flags & VM_WRITE)
2660                                 entry = pte_mkwrite(pte_mkdirty(entry));
2661                         entry = pte_mkdevmap(entry);
2662                 }
2663         } else {
2664                 entry = mk_pte(page, vma->vm_page_prot);
2665                 if (vma->vm_flags & VM_WRITE)
2666                         entry = pte_mkwrite(pte_mkdirty(entry));
2667         }
2668
2669         ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2670
2671         if (pte_present(*ptep)) {
2672                 unsigned long pfn = pte_pfn(*ptep);
2673
2674                 if (!is_zero_pfn(pfn)) {
2675                         pte_unmap_unlock(ptep, ptl);
2676                         mem_cgroup_cancel_charge(page, memcg, false);
2677                         goto abort;
2678                 }
2679                 flush = true;
2680         } else if (!pte_none(*ptep)) {
2681                 pte_unmap_unlock(ptep, ptl);
2682                 mem_cgroup_cancel_charge(page, memcg, false);
2683                 goto abort;
2684         }
2685
2686         /*
2687          * Check for usefaultfd but do not deliver the fault. Instead,
2688          * just back off.
2689          */
2690         if (userfaultfd_missing(vma)) {
2691                 pte_unmap_unlock(ptep, ptl);
2692                 mem_cgroup_cancel_charge(page, memcg, false);
2693                 goto abort;
2694         }
2695
2696         inc_mm_counter(mm, MM_ANONPAGES);
2697         page_add_new_anon_rmap(page, vma, addr, false);
2698         mem_cgroup_commit_charge(page, memcg, false, false);
2699         if (!is_zone_device_page(page))
2700                 lru_cache_add_active_or_unevictable(page, vma);
2701         get_page(page);
2702
2703         if (flush) {
2704                 flush_cache_page(vma, addr, pte_pfn(*ptep));
2705                 ptep_clear_flush_notify(vma, addr, ptep);
2706                 set_pte_at_notify(mm, addr, ptep, entry);
2707                 update_mmu_cache(vma, addr, ptep);
2708         } else {
2709                 /* No need to invalidate - it was non-present before */
2710                 set_pte_at(mm, addr, ptep, entry);
2711                 update_mmu_cache(vma, addr, ptep);
2712         }
2713
2714         pte_unmap_unlock(ptep, ptl);
2715         *src = MIGRATE_PFN_MIGRATE;
2716         return;
2717
2718 abort:
2719         *src &= ~MIGRATE_PFN_MIGRATE;
2720 }
2721
2722 /*
2723  * migrate_vma_pages() - migrate meta-data from src page to dst page
2724  * @migrate: migrate struct containing all migration information
2725  *
2726  * This migrates struct page meta-data from source struct page to destination
2727  * struct page. This effectively finishes the migration from source page to the
2728  * destination page.
2729  */
2730 static void migrate_vma_pages(struct migrate_vma *migrate)
2731 {
2732         const unsigned long npages = migrate->npages;
2733         const unsigned long start = migrate->start;
2734         struct mmu_notifier_range range;
2735         unsigned long addr, i;
2736         bool notified = false;
2737
2738         for (i = 0, addr = start; i < npages; addr += PAGE_SIZE, i++) {
2739                 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2740                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2741                 struct address_space *mapping;
2742                 int r;
2743
2744                 if (!newpage) {
2745                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2746                         continue;
2747                 }
2748
2749                 if (!page) {
2750                         if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE)) {
2751                                 continue;
2752                         }
2753                         if (!notified) {
2754                                 notified = true;
2755
2756                                 mmu_notifier_range_init(&range,
2757                                                         migrate->vma->vm_mm,
2758                                                         addr, migrate->end);
2759                                 mmu_notifier_invalidate_range_start(&range);
2760                         }
2761                         migrate_vma_insert_page(migrate, addr, newpage,
2762                                                 &migrate->src[i],
2763                                                 &migrate->dst[i]);
2764                         continue;
2765                 }
2766
2767                 mapping = page_mapping(page);
2768
2769                 if (is_zone_device_page(newpage)) {
2770                         if (is_device_private_page(newpage)) {
2771                                 /*
2772                                  * For now only support private anonymous when
2773                                  * migrating to un-addressable device memory.
2774                                  */
2775                                 if (mapping) {
2776                                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2777                                         continue;
2778                                 }
2779                         } else if (!is_device_public_page(newpage)) {
2780                                 /*
2781                                  * Other types of ZONE_DEVICE page are not
2782                                  * supported.
2783                                  */
2784                                 migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2785                                 continue;
2786                         }
2787                 }
2788
2789                 r = migrate_page(mapping, newpage, page, MIGRATE_SYNC_NO_COPY);
2790                 if (r != MIGRATEPAGE_SUCCESS)
2791                         migrate->src[i] &= ~MIGRATE_PFN_MIGRATE;
2792         }
2793
2794         /*
2795          * No need to double call mmu_notifier->invalidate_range() callback as
2796          * the above ptep_clear_flush_notify() inside migrate_vma_insert_page()
2797          * did already call it.
2798          */
2799         if (notified)
2800                 mmu_notifier_invalidate_range_only_end(&range);
2801 }
2802
2803 /*
2804  * migrate_vma_finalize() - restore CPU page table entry
2805  * @migrate: migrate struct containing all migration information
2806  *
2807  * This replaces the special migration pte entry with either a mapping to the
2808  * new page if migration was successful for that page, or to the original page
2809  * otherwise.
2810  *
2811  * This also unlocks the pages and puts them back on the lru, or drops the extra
2812  * refcount, for device pages.
2813  */
2814 static void migrate_vma_finalize(struct migrate_vma *migrate)
2815 {
2816         const unsigned long npages = migrate->npages;
2817         unsigned long i;
2818
2819         for (i = 0; i < npages; i++) {
2820                 struct page *newpage = migrate_pfn_to_page(migrate->dst[i]);
2821                 struct page *page = migrate_pfn_to_page(migrate->src[i]);
2822
2823                 if (!page) {
2824                         if (newpage) {
2825                                 unlock_page(newpage);
2826                                 put_page(newpage);
2827                         }
2828                         continue;
2829                 }
2830
2831                 if (!(migrate->src[i] & MIGRATE_PFN_MIGRATE) || !newpage) {
2832                         if (newpage) {
2833                                 unlock_page(newpage);
2834                                 put_page(newpage);
2835                         }
2836                         newpage = page;
2837                 }
2838
2839                 remove_migration_ptes(page, newpage, false);
2840                 unlock_page(page);
2841                 migrate->cpages--;
2842
2843                 if (is_zone_device_page(page))
2844                         put_page(page);
2845                 else
2846                         putback_lru_page(page);
2847
2848                 if (newpage != page) {
2849                         unlock_page(newpage);
2850                         if (is_zone_device_page(newpage))
2851                                 put_page(newpage);
2852                         else
2853                                 putback_lru_page(newpage);
2854                 }
2855         }
2856 }
2857
2858 /*
2859  * migrate_vma() - migrate a range of memory inside vma
2860  *
2861  * @ops: migration callback for allocating destination memory and copying
2862  * @vma: virtual memory area containing the range to be migrated
2863  * @start: start address of the range to migrate (inclusive)
2864  * @end: end address of the range to migrate (exclusive)
2865  * @src: array of hmm_pfn_t containing source pfns
2866  * @dst: array of hmm_pfn_t containing destination pfns
2867  * @private: pointer passed back to each of the callback
2868  * Returns: 0 on success, error code otherwise
2869  *
2870  * This function tries to migrate a range of memory virtual address range, using
2871  * callbacks to allocate and copy memory from source to destination. First it
2872  * collects all the pages backing each virtual address in the range, saving this
2873  * inside the src array. Then it locks those pages and unmaps them. Once the pages
2874  * are locked and unmapped, it checks whether each page is pinned or not. Pages
2875  * that aren't pinned have the MIGRATE_PFN_MIGRATE flag set (by this function)
2876  * in the corresponding src array entry. It then restores any pages that are
2877  * pinned, by remapping and unlocking those pages.
2878  *
2879  * At this point it calls the alloc_and_copy() callback. For documentation on
2880  * what is expected from that callback, see struct migrate_vma_ops comments in
2881  * include/linux/migrate.h
2882  *
2883  * After the alloc_and_copy() callback, this function goes over each entry in
2884  * the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
2885  * set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
2886  * then the function tries to migrate struct page information from the source
2887  * struct page to the destination struct page. If it fails to migrate the struct
2888  * page information, then it clears the MIGRATE_PFN_MIGRATE flag in the src
2889  * array.
2890  *
2891  * At this point all successfully migrated pages have an entry in the src
2892  * array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
2893  * array entry with MIGRATE_PFN_VALID flag set.
2894  *
2895  * It then calls the finalize_and_map() callback. See comments for "struct
2896  * migrate_vma_ops", in include/linux/migrate.h for details about
2897  * finalize_and_map() behavior.
2898  *
2899  * After the finalize_and_map() callback, for successfully migrated pages, this
2900  * function updates the CPU page table to point to new pages, otherwise it
2901  * restores the CPU page table to point to the original source pages.
2902  *
2903  * Function returns 0 after the above steps, even if no pages were migrated
2904  * (The function only returns an error if any of the arguments are invalid.)
2905  *
2906  * Both src and dst array must be big enough for (end - start) >> PAGE_SHIFT
2907  * unsigned long entries.
2908  */
2909 int migrate_vma(const struct migrate_vma_ops *ops,
2910                 struct vm_area_struct *vma,
2911                 unsigned long start,
2912                 unsigned long end,
2913                 unsigned long *src,
2914                 unsigned long *dst,
2915                 void *private)
2916 {
2917         struct migrate_vma migrate;
2918
2919         /* Sanity check the arguments */
2920         start &= PAGE_MASK;
2921         end &= PAGE_MASK;
2922         if (!vma || is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_SPECIAL) ||
2923                         vma_is_dax(vma))
2924                 return -EINVAL;
2925         if (start < vma->vm_start || start >= vma->vm_end)
2926                 return -EINVAL;
2927         if (end <= vma->vm_start || end > vma->vm_end)
2928                 return -EINVAL;
2929         if (!ops || !src || !dst || start >= end)
2930                 return -EINVAL;
2931
2932         memset(src, 0, sizeof(*src) * ((end - start) >> PAGE_SHIFT));
2933         migrate.src = src;
2934         migrate.dst = dst;
2935         migrate.start = start;
2936         migrate.npages = 0;
2937         migrate.cpages = 0;
2938         migrate.end = end;
2939         migrate.vma = vma;
2940
2941         /* Collect, and try to unmap source pages */
2942         migrate_vma_collect(&migrate);
2943         if (!migrate.cpages)
2944                 return 0;
2945
2946         /* Lock and isolate page */
2947         migrate_vma_prepare(&migrate);
2948         if (!migrate.cpages)
2949                 return 0;
2950
2951         /* Unmap pages */
2952         migrate_vma_unmap(&migrate);
2953         if (!migrate.cpages)
2954                 return 0;
2955
2956         /*
2957          * At this point pages are locked and unmapped, and thus they have
2958          * stable content and can safely be copied to destination memory that
2959          * is allocated by the callback.
2960          *
2961          * Note that migration can fail in migrate_vma_struct_page() for each
2962          * individual page.
2963          */
2964         ops->alloc_and_copy(vma, src, dst, start, end, private);
2965
2966         /* This does the real migration of struct page */
2967         migrate_vma_pages(&migrate);
2968
2969         ops->finalize_and_map(vma, src, dst, start, end, private);
2970
2971         /* Unlock and remap pages */
2972         migrate_vma_finalize(&migrate);
2973
2974         return 0;
2975 }
2976 EXPORT_SYMBOL(migrate_vma);
2977 #endif /* defined(MIGRATE_VMA_HELPER) */