xref: /openbmc/linux/mm/migrate.c (revision 3fe2011ff51e92500010a495df4be86745fbbda9)
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/module.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/gfp.h>
36 
37 #include "internal.h"
38 
39 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
40 
41 /*
42  * migrate_prep() needs to be called before we start compiling a list of pages
43  * to be migrated using isolate_lru_page().
44  */
45 int migrate_prep(void)
46 {
47 	/*
48 	 * Clear the LRU lists so pages can be isolated.
49 	 * Note that pages may be moved off the LRU after we have
50 	 * drained them. Those pages will fail to migrate like other
51 	 * pages that may be busy.
52 	 */
53 	lru_add_drain_all();
54 
55 	return 0;
56 }
57 
58 /*
59  * Add isolated pages on the list back to the LRU under page lock
60  * to avoid leaking evictable pages back onto unevictable list.
61  */
62 void putback_lru_pages(struct list_head *l)
63 {
64 	struct page *page;
65 	struct page *page2;
66 
67 	list_for_each_entry_safe(page, page2, l, lru) {
68 		list_del(&page->lru);
69 		dec_zone_page_state(page, NR_ISOLATED_ANON +
70 				page_is_file_cache(page));
71 		putback_lru_page(page);
72 	}
73 }
74 
75 /*
76  * Restore a potential migration pte to a working pte entry
77  */
78 static int remove_migration_pte(struct page *new, struct vm_area_struct *vma,
79 				 unsigned long addr, void *old)
80 {
81 	struct mm_struct *mm = vma->vm_mm;
82 	swp_entry_t entry;
83  	pgd_t *pgd;
84  	pud_t *pud;
85  	pmd_t *pmd;
86 	pte_t *ptep, pte;
87  	spinlock_t *ptl;
88 
89  	pgd = pgd_offset(mm, addr);
90 	if (!pgd_present(*pgd))
91 		goto out;
92 
93 	pud = pud_offset(pgd, addr);
94 	if (!pud_present(*pud))
95 		goto out;
96 
97 	pmd = pmd_offset(pud, addr);
98 	if (!pmd_present(*pmd))
99 		goto out;
100 
101 	ptep = pte_offset_map(pmd, addr);
102 
103 	if (!is_swap_pte(*ptep)) {
104 		pte_unmap(ptep);
105 		goto out;
106  	}
107 
108  	ptl = pte_lockptr(mm, pmd);
109  	spin_lock(ptl);
110 	pte = *ptep;
111 	if (!is_swap_pte(pte))
112 		goto unlock;
113 
114 	entry = pte_to_swp_entry(pte);
115 
116 	if (!is_migration_entry(entry) ||
117 	    migration_entry_to_page(entry) != old)
118 		goto unlock;
119 
120 	get_page(new);
121 	pte = pte_mkold(mk_pte(new, vma->vm_page_prot));
122 	if (is_write_migration_entry(entry))
123 		pte = pte_mkwrite(pte);
124 	flush_cache_page(vma, addr, pte_pfn(pte));
125 	set_pte_at(mm, addr, ptep, pte);
126 
127 	if (PageAnon(new))
128 		page_add_anon_rmap(new, vma, addr);
129 	else
130 		page_add_file_rmap(new);
131 
132 	/* No need to invalidate - it was non-present before */
133 	update_mmu_cache(vma, addr, ptep);
134 unlock:
135 	pte_unmap_unlock(ptep, ptl);
136 out:
137 	return SWAP_AGAIN;
138 }
139 
140 /*
141  * Get rid of all migration entries and replace them by
142  * references to the indicated page.
143  */
144 static void remove_migration_ptes(struct page *old, struct page *new)
145 {
146 	rmap_walk(new, remove_migration_pte, old);
147 }
148 
149 /*
150  * Something used the pte of a page under migration. We need to
151  * get to the page and wait until migration is finished.
152  * When we return from this function the fault will be retried.
153  *
154  * This function is called from do_swap_page().
155  */
156 void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
157 				unsigned long address)
158 {
159 	pte_t *ptep, pte;
160 	spinlock_t *ptl;
161 	swp_entry_t entry;
162 	struct page *page;
163 
164 	ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
165 	pte = *ptep;
166 	if (!is_swap_pte(pte))
167 		goto out;
168 
169 	entry = pte_to_swp_entry(pte);
170 	if (!is_migration_entry(entry))
171 		goto out;
172 
173 	page = migration_entry_to_page(entry);
174 
175 	/*
176 	 * Once radix-tree replacement of page migration started, page_count
177 	 * *must* be zero. And, we don't want to call wait_on_page_locked()
178 	 * against a page without get_page().
179 	 * So, we use get_page_unless_zero(), here. Even failed, page fault
180 	 * will occur again.
181 	 */
182 	if (!get_page_unless_zero(page))
183 		goto out;
184 	pte_unmap_unlock(ptep, ptl);
185 	wait_on_page_locked(page);
186 	put_page(page);
187 	return;
188 out:
189 	pte_unmap_unlock(ptep, ptl);
190 }
191 
192 /*
193  * Replace the page in the mapping.
194  *
195  * The number of remaining references must be:
196  * 1 for anonymous pages without a mapping
197  * 2 for pages with a mapping
198  * 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
199  */
200 static int migrate_page_move_mapping(struct address_space *mapping,
201 		struct page *newpage, struct page *page)
202 {
203 	int expected_count;
204 	void **pslot;
205 
206 	if (!mapping) {
207 		/* Anonymous page without mapping */
208 		if (page_count(page) != 1)
209 			return -EAGAIN;
210 		return 0;
211 	}
212 
213 	spin_lock_irq(&mapping->tree_lock);
214 
215 	pslot = radix_tree_lookup_slot(&mapping->page_tree,
216  					page_index(page));
217 
218 	expected_count = 2 + page_has_private(page);
219 	if (page_count(page) != expected_count ||
220 			(struct page *)radix_tree_deref_slot(pslot) != page) {
221 		spin_unlock_irq(&mapping->tree_lock);
222 		return -EAGAIN;
223 	}
224 
225 	if (!page_freeze_refs(page, expected_count)) {
226 		spin_unlock_irq(&mapping->tree_lock);
227 		return -EAGAIN;
228 	}
229 
230 	/*
231 	 * Now we know that no one else is looking at the page.
232 	 */
233 	get_page(newpage);	/* add cache reference */
234 	if (PageSwapCache(page)) {
235 		SetPageSwapCache(newpage);
236 		set_page_private(newpage, page_private(page));
237 	}
238 
239 	radix_tree_replace_slot(pslot, newpage);
240 
241 	page_unfreeze_refs(page, expected_count);
242 	/*
243 	 * Drop cache reference from old page.
244 	 * We know this isn't the last reference.
245 	 */
246 	__put_page(page);
247 
248 	/*
249 	 * If moved to a different zone then also account
250 	 * the page for that zone. Other VM counters will be
251 	 * taken care of when we establish references to the
252 	 * new page and drop references to the old page.
253 	 *
254 	 * Note that anonymous pages are accounted for
255 	 * via NR_FILE_PAGES and NR_ANON_PAGES if they
256 	 * are mapped to swap space.
257 	 */
258 	__dec_zone_page_state(page, NR_FILE_PAGES);
259 	__inc_zone_page_state(newpage, NR_FILE_PAGES);
260 	if (PageSwapBacked(page)) {
261 		__dec_zone_page_state(page, NR_SHMEM);
262 		__inc_zone_page_state(newpage, NR_SHMEM);
263 	}
264 	spin_unlock_irq(&mapping->tree_lock);
265 
266 	return 0;
267 }
268 
269 /*
270  * Copy the page to its new location
271  */
272 static void migrate_page_copy(struct page *newpage, struct page *page)
273 {
274 	copy_highpage(newpage, page);
275 
276 	if (PageError(page))
277 		SetPageError(newpage);
278 	if (PageReferenced(page))
279 		SetPageReferenced(newpage);
280 	if (PageUptodate(page))
281 		SetPageUptodate(newpage);
282 	if (TestClearPageActive(page)) {
283 		VM_BUG_ON(PageUnevictable(page));
284 		SetPageActive(newpage);
285 	} else if (TestClearPageUnevictable(page))
286 		SetPageUnevictable(newpage);
287 	if (PageChecked(page))
288 		SetPageChecked(newpage);
289 	if (PageMappedToDisk(page))
290 		SetPageMappedToDisk(newpage);
291 
292 	if (PageDirty(page)) {
293 		clear_page_dirty_for_io(page);
294 		/*
295 		 * Want to mark the page and the radix tree as dirty, and
296 		 * redo the accounting that clear_page_dirty_for_io undid,
297 		 * but we can't use set_page_dirty because that function
298 		 * is actually a signal that all of the page has become dirty.
299 		 * Wheras only part of our page may be dirty.
300 		 */
301 		__set_page_dirty_nobuffers(newpage);
302  	}
303 
304 	mlock_migrate_page(newpage, page);
305 	ksm_migrate_page(newpage, page);
306 
307 	ClearPageSwapCache(page);
308 	ClearPagePrivate(page);
309 	set_page_private(page, 0);
310 	page->mapping = NULL;
311 
312 	/*
313 	 * If any waiters have accumulated on the new page then
314 	 * wake them up.
315 	 */
316 	if (PageWriteback(newpage))
317 		end_page_writeback(newpage);
318 }
319 
320 /************************************************************
321  *                    Migration functions
322  ***********************************************************/
323 
324 /* Always fail migration. Used for mappings that are not movable */
325 int fail_migrate_page(struct address_space *mapping,
326 			struct page *newpage, struct page *page)
327 {
328 	return -EIO;
329 }
330 EXPORT_SYMBOL(fail_migrate_page);
331 
332 /*
333  * Common logic to directly migrate a single page suitable for
334  * pages that do not use PagePrivate/PagePrivate2.
335  *
336  * Pages are locked upon entry and exit.
337  */
338 int migrate_page(struct address_space *mapping,
339 		struct page *newpage, struct page *page)
340 {
341 	int rc;
342 
343 	BUG_ON(PageWriteback(page));	/* Writeback must be complete */
344 
345 	rc = migrate_page_move_mapping(mapping, newpage, page);
346 
347 	if (rc)
348 		return rc;
349 
350 	migrate_page_copy(newpage, page);
351 	return 0;
352 }
353 EXPORT_SYMBOL(migrate_page);
354 
355 #ifdef CONFIG_BLOCK
356 /*
357  * Migration function for pages with buffers. This function can only be used
358  * if the underlying filesystem guarantees that no other references to "page"
359  * exist.
360  */
361 int buffer_migrate_page(struct address_space *mapping,
362 		struct page *newpage, struct page *page)
363 {
364 	struct buffer_head *bh, *head;
365 	int rc;
366 
367 	if (!page_has_buffers(page))
368 		return migrate_page(mapping, newpage, page);
369 
370 	head = page_buffers(page);
371 
372 	rc = migrate_page_move_mapping(mapping, newpage, page);
373 
374 	if (rc)
375 		return rc;
376 
377 	bh = head;
378 	do {
379 		get_bh(bh);
380 		lock_buffer(bh);
381 		bh = bh->b_this_page;
382 
383 	} while (bh != head);
384 
385 	ClearPagePrivate(page);
386 	set_page_private(newpage, page_private(page));
387 	set_page_private(page, 0);
388 	put_page(page);
389 	get_page(newpage);
390 
391 	bh = head;
392 	do {
393 		set_bh_page(bh, newpage, bh_offset(bh));
394 		bh = bh->b_this_page;
395 
396 	} while (bh != head);
397 
398 	SetPagePrivate(newpage);
399 
400 	migrate_page_copy(newpage, page);
401 
402 	bh = head;
403 	do {
404 		unlock_buffer(bh);
405  		put_bh(bh);
406 		bh = bh->b_this_page;
407 
408 	} while (bh != head);
409 
410 	return 0;
411 }
412 EXPORT_SYMBOL(buffer_migrate_page);
413 #endif
414 
415 /*
416  * Writeback a page to clean the dirty state
417  */
418 static int writeout(struct address_space *mapping, struct page *page)
419 {
420 	struct writeback_control wbc = {
421 		.sync_mode = WB_SYNC_NONE,
422 		.nr_to_write = 1,
423 		.range_start = 0,
424 		.range_end = LLONG_MAX,
425 		.nonblocking = 1,
426 		.for_reclaim = 1
427 	};
428 	int rc;
429 
430 	if (!mapping->a_ops->writepage)
431 		/* No write method for the address space */
432 		return -EINVAL;
433 
434 	if (!clear_page_dirty_for_io(page))
435 		/* Someone else already triggered a write */
436 		return -EAGAIN;
437 
438 	/*
439 	 * A dirty page may imply that the underlying filesystem has
440 	 * the page on some queue. So the page must be clean for
441 	 * migration. Writeout may mean we loose the lock and the
442 	 * page state is no longer what we checked for earlier.
443 	 * At this point we know that the migration attempt cannot
444 	 * be successful.
445 	 */
446 	remove_migration_ptes(page, page);
447 
448 	rc = mapping->a_ops->writepage(page, &wbc);
449 
450 	if (rc != AOP_WRITEPAGE_ACTIVATE)
451 		/* unlocked. Relock */
452 		lock_page(page);
453 
454 	return (rc < 0) ? -EIO : -EAGAIN;
455 }
456 
457 /*
458  * Default handling if a filesystem does not provide a migration function.
459  */
460 static int fallback_migrate_page(struct address_space *mapping,
461 	struct page *newpage, struct page *page)
462 {
463 	if (PageDirty(page))
464 		return writeout(mapping, page);
465 
466 	/*
467 	 * Buffers may be managed in a filesystem specific way.
468 	 * We must have no buffers or drop them.
469 	 */
470 	if (page_has_private(page) &&
471 	    !try_to_release_page(page, GFP_KERNEL))
472 		return -EAGAIN;
473 
474 	return migrate_page(mapping, newpage, page);
475 }
476 
477 /*
478  * Move a page to a newly allocated page
479  * The page is locked and all ptes have been successfully removed.
480  *
481  * The new page will have replaced the old page if this function
482  * is successful.
483  *
484  * Return value:
485  *   < 0 - error code
486  *  == 0 - success
487  */
488 static int move_to_new_page(struct page *newpage, struct page *page,
489 						int remap_swapcache)
490 {
491 	struct address_space *mapping;
492 	int rc;
493 
494 	/*
495 	 * Block others from accessing the page when we get around to
496 	 * establishing additional references. We are the only one
497 	 * holding a reference to the new page at this point.
498 	 */
499 	if (!trylock_page(newpage))
500 		BUG();
501 
502 	/* Prepare mapping for the new page.*/
503 	newpage->index = page->index;
504 	newpage->mapping = page->mapping;
505 	if (PageSwapBacked(page))
506 		SetPageSwapBacked(newpage);
507 
508 	mapping = page_mapping(page);
509 	if (!mapping)
510 		rc = migrate_page(mapping, newpage, page);
511 	else if (mapping->a_ops->migratepage)
512 		/*
513 		 * Most pages have a mapping and most filesystems
514 		 * should provide a migration function. Anonymous
515 		 * pages are part of swap space which also has its
516 		 * own migration function. This is the most common
517 		 * path for page migration.
518 		 */
519 		rc = mapping->a_ops->migratepage(mapping,
520 						newpage, page);
521 	else
522 		rc = fallback_migrate_page(mapping, newpage, page);
523 
524 	if (rc) {
525 		newpage->mapping = NULL;
526 	} else {
527 		if (remap_swapcache)
528 			remove_migration_ptes(page, newpage);
529 	}
530 
531 	unlock_page(newpage);
532 
533 	return rc;
534 }
535 
536 /*
537  * Obtain the lock on page, remove all ptes and migrate the page
538  * to the newly allocated page in newpage.
539  */
540 static int unmap_and_move(new_page_t get_new_page, unsigned long private,
541 			struct page *page, int force, int offlining)
542 {
543 	int rc = 0;
544 	int *result = NULL;
545 	struct page *newpage = get_new_page(page, private, &result);
546 	int remap_swapcache = 1;
547 	int rcu_locked = 0;
548 	int charge = 0;
549 	struct mem_cgroup *mem = NULL;
550 	struct anon_vma *anon_vma = NULL;
551 
552 	if (!newpage)
553 		return -ENOMEM;
554 
555 	if (page_count(page) == 1) {
556 		/* page was freed from under us. So we are done. */
557 		goto move_newpage;
558 	}
559 
560 	/* prepare cgroup just returns 0 or -ENOMEM */
561 	rc = -EAGAIN;
562 
563 	if (!trylock_page(page)) {
564 		if (!force)
565 			goto move_newpage;
566 		lock_page(page);
567 	}
568 
569 	/*
570 	 * Only memory hotplug's offline_pages() caller has locked out KSM,
571 	 * and can safely migrate a KSM page.  The other cases have skipped
572 	 * PageKsm along with PageReserved - but it is only now when we have
573 	 * the page lock that we can be certain it will not go KSM beneath us
574 	 * (KSM will not upgrade a page from PageAnon to PageKsm when it sees
575 	 * its pagecount raised, but only here do we take the page lock which
576 	 * serializes that).
577 	 */
578 	if (PageKsm(page) && !offlining) {
579 		rc = -EBUSY;
580 		goto unlock;
581 	}
582 
583 	/* charge against new page */
584 	charge = mem_cgroup_prepare_migration(page, &mem);
585 	if (charge == -ENOMEM) {
586 		rc = -ENOMEM;
587 		goto unlock;
588 	}
589 	BUG_ON(charge);
590 
591 	if (PageWriteback(page)) {
592 		if (!force)
593 			goto uncharge;
594 		wait_on_page_writeback(page);
595 	}
596 	/*
597 	 * By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
598 	 * we cannot notice that anon_vma is freed while we migrates a page.
599 	 * This rcu_read_lock() delays freeing anon_vma pointer until the end
600 	 * of migration. File cache pages are no problem because of page_lock()
601 	 * File Caches may use write_page() or lock_page() in migration, then,
602 	 * just care Anon page here.
603 	 */
604 	if (PageAnon(page)) {
605 		rcu_read_lock();
606 		rcu_locked = 1;
607 
608 		/* Determine how to safely use anon_vma */
609 		if (!page_mapped(page)) {
610 			if (!PageSwapCache(page))
611 				goto rcu_unlock;
612 
613 			/*
614 			 * We cannot be sure that the anon_vma of an unmapped
615 			 * swapcache page is safe to use because we don't
616 			 * know in advance if the VMA that this page belonged
617 			 * to still exists. If the VMA and others sharing the
618 			 * data have been freed, then the anon_vma could
619 			 * already be invalid.
620 			 *
621 			 * To avoid this possibility, swapcache pages get
622 			 * migrated but are not remapped when migration
623 			 * completes
624 			 */
625 			remap_swapcache = 0;
626 		} else {
627 			/*
628 			 * Take a reference count on the anon_vma if the
629 			 * page is mapped so that it is guaranteed to
630 			 * exist when the page is remapped later
631 			 */
632 			anon_vma = page_anon_vma(page);
633 			atomic_inc(&anon_vma->external_refcount);
634 		}
635 	}
636 
637 	/*
638 	 * Corner case handling:
639 	 * 1. When a new swap-cache page is read into, it is added to the LRU
640 	 * and treated as swapcache but it has no rmap yet.
641 	 * Calling try_to_unmap() against a page->mapping==NULL page will
642 	 * trigger a BUG.  So handle it here.
643 	 * 2. An orphaned page (see truncate_complete_page) might have
644 	 * fs-private metadata. The page can be picked up due to memory
645 	 * offlining.  Everywhere else except page reclaim, the page is
646 	 * invisible to the vm, so the page can not be migrated.  So try to
647 	 * free the metadata, so the page can be freed.
648 	 */
649 	if (!page->mapping) {
650 		if (!PageAnon(page) && page_has_private(page)) {
651 			/*
652 			 * Go direct to try_to_free_buffers() here because
653 			 * a) that's what try_to_release_page() would do anyway
654 			 * b) we may be under rcu_read_lock() here, so we can't
655 			 *    use GFP_KERNEL which is what try_to_release_page()
656 			 *    needs to be effective.
657 			 */
658 			try_to_free_buffers(page);
659 			goto rcu_unlock;
660 		}
661 		goto skip_unmap;
662 	}
663 
664 	/* Establish migration ptes or remove ptes */
665 	try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
666 
667 skip_unmap:
668 	if (!page_mapped(page))
669 		rc = move_to_new_page(newpage, page, remap_swapcache);
670 
671 	if (rc && remap_swapcache)
672 		remove_migration_ptes(page, page);
673 rcu_unlock:
674 
675 	/* Drop an anon_vma reference if we took one */
676 	if (anon_vma && atomic_dec_and_lock(&anon_vma->external_refcount, &anon_vma->lock)) {
677 		int empty = list_empty(&anon_vma->head);
678 		spin_unlock(&anon_vma->lock);
679 		if (empty)
680 			anon_vma_free(anon_vma);
681 	}
682 
683 	if (rcu_locked)
684 		rcu_read_unlock();
685 uncharge:
686 	if (!charge)
687 		mem_cgroup_end_migration(mem, page, newpage);
688 unlock:
689 	unlock_page(page);
690 
691 	if (rc != -EAGAIN) {
692  		/*
693  		 * A page that has been migrated has all references
694  		 * removed and will be freed. A page that has not been
695  		 * migrated will have kepts its references and be
696  		 * restored.
697  		 */
698  		list_del(&page->lru);
699 		dec_zone_page_state(page, NR_ISOLATED_ANON +
700 				page_is_file_cache(page));
701 		putback_lru_page(page);
702 	}
703 
704 move_newpage:
705 
706 	/*
707 	 * Move the new page to the LRU. If migration was not successful
708 	 * then this will free the page.
709 	 */
710 	putback_lru_page(newpage);
711 
712 	if (result) {
713 		if (rc)
714 			*result = rc;
715 		else
716 			*result = page_to_nid(newpage);
717 	}
718 	return rc;
719 }
720 
721 /*
722  * migrate_pages
723  *
724  * The function takes one list of pages to migrate and a function
725  * that determines from the page to be migrated and the private data
726  * the target of the move and allocates the page.
727  *
728  * The function returns after 10 attempts or if no pages
729  * are movable anymore because to has become empty
730  * or no retryable pages exist anymore. All pages will be
731  * returned to the LRU or freed.
732  *
733  * Return: Number of pages not migrated or error code.
734  */
735 int migrate_pages(struct list_head *from,
736 		new_page_t get_new_page, unsigned long private, int offlining)
737 {
738 	int retry = 1;
739 	int nr_failed = 0;
740 	int pass = 0;
741 	struct page *page;
742 	struct page *page2;
743 	int swapwrite = current->flags & PF_SWAPWRITE;
744 	int rc;
745 
746 	if (!swapwrite)
747 		current->flags |= PF_SWAPWRITE;
748 
749 	for(pass = 0; pass < 10 && retry; pass++) {
750 		retry = 0;
751 
752 		list_for_each_entry_safe(page, page2, from, lru) {
753 			cond_resched();
754 
755 			rc = unmap_and_move(get_new_page, private,
756 						page, pass > 2, offlining);
757 
758 			switch(rc) {
759 			case -ENOMEM:
760 				goto out;
761 			case -EAGAIN:
762 				retry++;
763 				break;
764 			case 0:
765 				break;
766 			default:
767 				/* Permanent failure */
768 				nr_failed++;
769 				break;
770 			}
771 		}
772 	}
773 	rc = 0;
774 out:
775 	if (!swapwrite)
776 		current->flags &= ~PF_SWAPWRITE;
777 
778 	putback_lru_pages(from);
779 
780 	if (rc)
781 		return rc;
782 
783 	return nr_failed + retry;
784 }
785 
786 #ifdef CONFIG_NUMA
787 /*
788  * Move a list of individual pages
789  */
790 struct page_to_node {
791 	unsigned long addr;
792 	struct page *page;
793 	int node;
794 	int status;
795 };
796 
797 static struct page *new_page_node(struct page *p, unsigned long private,
798 		int **result)
799 {
800 	struct page_to_node *pm = (struct page_to_node *)private;
801 
802 	while (pm->node != MAX_NUMNODES && pm->page != p)
803 		pm++;
804 
805 	if (pm->node == MAX_NUMNODES)
806 		return NULL;
807 
808 	*result = &pm->status;
809 
810 	return alloc_pages_exact_node(pm->node,
811 				GFP_HIGHUSER_MOVABLE | GFP_THISNODE, 0);
812 }
813 
814 /*
815  * Move a set of pages as indicated in the pm array. The addr
816  * field must be set to the virtual address of the page to be moved
817  * and the node number must contain a valid target node.
818  * The pm array ends with node = MAX_NUMNODES.
819  */
820 static int do_move_page_to_node_array(struct mm_struct *mm,
821 				      struct page_to_node *pm,
822 				      int migrate_all)
823 {
824 	int err;
825 	struct page_to_node *pp;
826 	LIST_HEAD(pagelist);
827 
828 	down_read(&mm->mmap_sem);
829 
830 	/*
831 	 * Build a list of pages to migrate
832 	 */
833 	for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
834 		struct vm_area_struct *vma;
835 		struct page *page;
836 
837 		err = -EFAULT;
838 		vma = find_vma(mm, pp->addr);
839 		if (!vma || !vma_migratable(vma))
840 			goto set_status;
841 
842 		page = follow_page(vma, pp->addr, FOLL_GET);
843 
844 		err = PTR_ERR(page);
845 		if (IS_ERR(page))
846 			goto set_status;
847 
848 		err = -ENOENT;
849 		if (!page)
850 			goto set_status;
851 
852 		/* Use PageReserved to check for zero page */
853 		if (PageReserved(page) || PageKsm(page))
854 			goto put_and_set;
855 
856 		pp->page = page;
857 		err = page_to_nid(page);
858 
859 		if (err == pp->node)
860 			/*
861 			 * Node already in the right place
862 			 */
863 			goto put_and_set;
864 
865 		err = -EACCES;
866 		if (page_mapcount(page) > 1 &&
867 				!migrate_all)
868 			goto put_and_set;
869 
870 		err = isolate_lru_page(page);
871 		if (!err) {
872 			list_add_tail(&page->lru, &pagelist);
873 			inc_zone_page_state(page, NR_ISOLATED_ANON +
874 					    page_is_file_cache(page));
875 		}
876 put_and_set:
877 		/*
878 		 * Either remove the duplicate refcount from
879 		 * isolate_lru_page() or drop the page ref if it was
880 		 * not isolated.
881 		 */
882 		put_page(page);
883 set_status:
884 		pp->status = err;
885 	}
886 
887 	err = 0;
888 	if (!list_empty(&pagelist))
889 		err = migrate_pages(&pagelist, new_page_node,
890 				(unsigned long)pm, 0);
891 
892 	up_read(&mm->mmap_sem);
893 	return err;
894 }
895 
896 /*
897  * Migrate an array of page address onto an array of nodes and fill
898  * the corresponding array of status.
899  */
900 static int do_pages_move(struct mm_struct *mm, struct task_struct *task,
901 			 unsigned long nr_pages,
902 			 const void __user * __user *pages,
903 			 const int __user *nodes,
904 			 int __user *status, int flags)
905 {
906 	struct page_to_node *pm;
907 	nodemask_t task_nodes;
908 	unsigned long chunk_nr_pages;
909 	unsigned long chunk_start;
910 	int err;
911 
912 	task_nodes = cpuset_mems_allowed(task);
913 
914 	err = -ENOMEM;
915 	pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
916 	if (!pm)
917 		goto out;
918 
919 	migrate_prep();
920 
921 	/*
922 	 * Store a chunk of page_to_node array in a page,
923 	 * but keep the last one as a marker
924 	 */
925 	chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
926 
927 	for (chunk_start = 0;
928 	     chunk_start < nr_pages;
929 	     chunk_start += chunk_nr_pages) {
930 		int j;
931 
932 		if (chunk_start + chunk_nr_pages > nr_pages)
933 			chunk_nr_pages = nr_pages - chunk_start;
934 
935 		/* fill the chunk pm with addrs and nodes from user-space */
936 		for (j = 0; j < chunk_nr_pages; j++) {
937 			const void __user *p;
938 			int node;
939 
940 			err = -EFAULT;
941 			if (get_user(p, pages + j + chunk_start))
942 				goto out_pm;
943 			pm[j].addr = (unsigned long) p;
944 
945 			if (get_user(node, nodes + j + chunk_start))
946 				goto out_pm;
947 
948 			err = -ENODEV;
949 			if (node < 0 || node >= MAX_NUMNODES)
950 				goto out_pm;
951 
952 			if (!node_state(node, N_HIGH_MEMORY))
953 				goto out_pm;
954 
955 			err = -EACCES;
956 			if (!node_isset(node, task_nodes))
957 				goto out_pm;
958 
959 			pm[j].node = node;
960 		}
961 
962 		/* End marker for this chunk */
963 		pm[chunk_nr_pages].node = MAX_NUMNODES;
964 
965 		/* Migrate this chunk */
966 		err = do_move_page_to_node_array(mm, pm,
967 						 flags & MPOL_MF_MOVE_ALL);
968 		if (err < 0)
969 			goto out_pm;
970 
971 		/* Return status information */
972 		for (j = 0; j < chunk_nr_pages; j++)
973 			if (put_user(pm[j].status, status + j + chunk_start)) {
974 				err = -EFAULT;
975 				goto out_pm;
976 			}
977 	}
978 	err = 0;
979 
980 out_pm:
981 	free_page((unsigned long)pm);
982 out:
983 	return err;
984 }
985 
986 /*
987  * Determine the nodes of an array of pages and store it in an array of status.
988  */
989 static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
990 				const void __user **pages, int *status)
991 {
992 	unsigned long i;
993 
994 	down_read(&mm->mmap_sem);
995 
996 	for (i = 0; i < nr_pages; i++) {
997 		unsigned long addr = (unsigned long)(*pages);
998 		struct vm_area_struct *vma;
999 		struct page *page;
1000 		int err = -EFAULT;
1001 
1002 		vma = find_vma(mm, addr);
1003 		if (!vma)
1004 			goto set_status;
1005 
1006 		page = follow_page(vma, addr, 0);
1007 
1008 		err = PTR_ERR(page);
1009 		if (IS_ERR(page))
1010 			goto set_status;
1011 
1012 		err = -ENOENT;
1013 		/* Use PageReserved to check for zero page */
1014 		if (!page || PageReserved(page) || PageKsm(page))
1015 			goto set_status;
1016 
1017 		err = page_to_nid(page);
1018 set_status:
1019 		*status = err;
1020 
1021 		pages++;
1022 		status++;
1023 	}
1024 
1025 	up_read(&mm->mmap_sem);
1026 }
1027 
1028 /*
1029  * Determine the nodes of a user array of pages and store it in
1030  * a user array of status.
1031  */
1032 static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
1033 			 const void __user * __user *pages,
1034 			 int __user *status)
1035 {
1036 #define DO_PAGES_STAT_CHUNK_NR 16
1037 	const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
1038 	int chunk_status[DO_PAGES_STAT_CHUNK_NR];
1039 
1040 	while (nr_pages) {
1041 		unsigned long chunk_nr;
1042 
1043 		chunk_nr = nr_pages;
1044 		if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
1045 			chunk_nr = DO_PAGES_STAT_CHUNK_NR;
1046 
1047 		if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
1048 			break;
1049 
1050 		do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
1051 
1052 		if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
1053 			break;
1054 
1055 		pages += chunk_nr;
1056 		status += chunk_nr;
1057 		nr_pages -= chunk_nr;
1058 	}
1059 	return nr_pages ? -EFAULT : 0;
1060 }
1061 
1062 /*
1063  * Move a list of pages in the address space of the currently executing
1064  * process.
1065  */
1066 SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
1067 		const void __user * __user *, pages,
1068 		const int __user *, nodes,
1069 		int __user *, status, int, flags)
1070 {
1071 	const struct cred *cred = current_cred(), *tcred;
1072 	struct task_struct *task;
1073 	struct mm_struct *mm;
1074 	int err;
1075 
1076 	/* Check flags */
1077 	if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
1078 		return -EINVAL;
1079 
1080 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1081 		return -EPERM;
1082 
1083 	/* Find the mm_struct */
1084 	read_lock(&tasklist_lock);
1085 	task = pid ? find_task_by_vpid(pid) : current;
1086 	if (!task) {
1087 		read_unlock(&tasklist_lock);
1088 		return -ESRCH;
1089 	}
1090 	mm = get_task_mm(task);
1091 	read_unlock(&tasklist_lock);
1092 
1093 	if (!mm)
1094 		return -EINVAL;
1095 
1096 	/*
1097 	 * Check if this process has the right to modify the specified
1098 	 * process. The right exists if the process has administrative
1099 	 * capabilities, superuser privileges or the same
1100 	 * userid as the target process.
1101 	 */
1102 	rcu_read_lock();
1103 	tcred = __task_cred(task);
1104 	if (cred->euid != tcred->suid && cred->euid != tcred->uid &&
1105 	    cred->uid  != tcred->suid && cred->uid  != tcred->uid &&
1106 	    !capable(CAP_SYS_NICE)) {
1107 		rcu_read_unlock();
1108 		err = -EPERM;
1109 		goto out;
1110 	}
1111 	rcu_read_unlock();
1112 
1113  	err = security_task_movememory(task);
1114  	if (err)
1115 		goto out;
1116 
1117 	if (nodes) {
1118 		err = do_pages_move(mm, task, nr_pages, pages, nodes, status,
1119 				    flags);
1120 	} else {
1121 		err = do_pages_stat(mm, nr_pages, pages, status);
1122 	}
1123 
1124 out:
1125 	mmput(mm);
1126 	return err;
1127 }
1128 
1129 /*
1130  * Call migration functions in the vma_ops that may prepare
1131  * memory in a vm for migration. migration functions may perform
1132  * the migration for vmas that do not have an underlying page struct.
1133  */
1134 int migrate_vmas(struct mm_struct *mm, const nodemask_t *to,
1135 	const nodemask_t *from, unsigned long flags)
1136 {
1137  	struct vm_area_struct *vma;
1138  	int err = 0;
1139 
1140 	for (vma = mm->mmap; vma && !err; vma = vma->vm_next) {
1141  		if (vma->vm_ops && vma->vm_ops->migrate) {
1142  			err = vma->vm_ops->migrate(vma, to, from, flags);
1143  			if (err)
1144  				break;
1145  		}
1146  	}
1147  	return err;
1148 }
1149 #endif
1150