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