OSDN Git Service

Merge "drm/msm/sde: add post_disable stage for phys encoder"
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / mm / migrate.c
1 /*
2  * Memory Migration functionality - linux/mm/migrate.c
3  *
4  * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
5  *
6  * Page migration was first developed in the context of the memory hotplug
7  * project. The main authors of the migration code are:
8  *
9  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
10  * Hirokazu Takahashi <taka@valinux.co.jp>
11  * Dave Hansen <haveblue@us.ibm.com>
12  * Christoph Lameter
13  */
14
15 #include <linux/migrate.h>
16 #include <linux/export.h>
17 #include <linux/swap.h>
18 #include <linux/swapops.h>
19 #include <linux/pagemap.h>
20 #include <linux/buffer_head.h>
21 #include <linux/mm_inline.h>
22 #include <linux/nsproxy.h>
23 #include <linux/pagevec.h>
24 #include <linux/ksm.h>
25 #include <linux/rmap.h>
26 #include <linux/topology.h>
27 #include <linux/cpu.h>
28 #include <linux/cpuset.h>
29 #include <linux/writeback.h>
30 #include <linux/mempolicy.h>
31 #include <linux/vmalloc.h>
32 #include <linux/security.h>
33 #include <linux/backing-dev.h>
34 #include <linux/compaction.h>
35 #include <linux/syscalls.h>
36 #include <linux/hugetlb.h>
37 #include <linux/hugetlb_cgroup.h>
38 #include <linux/gfp.h>
39 #include <linux/balloon_compaction.h>
40 #include <linux/mmu_notifier.h>
41 #include <linux/page_idle.h>
42 #include <linux/page_owner.h>
43 #include <linux/ptrace.h>
44
45 #include <asm/tlbflush.h>
46
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/migrate.h>
49
50 #include "internal.h"
51
52 /*
53  * migrate_prep() needs to be called before we start compiling a list of pages
54  * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
55  * undesirable, use migrate_prep_local()
56  */
57 int migrate_prep(void)
58 {
59         /*
60          * Clear the LRU lists so pages can be isolated.
61          * Note that pages may be moved off the LRU after we have
62          * drained them. Those pages will fail to migrate like other
63          * pages that may be busy.
64          */
65         lru_add_drain_all();
66
67         return 0;
68 }
69
70 /* Do the necessary work of migrate_prep but not if it involves other CPUs */
71 int migrate_prep_local(void)
72 {
73         lru_add_drain();
74
75         return 0;
76 }
77
78 int isolate_movable_page(struct page *page, isolate_mode_t mode)
79 {
80         struct address_space *mapping;
81
82         /*
83          * Avoid burning cycles with pages that are yet under __free_pages(),
84          * or just got freed under us.
85          *
86          * In case we 'win' a race for a movable page being freed under us and
87          * raise its refcount preventing __free_pages() from doing its job
88          * the put_page() at the end of this block will take care of
89          * release this page, thus avoiding a nasty leakage.
90          */
91         if (unlikely(!get_page_unless_zero(page)))
92                 goto out;
93
94         /*
95          * Check PageMovable before holding a PG_lock because page's owner
96          * assumes anybody doesn't touch PG_lock of newly allocated page
97          * so unconditionally grapping the lock ruins page's owner side.
98          */
99         if (unlikely(!__PageMovable(page)))
100                 goto out_putpage;
101         /*
102          * As movable pages are not isolated from LRU lists, concurrent
103          * compaction threads can race against page migration functions
104          * as well as race against the releasing a page.
105          *
106          * In order to avoid having an already isolated movable page
107          * being (wrongly) re-isolated while it is under migration,
108          * or to avoid attempting to isolate pages being released,
109          * lets be sure we have the page lock
110          * before proceeding with the movable page isolation steps.
111          */
112         if (unlikely(!trylock_page(page)))
113                 goto out_putpage;
114
115         if (!PageMovable(page) || PageIsolated(page))
116                 goto out_no_isolated;
117
118         mapping = page_mapping(page);
119         VM_BUG_ON_PAGE(!mapping, page);
120
121         if (!mapping->a_ops->isolate_page(page, mode))
122                 goto out_no_isolated;
123
124         /* Driver shouldn't use PG_isolated bit of page->flags */
125         WARN_ON_ONCE(PageIsolated(page));
126         __SetPageIsolated(page);
127         unlock_page(page);
128
129         return 0;
130
131 out_no_isolated:
132         unlock_page(page);
133 out_putpage:
134         put_page(page);
135 out:
136         return -EBUSY;
137 }
138
139 /* It should be called on page which is PG_movable */
140 void putback_movable_page(struct page *page)
141 {
142         struct address_space *mapping;
143
144         VM_BUG_ON_PAGE(!PageLocked(page), page);
145         VM_BUG_ON_PAGE(!PageMovable(page), page);
146         VM_BUG_ON_PAGE(!PageIsolated(page), page);
147
148         mapping = page_mapping(page);
149         mapping->a_ops->putback_page(page);
150         __ClearPageIsolated(page);
151 }
152
153 /*
154  * Put previously isolated pages back onto the appropriate lists
155  * from where they were once taken off for compaction/migration.
156  *
157  * This function shall be used whenever the isolated pageset has been
158  * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
159  * and isolate_huge_page().
160  */
161 void putback_movable_pages(struct list_head *l)
162 {
163         struct page *page;
164         struct page *page2;
165
166         list_for_each_entry_safe(page, page2, l, lru) {
167                 if (unlikely(PageHuge(page))) {
168                         putback_active_hugepage(page);
169                         continue;
170                 }
171                 list_del(&page->lru);
172                 dec_zone_page_state(page, NR_ISOLATED_ANON +
173                                 page_is_file_cache(page));
174                 /*
175                  * We isolated non-lru movable page so here we can use
176                  * __PageMovable because LRU page's mapping cannot have
177                  * PAGE_MAPPING_MOVABLE.
178                  */
179                 if (unlikely(__PageMovable(page))) {
180                         VM_BUG_ON_PAGE(!PageIsolated(page), page);
181                         lock_page(page);
182                         if (PageMovable(page))
183                                 putback_movable_page(page);
184                         else
185                                 __ClearPageIsolated(page);
186                         unlock_page(page);
187                         put_page(page);
188                 } else {
189                         putback_lru_page(page);
190                 }
191         }
192 }
193
194 /*
195  * Restore a potential migration pte to a working pte entry
196  */
197 static int remove_migration_pte(struct page *new, struct vm_area_struct *vma,
198                                  unsigned long addr, void *old)
199 {
200         struct mm_struct *mm = vma->vm_mm;
201         swp_entry_t entry;
202         pmd_t *pmd;
203         pte_t *ptep, pte;
204         spinlock_t *ptl;
205
206         if (unlikely(PageHuge(new))) {
207                 ptep = huge_pte_offset(mm, addr);
208                 if (!ptep)
209                         goto out;
210                 ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep);
211         } else {
212                 pmd = mm_find_pmd(mm, addr);
213                 if (!pmd)
214                         goto out;
215
216                 ptep = pte_offset_map(pmd, addr);
217
218                 /*
219                  * Peek to check is_swap_pte() before taking ptlock?  No, we
220                  * can race mremap's move_ptes(), which skips anon_vma lock.
221                  */
222
223                 ptl = pte_lockptr(mm, pmd);
224         }
225
226         spin_lock(ptl);
227         pte = *ptep;
228         if (!is_swap_pte(pte))
229                 goto unlock;
230
231         entry = pte_to_swp_entry(pte);
232
233         if (!is_migration_entry(entry) ||
234             migration_entry_to_page(entry) != old)
235                 goto unlock;
236
237         get_page(new);
238         pte = pte_mkold(mk_pte(new, vma->vm_page_prot));
239         if (pte_swp_soft_dirty(*ptep))
240                 pte = pte_mksoft_dirty(pte);
241
242         /* Recheck VMA as permissions can change since migration started  */
243         if (is_write_migration_entry(entry))
244                 pte = maybe_mkwrite(pte, vma);
245
246 #ifdef CONFIG_HUGETLB_PAGE
247         if (PageHuge(new)) {
248                 pte = pte_mkhuge(pte);
249                 pte = arch_make_huge_pte(pte, vma, new, 0);
250         }
251 #endif
252         flush_dcache_page(new);
253         set_pte_at(mm, addr, ptep, pte);
254
255         if (PageHuge(new)) {
256                 if (PageAnon(new))
257                         hugepage_add_anon_rmap(new, vma, addr);
258                 else
259                         page_dup_rmap(new);
260         } else if (PageAnon(new))
261                 page_add_anon_rmap(new, vma, addr);
262         else
263                 page_add_file_rmap(new);
264
265         if (vma->vm_flags & VM_LOCKED)
266                 mlock_vma_page(new);
267
268         /* No need to invalidate - it was non-present before */
269         update_mmu_cache(vma, addr, ptep);
270 unlock:
271         pte_unmap_unlock(ptep, ptl);
272 out:
273         return SWAP_AGAIN;
274 }
275
276 /*
277  * Get rid of all migration entries and replace them by
278  * references to the indicated page.
279  */
280 static void remove_migration_ptes(struct page *old, struct page *new)
281 {
282         struct rmap_walk_control rwc = {
283                 .rmap_one = remove_migration_pte,
284                 .arg = old,
285         };
286
287         rmap_walk(new, &rwc);
288 }
289
290 /*
291  * Something used the pte of a page under migration. We need to
292  * get to the page and wait until migration is finished.
293  * When we return from this function the fault will be retried.
294  */
295 void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
296                                 spinlock_t *ptl)
297 {
298         pte_t pte;
299         swp_entry_t entry;
300         struct page *page;
301
302         spin_lock(ptl);
303         pte = *ptep;
304         if (!is_swap_pte(pte))
305                 goto out;
306
307         entry = pte_to_swp_entry(pte);
308         if (!is_migration_entry(entry))
309                 goto out;
310
311         page = migration_entry_to_page(entry);
312
313         /*
314          * Once radix-tree replacement of page migration started, page_count
315          * *must* be zero. And, we don't want to call wait_on_page_locked()
316          * against a page without get_page().
317          * So, we use get_page_unless_zero(), here. Even failed, page fault
318          * will occur again.
319          */
320         if (!get_page_unless_zero(page))
321                 goto out;
322         pte_unmap_unlock(ptep, ptl);
323         wait_on_page_locked(page);
324         put_page(page);
325         return;
326 out:
327         pte_unmap_unlock(ptep, ptl);
328 }
329
330 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
331                                 unsigned long address)
332 {
333         spinlock_t *ptl = pte_lockptr(mm, pmd);
334         pte_t *ptep = pte_offset_map(pmd, address);
335         __migration_entry_wait(mm, ptep, ptl);
336 }
337
338 void migration_entry_wait_huge(struct vm_area_struct *vma,
339                 struct mm_struct *mm, pte_t *pte)
340 {
341         spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte);
342         __migration_entry_wait(mm, pte, ptl);
343 }
344
345 #ifdef CONFIG_BLOCK
346 /* Returns true if all buffers are successfully locked */
347 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
348                                                         enum migrate_mode mode)
349 {
350         struct buffer_head *bh = head;
351
352         /* Simple case, sync compaction */
353         if (mode != MIGRATE_ASYNC) {
354                 do {
355                         get_bh(bh);
356                         lock_buffer(bh);
357                         bh = bh->b_this_page;
358
359                 } while (bh != head);
360
361                 return true;
362         }
363
364         /* async case, we cannot block on lock_buffer so use trylock_buffer */
365         do {
366                 get_bh(bh);
367                 if (!trylock_buffer(bh)) {
368                         /*
369                          * We failed to lock the buffer and cannot stall in
370                          * async migration. Release the taken locks
371                          */
372                         struct buffer_head *failed_bh = bh;
373                         put_bh(failed_bh);
374                         bh = head;
375                         while (bh != failed_bh) {
376                                 unlock_buffer(bh);
377                                 put_bh(bh);
378                                 bh = bh->b_this_page;
379                         }
380                         return false;
381                 }
382
383                 bh = bh->b_this_page;
384         } while (bh != head);
385         return true;
386 }
387 #else
388 static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
389                                                         enum migrate_mode mode)
390 {
391         return true;
392 }
393 #endif /* CONFIG_BLOCK */
394
395 /*
396  * Replace the page in the mapping.
397  *
398  * The number of remaining references must be:
399  * 1 for anonymous pages without a mapping
400  * 2 for pages with a mapping
401  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
402  */
403 int migrate_page_move_mapping(struct address_space *mapping,
404                 struct page *newpage, struct page *page,
405                 struct buffer_head *head, enum migrate_mode mode,
406                 int extra_count)
407 {
408         struct zone *oldzone, *newzone;
409         int dirty;
410         int expected_count = 1 + extra_count;
411         void **pslot;
412
413         if (!mapping) {
414                 /* Anonymous page without mapping */
415                 if (page_count(page) != expected_count)
416                         return -EAGAIN;
417
418                 /* No turning back from here */
419                 set_page_memcg(newpage, page_memcg(page));
420                 newpage->index = page->index;
421                 newpage->mapping = page->mapping;
422                 if (PageSwapBacked(page))
423                         SetPageSwapBacked(newpage);
424
425                 return MIGRATEPAGE_SUCCESS;
426         }
427
428         oldzone = page_zone(page);
429         newzone = page_zone(newpage);
430
431         spin_lock_irq(&mapping->tree_lock);
432
433         pslot = radix_tree_lookup_slot(&mapping->page_tree,
434                                         page_index(page));
435
436         expected_count += 1 + page_has_private(page);
437         if (page_count(page) != expected_count ||
438                 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
439                 spin_unlock_irq(&mapping->tree_lock);
440                 return -EAGAIN;
441         }
442
443         if (!page_freeze_refs(page, expected_count)) {
444                 spin_unlock_irq(&mapping->tree_lock);
445                 return -EAGAIN;
446         }
447
448         /*
449          * In the async migration case of moving a page with buffers, lock the
450          * buffers using trylock before the mapping is moved. If the mapping
451          * was moved, we later failed to lock the buffers and could not move
452          * the mapping back due to an elevated page count, we would have to
453          * block waiting on other references to be dropped.
454          */
455         if (mode == MIGRATE_ASYNC && head &&
456                         !buffer_migrate_lock_buffers(head, mode)) {
457                 page_unfreeze_refs(page, expected_count);
458                 spin_unlock_irq(&mapping->tree_lock);
459                 return -EAGAIN;
460         }
461
462         /*
463          * Now we know that no one else is looking at the page:
464          * no turning back from here.
465          */
466         set_page_memcg(newpage, page_memcg(page));
467         newpage->index = page->index;
468         newpage->mapping = page->mapping;
469         if (PageSwapBacked(page))
470                 SetPageSwapBacked(newpage);
471
472         get_page(newpage);      /* add cache reference */
473         if (PageSwapCache(page)) {
474                 SetPageSwapCache(newpage);
475                 set_page_private(newpage, page_private(page));
476         }
477
478         /* Move dirty while page refs frozen and newpage not yet exposed */
479         dirty = PageDirty(page);
480         if (dirty) {
481                 ClearPageDirty(page);
482                 SetPageDirty(newpage);
483         }
484
485         radix_tree_replace_slot(pslot, newpage);
486
487         /*
488          * Drop cache reference from old page by unfreezing
489          * to one less reference.
490          * We know this isn't the last reference.
491          */
492         page_unfreeze_refs(page, expected_count - 1);
493
494         spin_unlock(&mapping->tree_lock);
495         /* Leave irq disabled to prevent preemption while updating stats */
496
497         /*
498          * If moved to a different zone then also account
499          * the page for that zone. Other VM counters will be
500          * taken care of when we establish references to the
501          * new page and drop references to the old page.
502          *
503          * Note that anonymous pages are accounted for
504          * via NR_FILE_PAGES and NR_ANON_PAGES if they
505          * are mapped to swap space.
506          */
507         if (newzone != oldzone) {
508                 __dec_zone_state(oldzone, NR_FILE_PAGES);
509                 __inc_zone_state(newzone, NR_FILE_PAGES);
510                 if (PageSwapBacked(page) && !PageSwapCache(page)) {
511                         __dec_zone_state(oldzone, NR_SHMEM);
512                         __inc_zone_state(newzone, NR_SHMEM);
513                 }
514                 if (dirty && mapping_cap_account_dirty(mapping)) {
515                         __dec_zone_state(oldzone, NR_FILE_DIRTY);
516                         __inc_zone_state(newzone, NR_FILE_DIRTY);
517                 }
518         }
519         local_irq_enable();
520
521         return MIGRATEPAGE_SUCCESS;
522 }
523 EXPORT_SYMBOL(migrate_page_move_mapping);
524
525 /*
526  * The expected number of remaining references is the same as that
527  * of migrate_page_move_mapping().
528  */
529 int migrate_huge_page_move_mapping(struct address_space *mapping,
530                                    struct page *newpage, struct page *page)
531 {
532         int expected_count;
533         void **pslot;
534
535         spin_lock_irq(&mapping->tree_lock);
536
537         pslot = radix_tree_lookup_slot(&mapping->page_tree,
538                                         page_index(page));
539
540         expected_count = 2 + page_has_private(page);
541         if (page_count(page) != expected_count ||
542                 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
543                 spin_unlock_irq(&mapping->tree_lock);
544                 return -EAGAIN;
545         }
546
547         if (!page_freeze_refs(page, expected_count)) {
548                 spin_unlock_irq(&mapping->tree_lock);
549                 return -EAGAIN;
550         }
551
552         set_page_memcg(newpage, page_memcg(page));
553         newpage->index = page->index;
554         newpage->mapping = page->mapping;
555         get_page(newpage);
556
557         radix_tree_replace_slot(pslot, newpage);
558
559         page_unfreeze_refs(page, expected_count - 1);
560
561         spin_unlock_irq(&mapping->tree_lock);
562         return MIGRATEPAGE_SUCCESS;
563 }
564
565 /*
566  * Gigantic pages are so large that we do not guarantee that page++ pointer
567  * arithmetic will work across the entire page.  We need something more
568  * specialized.
569  */
570 static void __copy_gigantic_page(struct page *dst, struct page *src,
571                                 int nr_pages)
572 {
573         int i;
574         struct page *dst_base = dst;
575         struct page *src_base = src;
576
577         for (i = 0; i < nr_pages; ) {
578                 cond_resched();
579                 copy_highpage(dst, src);
580
581                 i++;
582                 dst = mem_map_next(dst, dst_base, i);
583                 src = mem_map_next(src, src_base, i);
584         }
585 }
586
587 static void copy_huge_page(struct page *dst, struct page *src)
588 {
589         int i;
590         int nr_pages;
591
592         if (PageHuge(src)) {
593                 /* hugetlbfs page */
594                 struct hstate *h = page_hstate(src);
595                 nr_pages = pages_per_huge_page(h);
596
597                 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) {
598                         __copy_gigantic_page(dst, src, nr_pages);
599                         return;
600                 }
601         } else {
602                 /* thp page */
603                 BUG_ON(!PageTransHuge(src));
604                 nr_pages = hpage_nr_pages(src);
605         }
606
607         for (i = 0; i < nr_pages; i++) {
608                 cond_resched();
609                 copy_highpage(dst + i, src + i);
610         }
611 }
612
613 /*
614  * Copy the page to its new location
615  */
616 void migrate_page_copy(struct page *newpage, struct page *page)
617 {
618         int cpupid;
619
620         if (PageHuge(page) || PageTransHuge(page))
621                 copy_huge_page(newpage, page);
622         else
623                 copy_highpage(newpage, page);
624
625         if (PageError(page))
626                 SetPageError(newpage);
627         if (PageReferenced(page))
628                 SetPageReferenced(newpage);
629         if (PageUptodate(page))
630                 SetPageUptodate(newpage);
631         if (TestClearPageActive(page)) {
632                 VM_BUG_ON_PAGE(PageUnevictable(page), page);
633                 SetPageActive(newpage);
634         } else if (TestClearPageUnevictable(page))
635                 SetPageUnevictable(newpage);
636         if (PageChecked(page))
637                 SetPageChecked(newpage);
638         if (PageMappedToDisk(page))
639                 SetPageMappedToDisk(newpage);
640
641         /* Move dirty on pages not done by migrate_page_move_mapping() */
642         if (PageDirty(page))
643                 SetPageDirty(newpage);
644
645         if (page_is_young(page))
646                 set_page_young(newpage);
647         if (page_is_idle(page))
648                 set_page_idle(newpage);
649
650         /*
651          * Copy NUMA information to the new page, to prevent over-eager
652          * future migrations of this same page.
653          */
654         cpupid = page_cpupid_xchg_last(page, -1);
655         page_cpupid_xchg_last(newpage, cpupid);
656
657         ksm_migrate_page(newpage, page);
658         /*
659          * Please do not reorder this without considering how mm/ksm.c's
660          * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
661          */
662         if (PageSwapCache(page))
663                 ClearPageSwapCache(page);
664         ClearPagePrivate(page);
665         set_page_private(page, 0);
666
667         /*
668          * If any waiters have accumulated on the new page then
669          * wake them up.
670          */
671         if (PageWriteback(newpage))
672                 end_page_writeback(newpage);
673
674         copy_page_owner(page, newpage);
675 }
676 EXPORT_SYMBOL(migrate_page_copy);
677
678 /************************************************************
679  *                    Migration functions
680  ***********************************************************/
681
682 /*
683  * Common logic to directly migrate a single LRU page suitable for
684  * pages that do not use PagePrivate/PagePrivate2.
685  *
686  * Pages are locked upon entry and exit.
687  */
688 int migrate_page(struct address_space *mapping,
689                 struct page *newpage, struct page *page,
690                 enum migrate_mode mode)
691 {
692         int rc;
693
694         BUG_ON(PageWriteback(page));    /* Writeback must be complete */
695
696         rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0);
697
698         if (rc != MIGRATEPAGE_SUCCESS)
699                 return rc;
700
701         migrate_page_copy(newpage, page);
702         return MIGRATEPAGE_SUCCESS;
703 }
704 EXPORT_SYMBOL(migrate_page);
705
706 #ifdef CONFIG_BLOCK
707 /*
708  * Migration function for pages with buffers. This function can only be used
709  * if the underlying filesystem guarantees that no other references to "page"
710  * exist.
711  */
712 int buffer_migrate_page(struct address_space *mapping,
713                 struct page *newpage, struct page *page, enum migrate_mode mode)
714 {
715         struct buffer_head *bh, *head;
716         int rc;
717
718         if (!page_has_buffers(page))
719                 return migrate_page(mapping, newpage, page, mode);
720
721         head = page_buffers(page);
722
723         rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0);
724
725         if (rc != MIGRATEPAGE_SUCCESS)
726                 return rc;
727
728         /*
729          * In the async case, migrate_page_move_mapping locked the buffers
730          * with an IRQ-safe spinlock held. In the sync case, the buffers
731          * need to be locked now
732          */
733         if (mode != MIGRATE_ASYNC)
734                 BUG_ON(!buffer_migrate_lock_buffers(head, mode));
735
736         ClearPagePrivate(page);
737         set_page_private(newpage, page_private(page));
738         set_page_private(page, 0);
739         put_page(page);
740         get_page(newpage);
741
742         bh = head;
743         do {
744                 set_bh_page(bh, newpage, bh_offset(bh));
745                 bh = bh->b_this_page;
746
747         } while (bh != head);
748
749         SetPagePrivate(newpage);
750
751         migrate_page_copy(newpage, page);
752
753         bh = head;
754         do {
755                 unlock_buffer(bh);
756                 put_bh(bh);
757                 bh = bh->b_this_page;
758
759         } while (bh != head);
760
761         return MIGRATEPAGE_SUCCESS;
762 }
763 EXPORT_SYMBOL(buffer_migrate_page);
764 #endif
765
766 /*
767  * Writeback a page to clean the dirty state
768  */
769 static int writeout(struct address_space *mapping, struct page *page)
770 {
771         struct writeback_control wbc = {
772                 .sync_mode = WB_SYNC_NONE,
773                 .nr_to_write = 1,
774                 .range_start = 0,
775                 .range_end = LLONG_MAX,
776                 .for_reclaim = 1
777         };
778         int rc;
779
780         if (!mapping->a_ops->writepage)
781                 /* No write method for the address space */
782                 return -EINVAL;
783
784         if (!clear_page_dirty_for_io(page))
785                 /* Someone else already triggered a write */
786                 return -EAGAIN;
787
788         /*
789          * A dirty page may imply that the underlying filesystem has
790          * the page on some queue. So the page must be clean for
791          * migration. Writeout may mean we loose the lock and the
792          * page state is no longer what we checked for earlier.
793          * At this point we know that the migration attempt cannot
794          * be successful.
795          */
796         remove_migration_ptes(page, page);
797
798         rc = mapping->a_ops->writepage(page, &wbc);
799
800         if (rc != AOP_WRITEPAGE_ACTIVATE)
801                 /* unlocked. Relock */
802                 lock_page(page);
803
804         return (rc < 0) ? -EIO : -EAGAIN;
805 }
806
807 /*
808  * Default handling if a filesystem does not provide a migration function.
809  */
810 static int fallback_migrate_page(struct address_space *mapping,
811         struct page *newpage, struct page *page, enum migrate_mode mode)
812 {
813         if (PageDirty(page)) {
814                 /* Only writeback pages in full synchronous migration */
815                 if (mode != MIGRATE_SYNC)
816                         return -EBUSY;
817                 return writeout(mapping, page);
818         }
819
820         /*
821          * Buffers may be managed in a filesystem specific way.
822          * We must have no buffers or drop them.
823          */
824         if (page_has_private(page) &&
825             !try_to_release_page(page, GFP_KERNEL))
826                 return -EAGAIN;
827
828         return migrate_page(mapping, newpage, page, mode);
829 }
830
831 /*
832  * Move a page to a newly allocated page
833  * The page is locked and all ptes have been successfully removed.
834  *
835  * The new page will have replaced the old page if this function
836  * is successful.
837  *
838  * Return value:
839  *   < 0 - error code
840  *  MIGRATEPAGE_SUCCESS - success
841  */
842 static int move_to_new_page(struct page *newpage, struct page *page,
843                                 enum migrate_mode mode)
844 {
845         struct address_space *mapping;
846         int rc = -EAGAIN;
847         bool is_lru = !__PageMovable(page);
848
849         VM_BUG_ON_PAGE(!PageLocked(page), page);
850         VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
851
852         mapping = page_mapping(page);
853
854         if (likely(is_lru)) {
855                 if (!mapping)
856                         rc = migrate_page(mapping, newpage, page, mode);
857                 else if (mapping->a_ops->migratepage)
858                         /*
859                          * Most pages have a mapping and most filesystems
860                          * provide a migratepage callback. Anonymous pages
861                          * are part of swap space which also has its own
862                          * migratepage callback. This is the most common path
863                          * for page migration.
864                          */
865                         rc = mapping->a_ops->migratepage(mapping, newpage,
866                                                         page, mode);
867                 else
868                         rc = fallback_migrate_page(mapping, newpage,
869                                                         page, mode);
870         } else {
871                 /*
872                  * In case of non-lru page, it could be released after
873                  * isolation step. In that case, we shouldn't try migration.
874                  */
875                 VM_BUG_ON_PAGE(!PageIsolated(page), page);
876                 if (!PageMovable(page)) {
877                         rc = MIGRATEPAGE_SUCCESS;
878                         __ClearPageIsolated(page);
879                         goto out;
880                 }
881
882                 rc = mapping->a_ops->migratepage(mapping, newpage,
883                                                 page, mode);
884                 WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
885                         !PageIsolated(page));
886         }
887
888         /*
889          * When successful, old pagecache page->mapping must be cleared before
890          * page is freed; but stats require that PageAnon be left as PageAnon.
891          */
892         if (rc == MIGRATEPAGE_SUCCESS) {
893                 set_page_memcg(page, NULL);
894                 if (__PageMovable(page)) {
895                         VM_BUG_ON_PAGE(!PageIsolated(page), page);
896
897                         /*
898                          * We clear PG_movable under page_lock so any compactor
899                          * cannot try to migrate this page.
900                          */
901                         __ClearPageIsolated(page);
902                 }
903
904                 /*
905                  * Anonymous and movable page->mapping will be cleard by
906                  * free_pages_prepare so don't reset it here for keeping
907                  * the type to work PageAnon, for example.
908                  */
909                 if (!PageMappingFlags(page))
910                         page->mapping = NULL;
911         }
912 out:
913         return rc;
914 }
915
916 static int __unmap_and_move(struct page *page, struct page *newpage,
917                                 int force, enum migrate_mode mode)
918 {
919         int rc = -EAGAIN;
920         int page_was_mapped = 0;
921         struct anon_vma *anon_vma = NULL;
922         bool is_lru = !__PageMovable(page);
923
924         if (!trylock_page(page)) {
925                 if (!force || mode == MIGRATE_ASYNC)
926                         goto out;
927
928                 /*
929                  * It's not safe for direct compaction to call lock_page.
930                  * For example, during page readahead pages are added locked
931                  * to the LRU. Later, when the IO completes the pages are
932                  * marked uptodate and unlocked. However, the queueing
933                  * could be merging multiple pages for one bio (e.g.
934                  * mpage_readpages). If an allocation happens for the
935                  * second or third page, the process can end up locking
936                  * the same page twice and deadlocking. Rather than
937                  * trying to be clever about what pages can be locked,
938                  * avoid the use of lock_page for direct compaction
939                  * altogether.
940                  */
941                 if (current->flags & PF_MEMALLOC)
942                         goto out;
943
944                 lock_page(page);
945         }
946
947         if (PageWriteback(page)) {
948                 /*
949                  * Only in the case of a full synchronous migration is it
950                  * necessary to wait for PageWriteback. In the async case,
951                  * the retry loop is too short and in the sync-light case,
952                  * the overhead of stalling is too much
953                  */
954                 if (mode != MIGRATE_SYNC) {
955                         rc = -EBUSY;
956                         goto out_unlock;
957                 }
958                 if (!force)
959                         goto out_unlock;
960                 wait_on_page_writeback(page);
961         }
962
963         /*
964          * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
965          * we cannot notice that anon_vma is freed while we migrates a page.
966          * This get_anon_vma() delays freeing anon_vma pointer until the end
967          * of migration. File cache pages are no problem because of page_lock()
968          * File Caches may use write_page() or lock_page() in migration, then,
969          * just care Anon page here.
970          *
971          * Only page_get_anon_vma() understands the subtleties of
972          * getting a hold on an anon_vma from outside one of its mms.
973          * But if we cannot get anon_vma, then we won't need it anyway,
974          * because that implies that the anon page is no longer mapped
975          * (and cannot be remapped so long as we hold the page lock).
976          */
977         if (PageAnon(page) && !PageKsm(page))
978                 anon_vma = page_get_anon_vma(page);
979
980         /*
981          * Block others from accessing the new page when we get around to
982          * establishing additional references. We are usually the only one
983          * holding a reference to newpage at this point. We used to have a BUG
984          * here if trylock_page(newpage) fails, but would like to allow for
985          * cases where there might be a race with the previous use of newpage.
986          * This is much like races on refcount of oldpage: just don't BUG().
987          */
988         if (unlikely(!trylock_page(newpage)))
989                 goto out_unlock;
990
991         if (unlikely(!is_lru)) {
992                 rc = move_to_new_page(newpage, page, mode);
993                 goto out_unlock_both;
994         }
995
996         /*
997          * Corner case handling:
998          * 1. When a new swap-cache page is read into, it is added to the LRU
999          * and treated as swapcache but it has no rmap yet.
1000          * Calling try_to_unmap() against a page->mapping==NULL page will
1001          * trigger a BUG.  So handle it here.
1002          * 2. An orphaned page (see truncate_complete_page) might have
1003          * fs-private metadata. The page can be picked up due to memory
1004          * offlining.  Everywhere else except page reclaim, the page is
1005          * invisible to the vm, so the page can not be migrated.  So try to
1006          * free the metadata, so the page can be freed.
1007          */
1008         if (!page->mapping) {
1009                 VM_BUG_ON_PAGE(PageAnon(page), page);
1010                 if (page_has_private(page)) {
1011                         try_to_free_buffers(page);
1012                         goto out_unlock_both;
1013                 }
1014         } else if (page_mapped(page)) {
1015                 /* Establish migration ptes */
1016                 VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
1017                                 page);
1018                 try_to_unmap(page,
1019                         TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS, NULL);
1020                 page_was_mapped = 1;
1021         }
1022
1023         if (!page_mapped(page))
1024                 rc = move_to_new_page(newpage, page, mode);
1025
1026         if (page_was_mapped)
1027                 remove_migration_ptes(page,
1028                         rc == MIGRATEPAGE_SUCCESS ? newpage : page);
1029
1030 out_unlock_both:
1031         unlock_page(newpage);
1032 out_unlock:
1033         /* Drop an anon_vma reference if we took one */
1034         if (anon_vma)
1035                 put_anon_vma(anon_vma);
1036         unlock_page(page);
1037 out:
1038         /*
1039          * If migration is successful, decrease refcount of the newpage
1040          * which will not free the page because new page owner increased
1041          * refcounter. As well, if it is LRU page, add the page to LRU
1042          * list in here.
1043          */
1044         if (rc == MIGRATEPAGE_SUCCESS) {
1045                 if (unlikely(__PageMovable(newpage)))
1046                         put_page(newpage);
1047                 else
1048                         putback_lru_page(newpage);
1049         }
1050
1051         return rc;
1052 }
1053
1054 /*
1055  * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move().  Work
1056  * around it.
1057  */
1058 #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM)
1059 #define ICE_noinline noinline
1060 #else
1061 #define ICE_noinline
1062 #endif
1063
1064 /*
1065  * Obtain the lock on page, remove all ptes and migrate the page
1066  * to the newly allocated page in newpage.
1067  */
1068 static ICE_noinline int unmap_and_move(new_page_t get_new_page,
1069                                    free_page_t put_new_page,
1070                                    unsigned long private, struct page *page,
1071                                    int force, enum migrate_mode mode,
1072                                    enum migrate_reason reason)
1073 {
1074         int rc = MIGRATEPAGE_SUCCESS;
1075         int *result = NULL;
1076         struct page *newpage;
1077
1078         newpage = get_new_page(page, private, &result);
1079         if (!newpage)
1080                 return -ENOMEM;
1081
1082         if (page_count(page) == 1) {
1083                 /* page was freed from under us. So we are done. */
1084                 ClearPageActive(page);
1085                 ClearPageUnevictable(page);
1086                 if (unlikely(__PageMovable(page))) {
1087                         lock_page(page);
1088                         if (!PageMovable(page))
1089                                 __ClearPageIsolated(page);
1090                         unlock_page(page);
1091                 }
1092                 if (put_new_page)
1093                         put_new_page(newpage, private);
1094                 else
1095                         put_page(newpage);
1096                 goto out;
1097         }
1098
1099         if (unlikely(PageTransHuge(page)))
1100                 if (unlikely(split_huge_page(page)))
1101                         goto out;
1102
1103         rc = __unmap_and_move(page, newpage, force, mode);
1104         if (rc == MIGRATEPAGE_SUCCESS) {
1105                 set_page_owner_migrate_reason(newpage, reason);
1106         }
1107
1108 out:
1109         if (rc != -EAGAIN) {
1110                 /*
1111                  * A page that has been migrated has all references
1112                  * removed and will be freed. A page that has not been
1113                  * migrated will have kepts its references and be
1114                  * restored.
1115                  */
1116                 list_del(&page->lru);
1117                 dec_zone_page_state(page, NR_ISOLATED_ANON +
1118                                 page_is_file_cache(page));
1119         }
1120
1121         /*
1122          * If migration is successful, releases reference grabbed during
1123          * isolation. Otherwise, restore the page to right list unless
1124          * we want to retry.
1125          */
1126         if (rc == MIGRATEPAGE_SUCCESS) {
1127                 put_page(page);
1128                 if (reason == MR_MEMORY_FAILURE) {
1129                         /*
1130                          * Set PG_HWPoison on just freed page
1131                          * intentionally. Although it's rather weird,
1132                          * it's how HWPoison flag works at the moment.
1133                          */
1134                         if (!test_set_page_hwpoison(page))
1135                                 num_poisoned_pages_inc();
1136                 }
1137         } else {
1138                 if (rc != -EAGAIN) {
1139                         if (likely(!__PageMovable(page))) {
1140                                 putback_lru_page(page);
1141                                 goto put_new;
1142                         }
1143
1144                         lock_page(page);
1145                         if (PageMovable(page))
1146                                 putback_movable_page(page);
1147                         else
1148                                 __ClearPageIsolated(page);
1149                         unlock_page(page);
1150                         put_page(page);
1151                 }
1152 put_new:
1153                 if (put_new_page)
1154                         put_new_page(newpage, private);
1155                 else
1156                         put_page(newpage);
1157         }
1158
1159         if (result) {
1160                 if (rc)
1161                         *result = rc;
1162                 else
1163                         *result = page_to_nid(newpage);
1164         }
1165         return rc;
1166 }
1167
1168 /*
1169  * Counterpart of unmap_and_move_page() for hugepage migration.
1170  *
1171  * This function doesn't wait the completion of hugepage I/O
1172  * because there is no race between I/O and migration for hugepage.
1173  * Note that currently hugepage I/O occurs only in direct I/O
1174  * where no lock is held and PG_writeback is irrelevant,
1175  * and writeback status of all subpages are counted in the reference
1176  * count of the head page (i.e. if all subpages of a 2MB hugepage are
1177  * under direct I/O, the reference of the head page is 512 and a bit more.)
1178  * This means that when we try to migrate hugepage whose subpages are
1179  * doing direct I/O, some references remain after try_to_unmap() and
1180  * hugepage migration fails without data corruption.
1181  *
1182  * There is also no race when direct I/O is issued on the page under migration,
1183  * because then pte is replaced with migration swap entry and direct I/O code
1184  * will wait in the page fault for migration to complete.
1185  */
1186 static int unmap_and_move_huge_page(new_page_t get_new_page,
1187                                 free_page_t put_new_page, unsigned long private,
1188                                 struct page *hpage, int force,
1189                                 enum migrate_mode mode, int reason)
1190 {
1191         int rc = -EAGAIN;
1192         int *result = NULL;
1193         int page_was_mapped = 0;
1194         struct page *new_hpage;
1195         struct anon_vma *anon_vma = NULL;
1196
1197         /*
1198          * Movability of hugepages depends on architectures and hugepage size.
1199          * This check is necessary because some callers of hugepage migration
1200          * like soft offline and memory hotremove don't walk through page
1201          * tables or check whether the hugepage is pmd-based or not before
1202          * kicking migration.
1203          */
1204         if (!hugepage_migration_supported(page_hstate(hpage))) {
1205                 putback_active_hugepage(hpage);
1206                 return -ENOSYS;
1207         }
1208
1209         new_hpage = get_new_page(hpage, private, &result);
1210         if (!new_hpage)
1211                 return -ENOMEM;
1212
1213         if (!trylock_page(hpage)) {
1214                 if (!force || mode != MIGRATE_SYNC)
1215                         goto out;
1216                 lock_page(hpage);
1217         }
1218
1219         /*
1220          * Check for pages which are in the process of being freed.  Without
1221          * page_mapping() set, hugetlbfs specific move page routine will not
1222          * be called and we could leak usage counts for subpools.
1223          */
1224         if (page_private(hpage) && !page_mapping(hpage)) {
1225                 rc = -EBUSY;
1226                 goto out_unlock;
1227         }
1228
1229         if (PageAnon(hpage))
1230                 anon_vma = page_get_anon_vma(hpage);
1231
1232         if (unlikely(!trylock_page(new_hpage)))
1233                 goto put_anon;
1234
1235         if (page_mapped(hpage)) {
1236                 try_to_unmap(hpage,
1237                         TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS, NULL);
1238                 page_was_mapped = 1;
1239         }
1240
1241         if (!page_mapped(hpage))
1242                 rc = move_to_new_page(new_hpage, hpage, mode);
1243
1244         if (page_was_mapped)
1245                 remove_migration_ptes(hpage,
1246                         rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage);
1247
1248         unlock_page(new_hpage);
1249
1250 put_anon:
1251         if (anon_vma)
1252                 put_anon_vma(anon_vma);
1253
1254         if (rc == MIGRATEPAGE_SUCCESS) {
1255                 hugetlb_cgroup_migrate(hpage, new_hpage);
1256                 put_new_page = NULL;
1257                 set_page_owner_migrate_reason(new_hpage, reason);
1258         }
1259
1260 out_unlock:
1261         unlock_page(hpage);
1262 out:
1263         if (rc != -EAGAIN)
1264                 putback_active_hugepage(hpage);
1265
1266         /*
1267          * If migration was not successful and there's a freeing callback, use
1268          * it.  Otherwise, put_page() will drop the reference grabbed during
1269          * isolation.
1270          */
1271         if (put_new_page)
1272                 put_new_page(new_hpage, private);
1273         else
1274                 putback_active_hugepage(new_hpage);
1275
1276         if (result) {
1277                 if (rc)
1278                         *result = rc;
1279                 else
1280                         *result = page_to_nid(new_hpage);
1281         }
1282         return rc;
1283 }
1284
1285 /*
1286  * migrate_pages - migrate the pages specified in a list, to the free pages
1287  *                 supplied as the target for the page migration
1288  *
1289  * @from:               The list of pages to be migrated.
1290  * @get_new_page:       The function used to allocate free pages to be used
1291  *                      as the target of the page migration.
1292  * @put_new_page:       The function used to free target pages if migration
1293  *                      fails, or NULL if no special handling is necessary.
1294  * @private:            Private data to be passed on to get_new_page()
1295  * @mode:               The migration mode that specifies the constraints for
1296  *                      page migration, if any.
1297  * @reason:             The reason for page migration.
1298  *
1299  * The function returns after 10 attempts or if no pages are movable any more
1300  * because the list has become empty or no retryable pages exist any more.
1301  * The caller should call putback_movable_pages() to return pages to the LRU
1302  * or free list only if ret != 0.
1303  *
1304  * Returns the number of pages that were not migrated, or an error code.
1305  */
1306 int migrate_pages(struct list_head *from, new_page_t get_new_page,
1307                 free_page_t put_new_page, unsigned long private,
1308                 enum migrate_mode mode, int reason)
1309 {
1310         int retry = 1;
1311         int nr_failed = 0;
1312         int nr_succeeded = 0;
1313         int pass = 0;
1314         struct page *page;
1315         struct page *page2;
1316         int swapwrite = current->flags & PF_SWAPWRITE;
1317         int rc;
1318
1319         trace_mm_migrate_pages_start(mode, reason);
1320
1321         if (!swapwrite)
1322                 current->flags |= PF_SWAPWRITE;
1323
1324         for(pass = 0; pass < 10 && retry; pass++) {
1325                 retry = 0;
1326
1327                 list_for_each_entry_safe(page, page2, from, lru) {
1328                         cond_resched();
1329
1330                         if (PageHuge(page))
1331                                 rc = unmap_and_move_huge_page(get_new_page,
1332                                                 put_new_page, private, page,
1333                                                 pass > 2, mode, reason);
1334                         else
1335                                 rc = unmap_and_move(get_new_page, put_new_page,
1336                                                 private, page, pass > 2, mode,
1337                                                 reason);
1338
1339                         switch(rc) {
1340                         case -ENOMEM:
1341                                 goto out;
1342                         case -EAGAIN:
1343                                 retry++;
1344                                 break;
1345                         case MIGRATEPAGE_SUCCESS:
1346                                 nr_succeeded++;
1347                                 break;
1348                         default:
1349                                 /*
1350                                  * Permanent failure (-EBUSY, -ENOSYS, etc.):
1351                                  * unlike -EAGAIN case, the failed page is
1352                                  * removed from migration page list and not
1353                                  * retried in the next outer loop.
1354                                  */
1355                                 nr_failed++;
1356                                 break;
1357                         }
1358                 }
1359         }
1360         nr_failed += retry;
1361         rc = nr_failed;
1362 out:
1363         if (nr_succeeded)
1364                 count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
1365         if (nr_failed)
1366                 count_vm_events(PGMIGRATE_FAIL, nr_failed);
1367         trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
1368
1369         if (!swapwrite)
1370                 current->flags &= ~PF_SWAPWRITE;
1371
1372         return rc;
1373 }
1374
1375 #ifdef CONFIG_NUMA
1376 /*
1377  * Move a list of individual pages
1378  */
1379 struct page_to_node {
1380         unsigned long addr;
1381         struct page *page;
1382         int node;
1383         int status;
1384 };
1385
1386 static struct page *new_page_node(struct page *p, unsigned long private,
1387                 int **result)
1388 {
1389         struct page_to_node *pm = (struct page_to_node *)private;
1390
1391         while (pm->node != MAX_NUMNODES && pm->page != p)
1392                 pm++;
1393
1394         if (pm->node == MAX_NUMNODES)
1395                 return NULL;
1396
1397         *result = &pm->status;
1398
1399         if (PageHuge(p))
1400                 return alloc_huge_page_node(page_hstate(compound_head(p)),
1401                                         pm->node);
1402         else
1403                 return __alloc_pages_node(pm->node,
1404                                 GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0);
1405 }
1406
1407 /*
1408  * Move a set of pages as indicated in the pm array. The addr
1409  * field must be set to the virtual address of the page to be moved
1410  * and the node number must contain a valid target node.
1411  * The pm array ends with node = MAX_NUMNODES.
1412  */
1413 static int do_move_page_to_node_array(struct mm_struct *mm,
1414                                       struct page_to_node *pm,
1415                                       int migrate_all)
1416 {
1417         int err;
1418         struct page_to_node *pp;
1419         LIST_HEAD(pagelist);
1420
1421         down_read(&mm->mmap_sem);
1422
1423         /*
1424          * Build a list of pages to migrate
1425          */
1426         for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
1427                 struct vm_area_struct *vma;
1428                 struct page *page;
1429
1430                 err = -EFAULT;
1431                 vma = find_vma(mm, pp->addr);
1432                 if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
1433                         goto set_status;
1434
1435                 /* FOLL_DUMP to ignore special (like zero) pages */
1436                 page = follow_page(vma, pp->addr,
1437                                 FOLL_GET | FOLL_SPLIT | FOLL_DUMP);
1438
1439                 err = PTR_ERR(page);
1440                 if (IS_ERR(page))
1441                         goto set_status;
1442
1443                 err = -ENOENT;
1444                 if (!page)
1445                         goto set_status;
1446
1447                 pp->page = page;
1448                 err = page_to_nid(page);
1449
1450                 if (err == pp->node)
1451                         /*
1452                          * Node already in the right place
1453                          */
1454                         goto put_and_set;
1455
1456                 err = -EACCES;
1457                 if (page_mapcount(page) > 1 &&
1458                                 !migrate_all)
1459                         goto put_and_set;
1460
1461                 if (PageHuge(page)) {
1462                         if (PageHead(page))
1463                                 isolate_huge_page(page, &pagelist);
1464                         goto put_and_set;
1465                 }
1466
1467                 err = isolate_lru_page(page);
1468                 if (!err) {
1469                         list_add_tail(&page->lru, &pagelist);
1470                         inc_zone_page_state(page, NR_ISOLATED_ANON +
1471                                             page_is_file_cache(page));
1472                 }
1473 put_and_set:
1474                 /*
1475                  * Either remove the duplicate refcount from
1476                  * isolate_lru_page() or drop the page ref if it was
1477                  * not isolated.
1478                  */
1479                 put_page(page);
1480 set_status:
1481                 pp->status = err;
1482         }
1483
1484         err = 0;
1485         if (!list_empty(&pagelist)) {
1486                 err = migrate_pages(&pagelist, new_page_node, NULL,
1487                                 (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL);
1488                 if (err)
1489                         putback_movable_pages(&pagelist);
1490         }
1491
1492         up_read(&mm->mmap_sem);
1493         return err;
1494 }
1495
1496 /*
1497  * Migrate an array of page address onto an array of nodes and fill
1498  * the corresponding array of status.
1499  */
1500 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1501                          unsigned long nr_pages,
1502                          const void __user * __user *pages,
1503                          const int __user *nodes,
1504                          int __user *status, int flags)
1505 {
1506         struct page_to_node *pm;
1507         unsigned long chunk_nr_pages;
1508         unsigned long chunk_start;
1509         int err;
1510
1511         err = -ENOMEM;
1512         pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
1513         if (!pm)
1514                 goto out;
1515
1516         migrate_prep();
1517
1518         /*
1519          * Store a chunk of page_to_node array in a page,
1520          * but keep the last one as a marker
1521          */
1522         chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
1523
1524         for (chunk_start = 0;
1525              chunk_start < nr_pages;
1526              chunk_start += chunk_nr_pages) {
1527                 int j;
1528
1529                 if (chunk_start + chunk_nr_pages > nr_pages)
1530                         chunk_nr_pages = nr_pages - chunk_start;
1531
1532                 /* fill the chunk pm with addrs and nodes from user-space */
1533                 for (j = 0; j < chunk_nr_pages; j++) {
1534                         const void __user *p;
1535                         int node;
1536
1537                         err = -EFAULT;
1538                         if (get_user(p, pages + j + chunk_start))
1539                                 goto out_pm;
1540                         pm[j].addr = (unsigned long) p;
1541
1542                         if (get_user(node, nodes + j + chunk_start))
1543                                 goto out_pm;
1544
1545                         err = -ENODEV;
1546                         if (node < 0 || node >= MAX_NUMNODES)
1547                                 goto out_pm;
1548
1549                         if (!node_state(node, N_MEMORY))
1550                                 goto out_pm;
1551
1552                         err = -EACCES;
1553                         if (!node_isset(node, task_nodes))
1554                                 goto out_pm;
1555
1556                         pm[j].node = node;
1557                 }
1558
1559                 /* End marker for this chunk */
1560                 pm[chunk_nr_pages].node = MAX_NUMNODES;
1561
1562                 /* Migrate this chunk */
1563                 err = do_move_page_to_node_array(mm, pm,
1564                                                  flags & MPOL_MF_MOVE_ALL);
1565                 if (err < 0)
1566                         goto out_pm;
1567
1568                 /* Return status information */
1569                 for (j = 0; j < chunk_nr_pages; j++)
1570                         if (put_user(pm[j].status, status + j + chunk_start)) {
1571                                 err = -EFAULT;
1572                                 goto out_pm;
1573                         }
1574         }
1575         err = 0;
1576
1577 out_pm:
1578         free_page((unsigned long)pm);
1579 out:
1580         return err;
1581 }
1582
1583 /*
1584  * Determine the nodes of an array of pages and store it in an array of status.
1585  */
1586 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1587                                 const void __user **pages, int *status)
1588 {
1589         unsigned long i;
1590
1591         down_read(&mm->mmap_sem);
1592
1593         for (i = 0; i < nr_pages; i++) {
1594                 unsigned long addr = (unsigned long)(*pages);
1595                 struct vm_area_struct *vma;
1596                 struct page *page;
1597                 int err = -EFAULT;
1598
1599                 vma = find_vma(mm, addr);
1600                 if (!vma || addr < vma->vm_start)
1601                         goto set_status;
1602
1603                 /* FOLL_DUMP to ignore special (like zero) pages */
1604                 page = follow_page(vma, addr, FOLL_DUMP);
1605
1606                 err = PTR_ERR(page);
1607                 if (IS_ERR(page))
1608                         goto set_status;
1609
1610                 err = page ? page_to_nid(page) : -ENOENT;
1611 set_status:
1612                 *status = err;
1613
1614                 pages++;
1615                 status++;
1616         }
1617
1618         up_read(&mm->mmap_sem);
1619 }
1620
1621 /*
1622  * Determine the nodes of a user array of pages and store it in
1623  * a user array of status.
1624  */
1625 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1626                          const void __user * __user *pages,
1627                          int __user *status)
1628 {
1629 #define DO_PAGES_STAT_CHUNK_NR 16
1630         const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1631         int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1632
1633         while (nr_pages) {
1634                 unsigned long chunk_nr;
1635
1636                 chunk_nr = nr_pages;
1637                 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1638                         chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1639
1640                 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1641                         break;
1642
1643                 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1644
1645                 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1646                         break;
1647
1648                 pages += chunk_nr;
1649                 status += chunk_nr;
1650                 nr_pages -= chunk_nr;
1651         }
1652         return nr_pages ? -EFAULT : 0;
1653 }
1654
1655 /*
1656  * Move a list of pages in the address space of the currently executing
1657  * process.
1658  */
1659 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1660                 const void __user * __user *, pages,
1661                 const int __user *, nodes,
1662                 int __user *, status, int, flags)
1663 {
1664         struct task_struct *task;
1665         struct mm_struct *mm;
1666         int err;
1667         nodemask_t task_nodes;
1668
1669         /* Check flags */
1670         if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1671                 return -EINVAL;
1672
1673         if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1674                 return -EPERM;
1675
1676         /* Find the mm_struct */
1677         rcu_read_lock();
1678         task = pid ? find_task_by_vpid(pid) : current;
1679         if (!task) {
1680                 rcu_read_unlock();
1681                 return -ESRCH;
1682         }
1683         get_task_struct(task);
1684
1685         /*
1686          * Check if this process has the right to modify the specified
1687          * process. Use the regular "ptrace_may_access()" checks.
1688          */
1689         if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1690                 rcu_read_unlock();
1691                 err = -EPERM;
1692                 goto out;
1693         }
1694         rcu_read_unlock();
1695
1696         err = security_task_movememory(task);
1697         if (err)
1698                 goto out;
1699
1700         task_nodes = cpuset_mems_allowed(task);
1701         mm = get_task_mm(task);
1702         put_task_struct(task);
1703
1704         if (!mm)
1705                 return -EINVAL;
1706
1707         if (nodes)
1708                 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1709                                     nodes, status, flags);
1710         else
1711                 err = do_pages_stat(mm, nr_pages, pages, status);
1712
1713         mmput(mm);
1714         return err;
1715
1716 out:
1717         put_task_struct(task);
1718         return err;
1719 }
1720
1721 #ifdef CONFIG_NUMA_BALANCING
1722 /*
1723  * Returns true if this is a safe migration target node for misplaced NUMA
1724  * pages. Currently it only checks the watermarks which crude
1725  */
1726 static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
1727                                    unsigned long nr_migrate_pages)
1728 {
1729         int z;
1730         for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1731                 struct zone *zone = pgdat->node_zones + z;
1732
1733                 if (!populated_zone(zone))
1734                         continue;
1735
1736                 if (!zone_reclaimable(zone))
1737                         continue;
1738
1739                 /* Avoid waking kswapd by allocating pages_to_migrate pages. */
1740                 if (!zone_watermark_ok(zone, 0,
1741                                        high_wmark_pages(zone) +
1742                                        nr_migrate_pages,
1743                                        0, 0))
1744                         continue;
1745                 return true;
1746         }
1747         return false;
1748 }
1749
1750 static struct page *alloc_misplaced_dst_page(struct page *page,
1751                                            unsigned long data,
1752                                            int **result)
1753 {
1754         int nid = (int) data;
1755         struct page *newpage;
1756
1757         newpage = __alloc_pages_node(nid,
1758                                          (GFP_HIGHUSER_MOVABLE |
1759                                           __GFP_THISNODE | __GFP_NOMEMALLOC |
1760                                           __GFP_NORETRY | __GFP_NOWARN) &
1761                                          ~__GFP_RECLAIM, 0);
1762
1763         return newpage;
1764 }
1765
1766 /*
1767  * page migration rate limiting control.
1768  * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs
1769  * window of time. Default here says do not migrate more than 1280M per second.
1770  */
1771 static unsigned int migrate_interval_millisecs __read_mostly = 100;
1772 static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT);
1773
1774 /* Returns true if the node is migrate rate-limited after the update */
1775 static bool numamigrate_update_ratelimit(pg_data_t *pgdat,
1776                                         unsigned long nr_pages)
1777 {
1778         /*
1779          * Rate-limit the amount of data that is being migrated to a node.
1780          * Optimal placement is no good if the memory bus is saturated and
1781          * all the time is being spent migrating!
1782          */
1783         if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) {
1784                 spin_lock(&pgdat->numabalancing_migrate_lock);
1785                 pgdat->numabalancing_migrate_nr_pages = 0;
1786                 pgdat->numabalancing_migrate_next_window = jiffies +
1787                         msecs_to_jiffies(migrate_interval_millisecs);
1788                 spin_unlock(&pgdat->numabalancing_migrate_lock);
1789         }
1790         if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) {
1791                 trace_mm_numa_migrate_ratelimit(current, pgdat->node_id,
1792                                                                 nr_pages);
1793                 return true;
1794         }
1795
1796         /*
1797          * This is an unlocked non-atomic update so errors are possible.
1798          * The consequences are failing to migrate when we potentiall should
1799          * have which is not severe enough to warrant locking. If it is ever
1800          * a problem, it can be converted to a per-cpu counter.
1801          */
1802         pgdat->numabalancing_migrate_nr_pages += nr_pages;
1803         return false;
1804 }
1805
1806 static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
1807 {
1808         int page_lru;
1809
1810         VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page);
1811
1812         /* Avoid migrating to a node that is nearly full */
1813         if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
1814                 return 0;
1815
1816         if (isolate_lru_page(page))
1817                 return 0;
1818
1819         /*
1820          * migrate_misplaced_transhuge_page() skips page migration's usual
1821          * check on page_count(), so we must do it here, now that the page
1822          * has been isolated: a GUP pin, or any other pin, prevents migration.
1823          * The expected page count is 3: 1 for page's mapcount and 1 for the
1824          * caller's pin and 1 for the reference taken by isolate_lru_page().
1825          */
1826         if (PageTransHuge(page) && page_count(page) != 3) {
1827                 putback_lru_page(page);
1828                 return 0;
1829         }
1830
1831         page_lru = page_is_file_cache(page);
1832         mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru,
1833                                 hpage_nr_pages(page));
1834
1835         /*
1836          * Isolating the page has taken another reference, so the
1837          * caller's reference can be safely dropped without the page
1838          * disappearing underneath us during migration.
1839          */
1840         put_page(page);
1841         return 1;
1842 }
1843
1844 bool pmd_trans_migrating(pmd_t pmd)
1845 {
1846         struct page *page = pmd_page(pmd);
1847         return PageLocked(page);
1848 }
1849
1850 /*
1851  * Attempt to migrate a misplaced page to the specified destination
1852  * node. Caller is expected to have an elevated reference count on
1853  * the page that will be dropped by this function before returning.
1854  */
1855 int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma,
1856                            int node)
1857 {
1858         pg_data_t *pgdat = NODE_DATA(node);
1859         int isolated;
1860         int nr_remaining;
1861         LIST_HEAD(migratepages);
1862
1863         /*
1864          * Don't migrate file pages that are mapped in multiple processes
1865          * with execute permissions as they are probably shared libraries.
1866          */
1867         if (page_mapcount(page) != 1 && page_is_file_cache(page) &&
1868             (vma->vm_flags & VM_EXEC))
1869                 goto out;
1870
1871         /*
1872          * Rate-limit the amount of data that is being migrated to a node.
1873          * Optimal placement is no good if the memory bus is saturated and
1874          * all the time is being spent migrating!
1875          */
1876         if (numamigrate_update_ratelimit(pgdat, 1))
1877                 goto out;
1878
1879         isolated = numamigrate_isolate_page(pgdat, page);
1880         if (!isolated)
1881                 goto out;
1882
1883         list_add(&page->lru, &migratepages);
1884         nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
1885                                      NULL, node, MIGRATE_ASYNC,
1886                                      MR_NUMA_MISPLACED);
1887         if (nr_remaining) {
1888                 if (!list_empty(&migratepages)) {
1889                         list_del(&page->lru);
1890                         dec_zone_page_state(page, NR_ISOLATED_ANON +
1891                                         page_is_file_cache(page));
1892                         putback_lru_page(page);
1893                 }
1894                 isolated = 0;
1895         } else
1896                 count_vm_numa_event(NUMA_PAGE_MIGRATE);
1897         BUG_ON(!list_empty(&migratepages));
1898         return isolated;
1899
1900 out:
1901         put_page(page);
1902         return 0;
1903 }
1904 #endif /* CONFIG_NUMA_BALANCING */
1905
1906 #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1907 /*
1908  * Migrates a THP to a given target node. page must be locked and is unlocked
1909  * before returning.
1910  */
1911 int migrate_misplaced_transhuge_page(struct mm_struct *mm,
1912                                 struct vm_area_struct *vma,
1913                                 pmd_t *pmd, pmd_t entry,
1914                                 unsigned long address,
1915                                 struct page *page, int node)
1916 {
1917         spinlock_t *ptl;
1918         pg_data_t *pgdat = NODE_DATA(node);
1919         int isolated = 0;
1920         struct page *new_page = NULL;
1921         int page_lru = page_is_file_cache(page);
1922         unsigned long mmun_start = address & HPAGE_PMD_MASK;
1923         unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE;
1924         pmd_t orig_entry;
1925
1926         /*
1927          * Rate-limit the amount of data that is being migrated to a node.
1928          * Optimal placement is no good if the memory bus is saturated and
1929          * all the time is being spent migrating!
1930          */
1931         if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))
1932                 goto out_dropref;
1933
1934         new_page = alloc_pages_node(node,
1935                 (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_RECLAIM,
1936                 HPAGE_PMD_ORDER);
1937         if (!new_page)
1938                 goto out_fail;
1939
1940         isolated = numamigrate_isolate_page(pgdat, page);
1941         if (!isolated) {
1942                 put_page(new_page);
1943                 goto out_fail;
1944         }
1945
1946         if (mm_tlb_flush_pending(mm))
1947                 flush_tlb_range(vma, mmun_start, mmun_end);
1948
1949         /* Prepare a page as a migration target */
1950         __SetPageLocked(new_page);
1951         SetPageSwapBacked(new_page);
1952
1953         /* anon mapping, we can simply copy page->mapping to the new page: */
1954         new_page->mapping = page->mapping;
1955         new_page->index = page->index;
1956         migrate_page_copy(new_page, page);
1957         WARN_ON(PageLRU(new_page));
1958
1959         /* Recheck the target PMD */
1960         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1961         ptl = pmd_lock(mm, pmd);
1962         if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) {
1963 fail_putback:
1964                 spin_unlock(ptl);
1965                 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1966
1967                 /* Reverse changes made by migrate_page_copy() */
1968                 if (TestClearPageActive(new_page))
1969                         SetPageActive(page);
1970                 if (TestClearPageUnevictable(new_page))
1971                         SetPageUnevictable(page);
1972
1973                 unlock_page(new_page);
1974                 put_page(new_page);             /* Free it */
1975
1976                 /* Retake the callers reference and putback on LRU */
1977                 get_page(page);
1978                 putback_lru_page(page);
1979                 mod_zone_page_state(page_zone(page),
1980                          NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
1981
1982                 goto out_unlock;
1983         }
1984
1985         orig_entry = *pmd;
1986         entry = mk_pmd(new_page, vma->vm_page_prot);
1987         entry = pmd_mkhuge(entry);
1988         entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
1989
1990         /*
1991          * Clear the old entry under pagetable lock and establish the new PTE.
1992          * Any parallel GUP will either observe the old page blocking on the
1993          * page lock, block on the page table lock or observe the new page.
1994          * The SetPageUptodate on the new page and page_add_new_anon_rmap
1995          * guarantee the copy is visible before the pagetable update.
1996          */
1997         flush_cache_range(vma, mmun_start, mmun_end);
1998         page_add_anon_rmap(new_page, vma, mmun_start);
1999         pmdp_huge_clear_flush_notify(vma, mmun_start, pmd);
2000         set_pmd_at(mm, mmun_start, pmd, entry);
2001         flush_tlb_range(vma, mmun_start, mmun_end);
2002         update_mmu_cache_pmd(vma, address, &entry);
2003
2004         if (page_count(page) != 2) {
2005                 set_pmd_at(mm, mmun_start, pmd, orig_entry);
2006                 flush_tlb_range(vma, mmun_start, mmun_end);
2007                 mmu_notifier_invalidate_range(mm, mmun_start, mmun_end);
2008                 update_mmu_cache_pmd(vma, address, &entry);
2009                 page_remove_rmap(new_page);
2010                 goto fail_putback;
2011         }
2012
2013         mlock_migrate_page(new_page, page);
2014         set_page_memcg(new_page, page_memcg(page));
2015         set_page_memcg(page, NULL);
2016         page_remove_rmap(page);
2017         set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED);
2018
2019         spin_unlock(ptl);
2020         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2021
2022         /* Take an "isolate" reference and put new page on the LRU. */
2023         get_page(new_page);
2024         putback_lru_page(new_page);
2025
2026         unlock_page(new_page);
2027         unlock_page(page);
2028         put_page(page);                 /* Drop the rmap reference */
2029         put_page(page);                 /* Drop the LRU isolation reference */
2030
2031         count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
2032         count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
2033
2034         mod_zone_page_state(page_zone(page),
2035                         NR_ISOLATED_ANON + page_lru,
2036                         -HPAGE_PMD_NR);
2037         return isolated;
2038
2039 out_fail:
2040         count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
2041 out_dropref:
2042         ptl = pmd_lock(mm, pmd);
2043         if (pmd_same(*pmd, entry)) {
2044                 entry = pmd_modify(entry, vma->vm_page_prot);
2045                 set_pmd_at(mm, mmun_start, pmd, entry);
2046                 update_mmu_cache_pmd(vma, address, &entry);
2047         }
2048         spin_unlock(ptl);
2049
2050 out_unlock:
2051         unlock_page(page);
2052         put_page(page);
2053         return 0;
2054 }
2055 #endif /* CONFIG_NUMA_BALANCING */
2056
2057 #endif /* CONFIG_NUMA */