]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - mm/migrate.c
0410e80c9ac36f5670bd0cb327be801a2f7d9e51
[karo-tx-linux.git] / mm / migrate.c
1 /*
2  * Memory Migration functionality - linux/mm/migration.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/memcontrol.h>
34 #include <linux/syscalls.h>
35 #include <linux/hugetlb.h>
36 #include <linux/hugetlb_cgroup.h>
37 #include <linux/gfp.h>
38 #include <linux/balloon_compaction.h>
39
40 #include <asm/tlbflush.h>
41
42 #include "internal.h"
43
44 /*
45  * migrate_prep() needs to be called before we start compiling a list of pages
46  * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
47  * undesirable, use migrate_prep_local()
48  */
49 int migrate_prep(void)
50 {
51         /*
52          * Clear the LRU lists so pages can be isolated.
53          * Note that pages may be moved off the LRU after we have
54          * drained them. Those pages will fail to migrate like other
55          * pages that may be busy.
56          */
57         lru_add_drain_all();
58
59         return 0;
60 }
61
62 /* Do the necessary work of migrate_prep but not if it involves other CPUs */
63 int migrate_prep_local(void)
64 {
65         lru_add_drain();
66
67         return 0;
68 }
69
70 /*
71  * Add isolated pages on the list back to the LRU under page lock
72  * to avoid leaking evictable pages back onto unevictable list.
73  */
74 void putback_lru_pages(struct list_head *l)
75 {
76         struct page *page;
77         struct page *page2;
78
79         list_for_each_entry_safe(page, page2, l, lru) {
80                 list_del(&page->lru);
81                 dec_zone_page_state(page, NR_ISOLATED_ANON +
82                                 page_is_file_cache(page));
83                 if (unlikely(balloon_page_movable(page)))
84                         balloon_page_putback(page);
85                 else
86                         putback_lru_page(page);
87         }
88 }
89
90 /*
91  * Restore a potential migration pte to a working pte entry
92  */
93 static int remove_migration_pte(struct page *new, struct vm_area_struct *vma,
94                                  unsigned long addr, void *old)
95 {
96         struct mm_struct *mm = vma->vm_mm;
97         swp_entry_t entry;
98         pmd_t *pmd;
99         pte_t *ptep, pte;
100         spinlock_t *ptl;
101
102         if (unlikely(PageHuge(new))) {
103                 ptep = huge_pte_offset(mm, addr);
104                 if (!ptep)
105                         goto out;
106                 ptl = &mm->page_table_lock;
107         } else {
108                 pmd = mm_find_pmd(mm, addr);
109                 if (!pmd)
110                         goto out;
111                 if (pmd_trans_huge(*pmd))
112                         goto out;
113
114                 ptep = pte_offset_map(pmd, addr);
115
116                 /*
117                  * Peek to check is_swap_pte() before taking ptlock?  No, we
118                  * can race mremap's move_ptes(), which skips anon_vma lock.
119                  */
120
121                 ptl = pte_lockptr(mm, pmd);
122         }
123
124         spin_lock(ptl);
125         pte = *ptep;
126         if (!is_swap_pte(pte))
127                 goto unlock;
128
129         entry = pte_to_swp_entry(pte);
130
131         if (!is_migration_entry(entry) ||
132             migration_entry_to_page(entry) != old)
133                 goto unlock;
134
135         get_page(new);
136         pte = pte_mkold(mk_pte(new, vma->vm_page_prot));
137         if (is_write_migration_entry(entry))
138                 pte = pte_mkwrite(pte);
139 #ifdef CONFIG_HUGETLB_PAGE
140         if (PageHuge(new))
141                 pte = pte_mkhuge(pte);
142 #endif
143         flush_cache_page(vma, addr, pte_pfn(pte));
144         set_pte_at(mm, addr, ptep, pte);
145
146         if (PageHuge(new)) {
147                 if (PageAnon(new))
148                         hugepage_add_anon_rmap(new, vma, addr);
149                 else
150                         page_dup_rmap(new);
151         } else if (PageAnon(new))
152                 page_add_anon_rmap(new, vma, addr);
153         else
154                 page_add_file_rmap(new);
155
156         /* No need to invalidate - it was non-present before */
157         update_mmu_cache(vma, addr, ptep);
158 unlock:
159         pte_unmap_unlock(ptep, ptl);
160 out:
161         return SWAP_AGAIN;
162 }
163
164 /*
165  * Get rid of all migration entries and replace them by
166  * references to the indicated page.
167  */
168 static void remove_migration_ptes(struct page *old, struct page *new)
169 {
170         rmap_walk(new, remove_migration_pte, old);
171 }
172
173 /*
174  * Something used the pte of a page under migration. We need to
175  * get to the page and wait until migration is finished.
176  * When we return from this function the fault will be retried.
177  */
178 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
179                                 unsigned long address)
180 {
181         pte_t *ptep, pte;
182         spinlock_t *ptl;
183         swp_entry_t entry;
184         struct page *page;
185
186         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
187         pte = *ptep;
188         if (!is_swap_pte(pte))
189                 goto out;
190
191         entry = pte_to_swp_entry(pte);
192         if (!is_migration_entry(entry))
193                 goto out;
194
195         page = migration_entry_to_page(entry);
196
197         /*
198          * Once radix-tree replacement of page migration started, page_count
199          * *must* be zero. And, we don't want to call wait_on_page_locked()
200          * against a page without get_page().
201          * So, we use get_page_unless_zero(), here. Even failed, page fault
202          * will occur again.
203          */
204         if (!get_page_unless_zero(page))
205                 goto out;
206         pte_unmap_unlock(ptep, ptl);
207         wait_on_page_locked(page);
208         put_page(page);
209         return;
210 out:
211         pte_unmap_unlock(ptep, ptl);
212 }
213
214 #ifdef CONFIG_BLOCK
215 /* Returns true if all buffers are successfully locked */
216 static bool buffer_migrate_lock_buffers(struct buffer_head *head,
217                                                         enum migrate_mode mode)
218 {
219         struct buffer_head *bh = head;
220
221         /* Simple case, sync compaction */
222         if (mode != MIGRATE_ASYNC && mode != MIGRATE_FAULT) {
223                 do {
224                         get_bh(bh);
225                         lock_buffer(bh);
226                         bh = bh->b_this_page;
227
228                 } while (bh != head);
229
230                 return true;
231         }
232
233         /* async case, we cannot block on lock_buffer so use trylock_buffer */
234         do {
235                 get_bh(bh);
236                 if (!trylock_buffer(bh)) {
237                         /*
238                          * We failed to lock the buffer and cannot stall in
239                          * async migration. Release the taken locks
240                          */
241                         struct buffer_head *failed_bh = bh;
242                         put_bh(failed_bh);
243                         bh = head;
244                         while (bh != failed_bh) {
245                                 unlock_buffer(bh);
246                                 put_bh(bh);
247                                 bh = bh->b_this_page;
248                         }
249                         return false;
250                 }
251
252                 bh = bh->b_this_page;
253         } while (bh != head);
254         return true;
255 }
256 #else
257 static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
258                                                         enum migrate_mode mode)
259 {
260         return true;
261 }
262 #endif /* CONFIG_BLOCK */
263
264 /*
265  * Replace the page in the mapping.
266  *
267  * The number of remaining references must be:
268  * 1 for anonymous pages without a mapping
269  * 2 for pages with a mapping
270  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
271  */
272 static int migrate_page_move_mapping(struct address_space *mapping,
273                 struct page *newpage, struct page *page,
274                 struct buffer_head *head, enum migrate_mode mode)
275 {
276         int expected_count = 0;
277         void **pslot;
278
279         if (mode == MIGRATE_FAULT) {
280                 /*
281                  * MIGRATE_FAULT has an extra reference on the page and
282                  * otherwise acts like ASYNC, no point in delaying the
283                  * fault, we'll try again next time.
284                  */
285                 expected_count++;
286         }
287
288         if (!mapping) {
289                 /* Anonymous page without mapping */
290                 expected_count += 1;
291                 if (page_count(page) != expected_count)
292                         return -EAGAIN;
293                 return MIGRATEPAGE_SUCCESS;
294         }
295
296         spin_lock_irq(&mapping->tree_lock);
297
298         pslot = radix_tree_lookup_slot(&mapping->page_tree,
299                                         page_index(page));
300
301         expected_count += 2 + page_has_private(page);
302         if (page_count(page) != expected_count ||
303                 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
304                 spin_unlock_irq(&mapping->tree_lock);
305                 return -EAGAIN;
306         }
307
308         if (!page_freeze_refs(page, expected_count)) {
309                 spin_unlock_irq(&mapping->tree_lock);
310                 return -EAGAIN;
311         }
312
313         /*
314          * In the async migration case of moving a page with buffers, lock the
315          * buffers using trylock before the mapping is moved. If the mapping
316          * was moved, we later failed to lock the buffers and could not move
317          * the mapping back due to an elevated page count, we would have to
318          * block waiting on other references to be dropped.
319          */
320         if ((mode == MIGRATE_ASYNC || mode == MIGRATE_FAULT) && head &&
321                         !buffer_migrate_lock_buffers(head, mode)) {
322                 page_unfreeze_refs(page, expected_count);
323                 spin_unlock_irq(&mapping->tree_lock);
324                 return -EAGAIN;
325         }
326
327         /*
328          * Now we know that no one else is looking at the page.
329          */
330         get_page(newpage);      /* add cache reference */
331         if (PageSwapCache(page)) {
332                 SetPageSwapCache(newpage);
333                 set_page_private(newpage, page_private(page));
334         }
335
336         radix_tree_replace_slot(pslot, newpage);
337
338         /*
339          * Drop cache reference from old page by unfreezing
340          * to one less reference.
341          * We know this isn't the last reference.
342          */
343         page_unfreeze_refs(page, expected_count - 1);
344
345         /*
346          * If moved to a different zone then also account
347          * the page for that zone. Other VM counters will be
348          * taken care of when we establish references to the
349          * new page and drop references to the old page.
350          *
351          * Note that anonymous pages are accounted for
352          * via NR_FILE_PAGES and NR_ANON_PAGES if they
353          * are mapped to swap space.
354          */
355         __dec_zone_page_state(page, NR_FILE_PAGES);
356         __inc_zone_page_state(newpage, NR_FILE_PAGES);
357         if (!PageSwapCache(page) && PageSwapBacked(page)) {
358                 __dec_zone_page_state(page, NR_SHMEM);
359                 __inc_zone_page_state(newpage, NR_SHMEM);
360         }
361         spin_unlock_irq(&mapping->tree_lock);
362
363         return MIGRATEPAGE_SUCCESS;
364 }
365
366 /*
367  * The expected number of remaining references is the same as that
368  * of migrate_page_move_mapping().
369  */
370 int migrate_huge_page_move_mapping(struct address_space *mapping,
371                                    struct page *newpage, struct page *page)
372 {
373         int expected_count;
374         void **pslot;
375
376         if (!mapping) {
377                 if (page_count(page) != 1)
378                         return -EAGAIN;
379                 return MIGRATEPAGE_SUCCESS;
380         }
381
382         spin_lock_irq(&mapping->tree_lock);
383
384         pslot = radix_tree_lookup_slot(&mapping->page_tree,
385                                         page_index(page));
386
387         expected_count = 2 + page_has_private(page);
388         if (page_count(page) != expected_count ||
389                 radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
390                 spin_unlock_irq(&mapping->tree_lock);
391                 return -EAGAIN;
392         }
393
394         if (!page_freeze_refs(page, expected_count)) {
395                 spin_unlock_irq(&mapping->tree_lock);
396                 return -EAGAIN;
397         }
398
399         get_page(newpage);
400
401         radix_tree_replace_slot(pslot, newpage);
402
403         page_unfreeze_refs(page, expected_count - 1);
404
405         spin_unlock_irq(&mapping->tree_lock);
406         return MIGRATEPAGE_SUCCESS;
407 }
408
409 /*
410  * Copy the page to its new location
411  */
412 void migrate_page_copy(struct page *newpage, struct page *page)
413 {
414         if (PageHuge(page) || PageTransHuge(page))
415                 copy_huge_page(newpage, page);
416         else
417                 copy_highpage(newpage, page);
418
419         if (PageError(page))
420                 SetPageError(newpage);
421         if (PageReferenced(page))
422                 SetPageReferenced(newpage);
423         if (PageUptodate(page))
424                 SetPageUptodate(newpage);
425         if (TestClearPageActive(page)) {
426                 VM_BUG_ON(PageUnevictable(page));
427                 SetPageActive(newpage);
428         } else if (TestClearPageUnevictable(page))
429                 SetPageUnevictable(newpage);
430         if (PageChecked(page))
431                 SetPageChecked(newpage);
432         if (PageMappedToDisk(page))
433                 SetPageMappedToDisk(newpage);
434
435         if (PageDirty(page)) {
436                 clear_page_dirty_for_io(page);
437                 /*
438                  * Want to mark the page and the radix tree as dirty, and
439                  * redo the accounting that clear_page_dirty_for_io undid,
440                  * but we can't use set_page_dirty because that function
441                  * is actually a signal that all of the page has become dirty.
442                  * Whereas only part of our page may be dirty.
443                  */
444                 if (PageSwapBacked(page))
445                         SetPageDirty(newpage);
446                 else
447                         __set_page_dirty_nobuffers(newpage);
448         }
449
450         mlock_migrate_page(newpage, page);
451         ksm_migrate_page(newpage, page);
452
453         ClearPageSwapCache(page);
454         ClearPagePrivate(page);
455         set_page_private(page, 0);
456
457         /*
458          * If any waiters have accumulated on the new page then
459          * wake them up.
460          */
461         if (PageWriteback(newpage))
462                 end_page_writeback(newpage);
463 }
464
465 /************************************************************
466  *                    Migration functions
467  ***********************************************************/
468
469 /* Always fail migration. Used for mappings that are not movable */
470 int fail_migrate_page(struct address_space *mapping,
471                         struct page *newpage, struct page *page)
472 {
473         return -EIO;
474 }
475 EXPORT_SYMBOL(fail_migrate_page);
476
477 /*
478  * Common logic to directly migrate a single page suitable for
479  * pages that do not use PagePrivate/PagePrivate2.
480  *
481  * Pages are locked upon entry and exit.
482  */
483 int migrate_page(struct address_space *mapping,
484                 struct page *newpage, struct page *page,
485                 enum migrate_mode mode)
486 {
487         int rc;
488
489         BUG_ON(PageWriteback(page));    /* Writeback must be complete */
490
491         rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode);
492
493         if (rc != MIGRATEPAGE_SUCCESS)
494                 return rc;
495
496         migrate_page_copy(newpage, page);
497         return MIGRATEPAGE_SUCCESS;
498 }
499 EXPORT_SYMBOL(migrate_page);
500
501 #ifdef CONFIG_BLOCK
502 /*
503  * Migration function for pages with buffers. This function can only be used
504  * if the underlying filesystem guarantees that no other references to "page"
505  * exist.
506  */
507 int buffer_migrate_page(struct address_space *mapping,
508                 struct page *newpage, struct page *page, enum migrate_mode mode)
509 {
510         struct buffer_head *bh, *head;
511         int rc;
512
513         if (!page_has_buffers(page))
514                 return migrate_page(mapping, newpage, page, mode);
515
516         head = page_buffers(page);
517
518         rc = migrate_page_move_mapping(mapping, newpage, page, head, mode);
519
520         if (rc != MIGRATEPAGE_SUCCESS)
521                 return rc;
522
523         /*
524          * In the async case, migrate_page_move_mapping locked the buffers
525          * with an IRQ-safe spinlock held. In the sync case, the buffers
526          * need to be locked now
527          */
528         if (mode != MIGRATE_ASYNC && mode != MIGRATE_FAULT)
529                 BUG_ON(!buffer_migrate_lock_buffers(head, mode));
530
531         ClearPagePrivate(page);
532         set_page_private(newpage, page_private(page));
533         set_page_private(page, 0);
534         put_page(page);
535         get_page(newpage);
536
537         bh = head;
538         do {
539                 set_bh_page(bh, newpage, bh_offset(bh));
540                 bh = bh->b_this_page;
541
542         } while (bh != head);
543
544         SetPagePrivate(newpage);
545
546         migrate_page_copy(newpage, page);
547
548         bh = head;
549         do {
550                 unlock_buffer(bh);
551                 put_bh(bh);
552                 bh = bh->b_this_page;
553
554         } while (bh != head);
555
556         return MIGRATEPAGE_SUCCESS;
557 }
558 EXPORT_SYMBOL(buffer_migrate_page);
559 #endif
560
561 /*
562  * Writeback a page to clean the dirty state
563  */
564 static int writeout(struct address_space *mapping, struct page *page)
565 {
566         struct writeback_control wbc = {
567                 .sync_mode = WB_SYNC_NONE,
568                 .nr_to_write = 1,
569                 .range_start = 0,
570                 .range_end = LLONG_MAX,
571                 .for_reclaim = 1
572         };
573         int rc;
574
575         if (!mapping->a_ops->writepage)
576                 /* No write method for the address space */
577                 return -EINVAL;
578
579         if (!clear_page_dirty_for_io(page))
580                 /* Someone else already triggered a write */
581                 return -EAGAIN;
582
583         /*
584          * A dirty page may imply that the underlying filesystem has
585          * the page on some queue. So the page must be clean for
586          * migration. Writeout may mean we loose the lock and the
587          * page state is no longer what we checked for earlier.
588          * At this point we know that the migration attempt cannot
589          * be successful.
590          */
591         remove_migration_ptes(page, page);
592
593         rc = mapping->a_ops->writepage(page, &wbc);
594
595         if (rc != AOP_WRITEPAGE_ACTIVATE)
596                 /* unlocked. Relock */
597                 lock_page(page);
598
599         return (rc < 0) ? -EIO : -EAGAIN;
600 }
601
602 /*
603  * Default handling if a filesystem does not provide a migration function.
604  */
605 static int fallback_migrate_page(struct address_space *mapping,
606         struct page *newpage, struct page *page, enum migrate_mode mode)
607 {
608         if (PageDirty(page)) {
609                 /* Only writeback pages in full synchronous migration */
610                 if (mode != MIGRATE_SYNC)
611                         return -EBUSY;
612                 return writeout(mapping, page);
613         }
614
615         /*
616          * Buffers may be managed in a filesystem specific way.
617          * We must have no buffers or drop them.
618          */
619         if (page_has_private(page) &&
620             !try_to_release_page(page, GFP_KERNEL))
621                 return -EAGAIN;
622
623         return migrate_page(mapping, newpage, page, mode);
624 }
625
626 /*
627  * Move a page to a newly allocated page
628  * The page is locked and all ptes have been successfully removed.
629  *
630  * The new page will have replaced the old page if this function
631  * is successful.
632  *
633  * Return value:
634  *   < 0 - error code
635  *  == 0 - success
636  */
637 static int move_to_new_page(struct page *newpage, struct page *page,
638                                 int remap_swapcache, enum migrate_mode mode)
639 {
640         struct address_space *mapping;
641         int rc;
642
643         /*
644          * Block others from accessing the page when we get around to
645          * establishing additional references. We are the only one
646          * holding a reference to the new page at this point.
647          */
648         if (!trylock_page(newpage))
649                 BUG();
650
651         /* Prepare mapping for the new page.*/
652         newpage->index = page->index;
653         newpage->mapping = page->mapping;
654         if (PageSwapBacked(page))
655                 SetPageSwapBacked(newpage);
656
657         mapping = page_mapping(page);
658         if (!mapping)
659                 rc = migrate_page(mapping, newpage, page, mode);
660         else if (mapping->a_ops->migratepage)
661                 /*
662                  * Most pages have a mapping and most filesystems provide a
663                  * migratepage callback. Anonymous pages are part of swap
664                  * space which also has its own migratepage callback. This
665                  * is the most common path for page migration.
666                  */
667                 rc = mapping->a_ops->migratepage(mapping,
668                                                 newpage, page, mode);
669         else
670                 rc = fallback_migrate_page(mapping, newpage, page, mode);
671
672         if (rc != MIGRATEPAGE_SUCCESS) {
673                 newpage->mapping = NULL;
674         } else {
675                 if (remap_swapcache)
676                         remove_migration_ptes(page, newpage);
677                 page->mapping = NULL;
678         }
679
680         unlock_page(newpage);
681
682         return rc;
683 }
684
685 static int __unmap_and_move(struct page *page, struct page *newpage,
686                         int force, bool offlining, enum migrate_mode mode)
687 {
688         int rc = -EAGAIN;
689         int remap_swapcache = 1;
690         struct mem_cgroup *mem;
691         struct anon_vma *anon_vma = NULL;
692
693         if (!trylock_page(page)) {
694                 if (!force || mode == MIGRATE_ASYNC || mode == MIGRATE_FAULT)
695                         goto out;
696
697                 /*
698                  * It's not safe for direct compaction to call lock_page.
699                  * For example, during page readahead pages are added locked
700                  * to the LRU. Later, when the IO completes the pages are
701                  * marked uptodate and unlocked. However, the queueing
702                  * could be merging multiple pages for one bio (e.g.
703                  * mpage_readpages). If an allocation happens for the
704                  * second or third page, the process can end up locking
705                  * the same page twice and deadlocking. Rather than
706                  * trying to be clever about what pages can be locked,
707                  * avoid the use of lock_page for direct compaction
708                  * altogether.
709                  */
710                 if (current->flags & PF_MEMALLOC)
711                         goto out;
712
713                 lock_page(page);
714         }
715
716         /*
717          * Only memory hotplug's offline_pages() caller has locked out KSM,
718          * and can safely migrate a KSM page.  The other cases have skipped
719          * PageKsm along with PageReserved - but it is only now when we have
720          * the page lock that we can be certain it will not go KSM beneath us
721          * (KSM will not upgrade a page from PageAnon to PageKsm when it sees
722          * its pagecount raised, but only here do we take the page lock which
723          * serializes that).
724          */
725         if (PageKsm(page) && !offlining) {
726                 rc = -EBUSY;
727                 goto unlock;
728         }
729
730         /* charge against new page */
731         mem_cgroup_prepare_migration(page, newpage, &mem);
732
733         if (PageWriteback(page)) {
734                 /*
735                  * Only in the case of a full syncronous migration is it
736                  * necessary to wait for PageWriteback. In the async case,
737                  * the retry loop is too short and in the sync-light case,
738                  * the overhead of stalling is too much
739                  */
740                 if (mode != MIGRATE_SYNC) {
741                         rc = -EBUSY;
742                         goto uncharge;
743                 }
744                 if (!force)
745                         goto uncharge;
746                 wait_on_page_writeback(page);
747         }
748         /*
749          * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
750          * we cannot notice that anon_vma is freed while we migrates a page.
751          * This get_anon_vma() delays freeing anon_vma pointer until the end
752          * of migration. File cache pages are no problem because of page_lock()
753          * File Caches may use write_page() or lock_page() in migration, then,
754          * just care Anon page here.
755          */
756         if (PageAnon(page)) {
757                 /*
758                  * Only page_lock_anon_vma() understands the subtleties of
759                  * getting a hold on an anon_vma from outside one of its mms.
760                  */
761                 anon_vma = page_get_anon_vma(page);
762                 if (anon_vma) {
763                         /*
764                          * Anon page
765                          */
766                 } else if (PageSwapCache(page)) {
767                         /*
768                          * We cannot be sure that the anon_vma of an unmapped
769                          * swapcache page is safe to use because we don't
770                          * know in advance if the VMA that this page belonged
771                          * to still exists. If the VMA and others sharing the
772                          * data have been freed, then the anon_vma could
773                          * already be invalid.
774                          *
775                          * To avoid this possibility, swapcache pages get
776                          * migrated but are not remapped when migration
777                          * completes
778                          */
779                         remap_swapcache = 0;
780                 } else {
781                         goto uncharge;
782                 }
783         }
784
785         if (unlikely(balloon_page_movable(page))) {
786                 /*
787                  * A ballooned page does not need any special attention from
788                  * physical to virtual reverse mapping procedures.
789                  * Skip any attempt to unmap PTEs or to remap swap cache,
790                  * in order to avoid burning cycles at rmap level, and perform
791                  * the page migration right away (proteced by page lock).
792                  */
793                 rc = balloon_page_migrate(newpage, page, mode);
794                 goto uncharge;
795         }
796
797         /*
798          * Corner case handling:
799          * 1. When a new swap-cache page is read into, it is added to the LRU
800          * and treated as swapcache but it has no rmap yet.
801          * Calling try_to_unmap() against a page->mapping==NULL page will
802          * trigger a BUG.  So handle it here.
803          * 2. An orphaned page (see truncate_complete_page) might have
804          * fs-private metadata. The page can be picked up due to memory
805          * offlining.  Everywhere else except page reclaim, the page is
806          * invisible to the vm, so the page can not be migrated.  So try to
807          * free the metadata, so the page can be freed.
808          */
809         if (!page->mapping) {
810                 VM_BUG_ON(PageAnon(page));
811                 if (page_has_private(page)) {
812                         try_to_free_buffers(page);
813                         goto uncharge;
814                 }
815                 goto skip_unmap;
816         }
817
818         /* Establish migration ptes or remove ptes */
819         try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
820
821 skip_unmap:
822         if (!page_mapped(page))
823                 rc = move_to_new_page(newpage, page, remap_swapcache, mode);
824
825         if (rc && remap_swapcache)
826                 remove_migration_ptes(page, page);
827
828         /* Drop an anon_vma reference if we took one */
829         if (anon_vma)
830                 put_anon_vma(anon_vma);
831
832 uncharge:
833         mem_cgroup_end_migration(mem, page, newpage,
834                                  (rc == MIGRATEPAGE_SUCCESS ||
835                                   rc == MIGRATEPAGE_BALLOON_SUCCESS));
836 unlock:
837         unlock_page(page);
838 out:
839         return rc;
840 }
841
842 /*
843  * Obtain the lock on page, remove all ptes and migrate the page
844  * to the newly allocated page in newpage.
845  */
846 static int unmap_and_move(new_page_t get_new_page, unsigned long private,
847                         struct page *page, int force, bool offlining,
848                         enum migrate_mode mode)
849 {
850         int rc = 0;
851         int *result = NULL;
852         struct page *newpage = get_new_page(page, private, &result);
853
854         if (!newpage)
855                 return -ENOMEM;
856
857         if (page_count(page) == 1) {
858                 /* page was freed from under us. So we are done. */
859                 goto out;
860         }
861
862         if (unlikely(PageTransHuge(page)))
863                 if (unlikely(split_huge_page(page)))
864                         goto out;
865
866         rc = __unmap_and_move(page, newpage, force, offlining, mode);
867
868         if (unlikely(rc == MIGRATEPAGE_BALLOON_SUCCESS)) {
869                 /*
870                  * A ballooned page has been migrated already.
871                  * Now, it's the time to remove the old page from the isolated
872                  * pageset list and handle it back to Buddy, wrap-up counters
873                  * and return.
874                  */
875                 dec_zone_page_state(page, NR_ISOLATED_ANON +
876                                     page_is_file_cache(page));
877                 put_page(page);
878                 __free_page(page);
879                 return 0;
880         }
881 out:
882         if (rc != -EAGAIN) {
883                 /*
884                  * A page that has been migrated has all references
885                  * removed and will be freed. A page that has not been
886                  * migrated will have kepts its references and be
887                  * restored.
888                  */
889                 list_del(&page->lru);
890                 dec_zone_page_state(page, NR_ISOLATED_ANON +
891                                 page_is_file_cache(page));
892                 putback_lru_page(page);
893         }
894         /*
895          * Move the new page to the LRU. If migration was not successful
896          * then this will free the page.
897          */
898         putback_lru_page(newpage);
899         if (result) {
900                 if (rc)
901                         *result = rc;
902                 else
903                         *result = page_to_nid(newpage);
904         }
905         return rc;
906 }
907
908 /*
909  * Counterpart of unmap_and_move_page() for hugepage migration.
910  *
911  * This function doesn't wait the completion of hugepage I/O
912  * because there is no race between I/O and migration for hugepage.
913  * Note that currently hugepage I/O occurs only in direct I/O
914  * where no lock is held and PG_writeback is irrelevant,
915  * and writeback status of all subpages are counted in the reference
916  * count of the head page (i.e. if all subpages of a 2MB hugepage are
917  * under direct I/O, the reference of the head page is 512 and a bit more.)
918  * This means that when we try to migrate hugepage whose subpages are
919  * doing direct I/O, some references remain after try_to_unmap() and
920  * hugepage migration fails without data corruption.
921  *
922  * There is also no race when direct I/O is issued on the page under migration,
923  * because then pte is replaced with migration swap entry and direct I/O code
924  * will wait in the page fault for migration to complete.
925  */
926 static int unmap_and_move_huge_page(new_page_t get_new_page,
927                                 unsigned long private, struct page *hpage,
928                                 int force, bool offlining,
929                                 enum migrate_mode mode)
930 {
931         int rc = 0;
932         int *result = NULL;
933         struct page *new_hpage = get_new_page(hpage, private, &result);
934         struct anon_vma *anon_vma = NULL;
935
936         if (!new_hpage)
937                 return -ENOMEM;
938
939         rc = -EAGAIN;
940
941         if (!trylock_page(hpage)) {
942                 if (!force || mode != MIGRATE_SYNC)
943                         goto out;
944                 lock_page(hpage);
945         }
946
947         if (PageAnon(hpage))
948                 anon_vma = page_get_anon_vma(hpage);
949
950         try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
951
952         if (!page_mapped(hpage))
953                 rc = move_to_new_page(new_hpage, hpage, 1, mode);
954
955         if (rc)
956                 remove_migration_ptes(hpage, hpage);
957
958         if (anon_vma)
959                 put_anon_vma(anon_vma);
960
961         if (!rc)
962                 hugetlb_cgroup_migrate(hpage, new_hpage);
963
964         unlock_page(hpage);
965 out:
966         put_page(new_hpage);
967         if (result) {
968                 if (rc)
969                         *result = rc;
970                 else
971                         *result = page_to_nid(new_hpage);
972         }
973         return rc;
974 }
975
976 /*
977  * migrate_pages
978  *
979  * The function takes one list of pages to migrate and a function
980  * that determines from the page to be migrated and the private data
981  * the target of the move and allocates the page.
982  *
983  * The function returns after 10 attempts or if no pages
984  * are movable anymore because to has become empty
985  * or no retryable pages exist anymore.
986  * Caller should call putback_lru_pages to return pages to the LRU
987  * or free list only if ret != 0.
988  *
989  * Return: Number of pages not migrated or error code.
990  */
991 int migrate_pages(struct list_head *from,
992                 new_page_t get_new_page, unsigned long private, bool offlining,
993                 enum migrate_mode mode)
994 {
995         int retry = 1;
996         int nr_failed = 0;
997         int pass = 0;
998         struct page *page;
999         struct page *page2;
1000         int swapwrite = current->flags & PF_SWAPWRITE;
1001         int rc;
1002
1003         if (!swapwrite)
1004                 current->flags |= PF_SWAPWRITE;
1005
1006         for(pass = 0; pass < 10 && retry; pass++) {
1007                 retry = 0;
1008
1009                 list_for_each_entry_safe(page, page2, from, lru) {
1010                         cond_resched();
1011
1012                         rc = unmap_and_move(get_new_page, private,
1013                                                 page, pass > 2, offlining,
1014                                                 mode);
1015
1016                         switch(rc) {
1017                         case -ENOMEM:
1018                                 goto out;
1019                         case -EAGAIN:
1020                                 retry++;
1021                                 break;
1022                         case MIGRATEPAGE_SUCCESS:
1023                                 break;
1024                         default:
1025                                 /* Permanent failure */
1026                                 nr_failed++;
1027                                 break;
1028                         }
1029                 }
1030         }
1031         rc = nr_failed + retry;
1032 out:
1033         if (!swapwrite)
1034                 current->flags &= ~PF_SWAPWRITE;
1035
1036         return rc;
1037 }
1038
1039 int migrate_huge_page(struct page *hpage, new_page_t get_new_page,
1040                       unsigned long private, bool offlining,
1041                       enum migrate_mode mode)
1042 {
1043         int pass, rc;
1044
1045         for (pass = 0; pass < 10; pass++) {
1046                 rc = unmap_and_move_huge_page(get_new_page,
1047                                               private, hpage, pass > 2, offlining,
1048                                               mode);
1049                 switch (rc) {
1050                 case -ENOMEM:
1051                         goto out;
1052                 case -EAGAIN:
1053                         /* try again */
1054                         cond_resched();
1055                         break;
1056                 case MIGRATEPAGE_SUCCESS:
1057                         goto out;
1058                 default:
1059                         rc = -EIO;
1060                         goto out;
1061                 }
1062         }
1063 out:
1064         return rc;
1065 }
1066
1067 #ifdef CONFIG_NUMA
1068 /*
1069  * Move a list of individual pages
1070  */
1071 struct page_to_node {
1072         unsigned long addr;
1073         struct page *page;
1074         int node;
1075         int status;
1076 };
1077
1078 static struct page *new_page_node(struct page *p, unsigned long private,
1079                 int **result)
1080 {
1081         struct page_to_node *pm = (struct page_to_node *)private;
1082
1083         while (pm->node != MAX_NUMNODES && pm->page != p)
1084                 pm++;
1085
1086         if (pm->node == MAX_NUMNODES)
1087                 return NULL;
1088
1089         *result = &pm->status;
1090
1091         return alloc_pages_exact_node(pm->node,
1092                                 GFP_HIGHUSER_MOVABLE | GFP_THISNODE, 0);
1093 }
1094
1095 /*
1096  * Move a set of pages as indicated in the pm array. The addr
1097  * field must be set to the virtual address of the page to be moved
1098  * and the node number must contain a valid target node.
1099  * The pm array ends with node = MAX_NUMNODES.
1100  */
1101 static int do_move_page_to_node_array(struct mm_struct *mm,
1102                                       struct page_to_node *pm,
1103                                       int migrate_all)
1104 {
1105         int err;
1106         struct page_to_node *pp;
1107         LIST_HEAD(pagelist);
1108
1109         down_read(&mm->mmap_sem);
1110
1111         /*
1112          * Build a list of pages to migrate
1113          */
1114         for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
1115                 struct vm_area_struct *vma;
1116                 struct page *page;
1117
1118                 err = -EFAULT;
1119                 vma = find_vma(mm, pp->addr);
1120                 if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
1121                         goto set_status;
1122
1123                 page = follow_page(vma, pp->addr, FOLL_GET|FOLL_SPLIT);
1124
1125                 err = PTR_ERR(page);
1126                 if (IS_ERR(page))
1127                         goto set_status;
1128
1129                 err = -ENOENT;
1130                 if (!page)
1131                         goto set_status;
1132
1133                 /* Use PageReserved to check for zero page */
1134                 if (PageReserved(page) || PageKsm(page))
1135                         goto put_and_set;
1136
1137                 pp->page = page;
1138                 err = page_to_nid(page);
1139
1140                 if (err == pp->node)
1141                         /*
1142                          * Node already in the right place
1143                          */
1144                         goto put_and_set;
1145
1146                 err = -EACCES;
1147                 if (page_mapcount(page) > 1 &&
1148                                 !migrate_all)
1149                         goto put_and_set;
1150
1151                 err = isolate_lru_page(page);
1152                 if (!err) {
1153                         list_add_tail(&page->lru, &pagelist);
1154                         inc_zone_page_state(page, NR_ISOLATED_ANON +
1155                                             page_is_file_cache(page));
1156                 }
1157 put_and_set:
1158                 /*
1159                  * Either remove the duplicate refcount from
1160                  * isolate_lru_page() or drop the page ref if it was
1161                  * not isolated.
1162                  */
1163                 put_page(page);
1164 set_status:
1165                 pp->status = err;
1166         }
1167
1168         err = 0;
1169         if (!list_empty(&pagelist)) {
1170                 err = migrate_pages(&pagelist, new_page_node,
1171                                 (unsigned long)pm, 0, MIGRATE_SYNC);
1172                 if (err)
1173                         putback_lru_pages(&pagelist);
1174         }
1175
1176         up_read(&mm->mmap_sem);
1177         return err;
1178 }
1179
1180 /*
1181  * Migrate an array of page address onto an array of nodes and fill
1182  * the corresponding array of status.
1183  */
1184 static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
1185                          unsigned long nr_pages,
1186                          const void __user * __user *pages,
1187                          const int __user *nodes,
1188                          int __user *status, int flags)
1189 {
1190         struct page_to_node *pm;
1191         unsigned long chunk_nr_pages;
1192         unsigned long chunk_start;
1193         int err;
1194
1195         err = -ENOMEM;
1196         pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
1197         if (!pm)
1198                 goto out;
1199
1200         migrate_prep();
1201
1202         /*
1203          * Store a chunk of page_to_node array in a page,
1204          * but keep the last one as a marker
1205          */
1206         chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
1207
1208         for (chunk_start = 0;
1209              chunk_start < nr_pages;
1210              chunk_start += chunk_nr_pages) {
1211                 int j;
1212
1213                 if (chunk_start + chunk_nr_pages > nr_pages)
1214                         chunk_nr_pages = nr_pages - chunk_start;
1215
1216                 /* fill the chunk pm with addrs and nodes from user-space */
1217                 for (j = 0; j < chunk_nr_pages; j++) {
1218                         const void __user *p;
1219                         int node;
1220
1221                         err = -EFAULT;
1222                         if (get_user(p, pages + j + chunk_start))
1223                                 goto out_pm;
1224                         pm[j].addr = (unsigned long) p;
1225
1226                         if (get_user(node, nodes + j + chunk_start))
1227                                 goto out_pm;
1228
1229                         err = -ENODEV;
1230                         if (node < 0 || node >= MAX_NUMNODES)
1231                                 goto out_pm;
1232
1233                         if (!node_state(node, N_HIGH_MEMORY))
1234                                 goto out_pm;
1235
1236                         err = -EACCES;
1237                         if (!node_isset(node, task_nodes))
1238                                 goto out_pm;
1239
1240                         pm[j].node = node;
1241                 }
1242
1243                 /* End marker for this chunk */
1244                 pm[chunk_nr_pages].node = MAX_NUMNODES;
1245
1246                 /* Migrate this chunk */
1247                 err = do_move_page_to_node_array(mm, pm,
1248                                                  flags & MPOL_MF_MOVE_ALL);
1249                 if (err < 0)
1250                         goto out_pm;
1251
1252                 /* Return status information */
1253                 for (j = 0; j < chunk_nr_pages; j++)
1254                         if (put_user(pm[j].status, status + j + chunk_start)) {
1255                                 err = -EFAULT;
1256                                 goto out_pm;
1257                         }
1258         }
1259         err = 0;
1260
1261 out_pm:
1262         free_page((unsigned long)pm);
1263 out:
1264         return err;
1265 }
1266
1267 /*
1268  * Determine the nodes of an array of pages and store it in an array of status.
1269  */
1270 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
1271                                 const void __user **pages, int *status)
1272 {
1273         unsigned long i;
1274
1275         down_read(&mm->mmap_sem);
1276
1277         for (i = 0; i < nr_pages; i++) {
1278                 unsigned long addr = (unsigned long)(*pages);
1279                 struct vm_area_struct *vma;
1280                 struct page *page;
1281                 int err = -EFAULT;
1282
1283                 vma = find_vma(mm, addr);
1284                 if (!vma || addr < vma->vm_start)
1285                         goto set_status;
1286
1287                 page = follow_page(vma, addr, 0);
1288
1289                 err = PTR_ERR(page);
1290                 if (IS_ERR(page))
1291                         goto set_status;
1292
1293                 err = -ENOENT;
1294                 /* Use PageReserved to check for zero page */
1295                 if (!page || PageReserved(page) || PageKsm(page))
1296                         goto set_status;
1297
1298                 err = page_to_nid(page);
1299 set_status:
1300                 *status = err;
1301
1302                 pages++;
1303                 status++;
1304         }
1305
1306         up_read(&mm->mmap_sem);
1307 }
1308
1309 /*
1310  * Determine the nodes of a user array of pages and store it in
1311  * a user array of status.
1312  */
1313 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1314                          const void __user * __user *pages,
1315                          int __user *status)
1316 {
1317 #define DO_PAGES_STAT_CHUNK_NR 16
1318         const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1319         int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1320
1321         while (nr_pages) {
1322                 unsigned long chunk_nr;
1323
1324                 chunk_nr = nr_pages;
1325                 if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1326                         chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1327
1328                 if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1329                         break;
1330
1331                 do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1332
1333                 if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1334                         break;
1335
1336                 pages += chunk_nr;
1337                 status += chunk_nr;
1338                 nr_pages -= chunk_nr;
1339         }
1340         return nr_pages ? -EFAULT : 0;
1341 }
1342
1343 /*
1344  * Move a list of pages in the address space of the currently executing
1345  * process.
1346  */
1347 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1348                 const void __user * __user *, pages,
1349                 const int __user *, nodes,
1350                 int __user *, status, int, flags)
1351 {
1352         const struct cred *cred = current_cred(), *tcred;
1353         struct task_struct *task;
1354         struct mm_struct *mm;
1355         int err;
1356         nodemask_t task_nodes;
1357
1358         /* Check flags */
1359         if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1360                 return -EINVAL;
1361
1362         if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1363                 return -EPERM;
1364
1365         /* Find the mm_struct */
1366         rcu_read_lock();
1367         task = pid ? find_task_by_vpid(pid) : current;
1368         if (!task) {
1369                 rcu_read_unlock();
1370                 return -ESRCH;
1371         }
1372         get_task_struct(task);
1373
1374         /*
1375          * Check if this process has the right to modify the specified
1376          * process. The right exists if the process has administrative
1377          * capabilities, superuser privileges or the same
1378          * userid as the target process.
1379          */
1380         tcred = __task_cred(task);
1381         if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
1382             !uid_eq(cred->uid,  tcred->suid) && !uid_eq(cred->uid,  tcred->uid) &&
1383             !capable(CAP_SYS_NICE)) {
1384                 rcu_read_unlock();
1385                 err = -EPERM;
1386                 goto out;
1387         }
1388         rcu_read_unlock();
1389
1390         err = security_task_movememory(task);
1391         if (err)
1392                 goto out;
1393
1394         task_nodes = cpuset_mems_allowed(task);
1395         mm = get_task_mm(task);
1396         put_task_struct(task);
1397
1398         if (!mm)
1399                 return -EINVAL;
1400
1401         if (nodes)
1402                 err = do_pages_move(mm, task_nodes, nr_pages, pages,
1403                                     nodes, status, flags);
1404         else
1405                 err = do_pages_stat(mm, nr_pages, pages, status);
1406
1407         mmput(mm);
1408         return err;
1409
1410 out:
1411         put_task_struct(task);
1412         return err;
1413 }
1414
1415 /*
1416  * Call migration functions in the vma_ops that may prepare
1417  * memory in a vm for migration. migration functions may perform
1418  * the migration for vmas that do not have an underlying page struct.
1419  */
1420 int migrate_vmas(struct mm_struct *mm, const nodemask_t *to,
1421         const nodemask_t *from, unsigned long flags)
1422 {
1423         struct vm_area_struct *vma;
1424         int err = 0;
1425
1426         for (vma = mm->mmap; vma && !err; vma = vma->vm_next) {
1427                 if (vma->vm_ops && vma->vm_ops->migrate) {
1428                         err = vma->vm_ops->migrate(vma, to, from, flags);
1429                         if (err)
1430                                 break;
1431                 }
1432         }
1433         return err;
1434 }
1435
1436 /*
1437  * Attempt to migrate a misplaced page to the specified destination
1438  * node.
1439  */
1440 int migrate_misplaced_page(struct page *page, int node)
1441 {
1442         struct address_space *mapping = page_mapping(page);
1443         int page_lru = page_is_file_cache(page);
1444         struct page *newpage;
1445         int ret = -EAGAIN;
1446         gfp_t gfp = GFP_HIGHUSER_MOVABLE;
1447
1448         /*
1449          * Don't migrate pages that are mapped in multiple processes.
1450          */
1451         if (page_mapcount(page) != 1)
1452                 goto out;
1453
1454         /*
1455          * Never wait for allocations just to migrate on fault, but don't dip
1456          * into reserves. And, only accept pages from the specified node. No
1457          * sense migrating to a different "misplaced" page!
1458          */
1459         if (mapping)
1460                 gfp = mapping_gfp_mask(mapping);
1461         gfp &= ~__GFP_WAIT;
1462         gfp |= __GFP_NOMEMALLOC | GFP_THISNODE;
1463
1464         newpage = alloc_pages_node(node, gfp, 0);
1465         if (!newpage) {
1466                 ret = -ENOMEM;
1467                 goto out;
1468         }
1469
1470         if (isolate_lru_page(page)) {
1471                 ret = -EBUSY;
1472                 goto put_new;
1473         }
1474
1475         inc_zone_page_state(page, NR_ISOLATED_ANON + page_lru);
1476         ret = __unmap_and_move(page, newpage, 0, 0, MIGRATE_FAULT);
1477         /*
1478          * A page that has been migrated has all references removed and will be
1479          * freed. A page that has not been migrated will have kepts its
1480          * references and be restored.
1481          */
1482         dec_zone_page_state(page, NR_ISOLATED_ANON + page_lru);
1483         putback_lru_page(page);
1484 put_new:
1485         /*
1486          * Move the new page to the LRU. If migration was not successful
1487          * then this will free the page.
1488          */
1489         putback_lru_page(newpage);
1490 out:
1491         return ret;
1492 }
1493
1494 #endif /* CONFIG_NUMA */