mempolicy.c 69.4 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3 4
/*
 * Simple NUMA memory policy for the Linux kernel.
 *
 * Copyright 2003,2004 Andi Kleen, SuSE Labs.
5
 * (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
Linus Torvalds's avatar
Linus Torvalds committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * Subject to the GNU Public License, version 2.
 *
 * NUMA policy allows the user to give hints in which node(s) memory should
 * be allocated.
 *
 * Support four policies per VMA and per process:
 *
 * The VMA policy has priority over the process policy for a page fault.
 *
 * interleave     Allocate memory interleaved over a set of nodes,
 *                with normal fallback if it fails.
 *                For VMA based allocations this interleaves based on the
 *                offset into the backing object or offset into the mapping
 *                for anonymous memory. For process policy an process counter
 *                is used.
21
 *
Linus Torvalds's avatar
Linus Torvalds committed
22 23
 * bind           Only allocate memory on a specific set of nodes,
 *                no fallback.
24 25 26 27
 *                FIXME: memory is allocated starting with the first node
 *                to the last. It would be better if bind would truly restrict
 *                the allocation to memory nodes instead
 *
Linus Torvalds's avatar
Linus Torvalds committed
28
 * preferred       Try a specific node first before normal fallback.
David Rientjes's avatar
David Rientjes committed
29
 *                As a special case NUMA_NO_NODE here means do the allocation
Linus Torvalds's avatar
Linus Torvalds committed
30 31 32
 *                on the local CPU. This is normally identical to default,
 *                but useful to set in a VMA when you have a non default
 *                process policy.
33
 *
Linus Torvalds's avatar
Linus Torvalds committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
 * default        Allocate on the local node first, or when on a VMA
 *                use the process policy. This is what Linux always did
 *		  in a NUMA aware kernel and still does by, ahem, default.
 *
 * The process policy is applied for most non interrupt memory allocations
 * in that process' context. Interrupts ignore the policies and always
 * try to allocate on the local CPU. The VMA policy is only applied for memory
 * allocations for a VMA in the VM.
 *
 * Currently there are a few corner cases in swapping where the policy
 * is not applied, but the majority should be handled. When process policy
 * is used it is not remembered over swap outs/swap ins.
 *
 * Only the highest zone in the zone hierarchy gets policied. Allocations
 * requesting a lower zone just use default policy. This implies that
 * on systems with highmem kernel lowmem allocation don't get policied.
 * Same with GFP_DMA allocations.
 *
 * For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
 * all users and remembered even when nobody has memory mapped.
 */

/* Notebook:
   fix mmap readahead to honour policy and enable policy for any page cache
   object
   statistics for bigpages
   global policy for page cache? currently it uses process policy. Requires
   first item above.
   handle mremap for shared memory (currently ignored for the policy)
   grows down?
   make bind policy root only? It can trigger oom much faster and the
   kernel is not always grateful with that.
*/

68 69
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

Linus Torvalds's avatar
Linus Torvalds committed
70 71 72 73 74 75
#include <linux/mempolicy.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/kernel.h>
#include <linux/sched.h>
76
#include <linux/sched/mm.h>
77
#include <linux/sched/numa_balancing.h>
78
#include <linux/sched/task.h>
Linus Torvalds's avatar
Linus Torvalds committed
79 80 81 82
#include <linux/nodemask.h>
#include <linux/cpuset.h>
#include <linux/slab.h>
#include <linux/string.h>
83
#include <linux/export.h>
84
#include <linux/nsproxy.h>
Linus Torvalds's avatar
Linus Torvalds committed
85 86 87
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/compat.h>
88
#include <linux/ptrace.h>
89
#include <linux/swap.h>
90 91
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
92
#include <linux/migrate.h>
93
#include <linux/ksm.h>
94
#include <linux/rmap.h>
95
#include <linux/security.h>
Adrian Bunk's avatar
Adrian Bunk committed
96
#include <linux/syscalls.h>
97
#include <linux/ctype.h>
98
#include <linux/mm_inline.h>
99
#include <linux/mmu_notifier.h>
100
#include <linux/printk.h>
101
#include <linux/swapops.h>
102

Linus Torvalds's avatar
Linus Torvalds committed
103
#include <asm/tlbflush.h>
104
#include <linux/uaccess.h>
Linus Torvalds's avatar
Linus Torvalds committed
105

106 107
#include "internal.h"

108
/* Internal flags */
109
#define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0)	/* Skip checks for continuous vmas */
110
#define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1)		/* Invert check for nodemask */
111

112 113
static struct kmem_cache *policy_cache;
static struct kmem_cache *sn_cache;
Linus Torvalds's avatar
Linus Torvalds committed
114 115 116

/* Highest zone. An specific allocation for a zone below that is not
   policied. */
117
enum zone_type policy_zone = 0;
Linus Torvalds's avatar
Linus Torvalds committed
118

119 120 121
/*
 * run-time system-wide default policy => local allocation
 */
122
static struct mempolicy default_policy = {
Linus Torvalds's avatar
Linus Torvalds committed
123
	.refcnt = ATOMIC_INIT(1), /* never free it */
124
	.mode = MPOL_PREFERRED,
125
	.flags = MPOL_F_LOCAL,
Linus Torvalds's avatar
Linus Torvalds committed
126 127
};

128 129
static struct mempolicy preferred_node_policy[MAX_NUMNODES];

130
struct mempolicy *get_task_policy(struct task_struct *p)
131 132
{
	struct mempolicy *pol = p->mempolicy;
133
	int node;
134

135 136
	if (pol)
		return pol;
137

138 139 140 141 142 143
	node = numa_node_id();
	if (node != NUMA_NO_NODE) {
		pol = &preferred_node_policy[node];
		/* preferred_node_policy is not initialised early in boot */
		if (pol->mode)
			return pol;
144 145
	}

146
	return &default_policy;
147 148
}

149 150
static const struct mempolicy_operations {
	int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
151
	void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
152 153
} mpol_ops[MPOL_MAX];

154 155
static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
{
Bob Liu's avatar
Bob Liu committed
156
	return pol->flags & MPOL_MODE_FLAGS;
157 158 159 160 161 162 163 164
}

static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
				   const nodemask_t *rel)
{
	nodemask_t tmp;
	nodes_fold(tmp, *orig, nodes_weight(*rel));
	nodes_onto(*ret, tmp, *rel);
165 166
}

167 168 169 170 171 172 173 174 175 176 177
static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes)
{
	if (nodes_empty(*nodes))
		return -EINVAL;
	pol->v.nodes = *nodes;
	return 0;
}

static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
{
	if (!nodes)
178
		pol->flags |= MPOL_F_LOCAL;	/* local allocation */
179 180 181 182 183 184 185 186 187
	else if (nodes_empty(*nodes))
		return -EINVAL;			/*  no allowed nodes */
	else
		pol->v.preferred_node = first_node(*nodes);
	return 0;
}

static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes)
{
188
	if (nodes_empty(*nodes))
189 190 191 192 193
		return -EINVAL;
	pol->v.nodes = *nodes;
	return 0;
}

194 195 196 197 198 199 200 201 202
/*
 * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
 * any, for the new policy.  mpol_new() has already validated the nodes
 * parameter with respect to the policy mode and flags.  But, we need to
 * handle an empty nodemask with MPOL_PREFERRED here.
 *
 * Must be called holding task's alloc_lock to protect task's mems_allowed
 * and mempolicy.  May also be called holding the mmap_semaphore for write.
 */
203 204
static int mpol_set_nodemask(struct mempolicy *pol,
		     const nodemask_t *nodes, struct nodemask_scratch *nsc)
205 206 207 208 209 210
{
	int ret;

	/* if mode is MPOL_DEFAULT, pol is NULL. This is right. */
	if (pol == NULL)
		return 0;
211
	/* Check N_MEMORY */
212
	nodes_and(nsc->mask1,
213
		  cpuset_current_mems_allowed, node_states[N_MEMORY]);
214 215 216 217 218 219

	VM_BUG_ON(!nodes);
	if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes))
		nodes = NULL;	/* explicit local allocation */
	else {
		if (pol->flags & MPOL_F_RELATIVE_NODES)
220
			mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
221
		else
222 223
			nodes_and(nsc->mask2, *nodes, nsc->mask1);

224 225 226 227 228 229 230
		if (mpol_store_user_nodemask(pol))
			pol->w.user_nodemask = *nodes;
		else
			pol->w.cpuset_mems_allowed =
						cpuset_current_mems_allowed;
	}

231 232 233 234
	if (nodes)
		ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
	else
		ret = mpol_ops[pol->mode].create(pol, NULL);
235 236 237 238 239 240 241
	return ret;
}

/*
 * This function just creates a new policy, does some check and simple
 * initialization. You must invoke mpol_set_nodemask() to set nodes.
 */
242 243
static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
				  nodemask_t *nodes)
Linus Torvalds's avatar
Linus Torvalds committed
244 245 246
{
	struct mempolicy *policy;

247
	pr_debug("setting mode %d flags %d nodes[0] %lx\n",
David Rientjes's avatar
David Rientjes committed
248
		 mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
249

250 251
	if (mode == MPOL_DEFAULT) {
		if (nodes && !nodes_empty(*nodes))
252
			return ERR_PTR(-EINVAL);
253
		return NULL;
254
	}
255 256 257 258 259 260 261 262 263 264 265 266 267
	VM_BUG_ON(!nodes);

	/*
	 * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
	 * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
	 * All other modes require a valid pointer to a non-empty nodemask.
	 */
	if (mode == MPOL_PREFERRED) {
		if (nodes_empty(*nodes)) {
			if (((flags & MPOL_F_STATIC_NODES) ||
			     (flags & MPOL_F_RELATIVE_NODES)))
				return ERR_PTR(-EINVAL);
		}
268
	} else if (mode == MPOL_LOCAL) {
269 270 271
		if (!nodes_empty(*nodes) ||
		    (flags & MPOL_F_STATIC_NODES) ||
		    (flags & MPOL_F_RELATIVE_NODES))
272 273
			return ERR_PTR(-EINVAL);
		mode = MPOL_PREFERRED;
274 275
	} else if (nodes_empty(*nodes))
		return ERR_PTR(-EINVAL);
Linus Torvalds's avatar
Linus Torvalds committed
276 277 278 279
	policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
	if (!policy)
		return ERR_PTR(-ENOMEM);
	atomic_set(&policy->refcnt, 1);
280
	policy->mode = mode;
281
	policy->flags = flags;
282

Linus Torvalds's avatar
Linus Torvalds committed
283
	return policy;
284 285
}

286 287 288 289 290 291 292 293
/* Slow path of a mpol destructor. */
void __mpol_put(struct mempolicy *p)
{
	if (!atomic_dec_and_test(&p->refcnt))
		return;
	kmem_cache_free(policy_cache, p);
}

294
static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
295 296 297
{
}

298
static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
299 300 301 302 303 304 305 306
{
	nodemask_t tmp;

	if (pol->flags & MPOL_F_STATIC_NODES)
		nodes_and(tmp, pol->w.user_nodemask, *nodes);
	else if (pol->flags & MPOL_F_RELATIVE_NODES)
		mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
	else {
307 308 309
		nodes_remap(tmp, pol->v.nodes,pol->w.cpuset_mems_allowed,
								*nodes);
		pol->w.cpuset_mems_allowed = tmp;
310
	}
311

312 313 314
	if (nodes_empty(tmp))
		tmp = *nodes;

315
	pol->v.nodes = tmp;
316 317 318
}

static void mpol_rebind_preferred(struct mempolicy *pol,
319
						const nodemask_t *nodes)
320 321 322 323 324 325
{
	nodemask_t tmp;

	if (pol->flags & MPOL_F_STATIC_NODES) {
		int node = first_node(pol->w.user_nodemask);

326
		if (node_isset(node, *nodes)) {
327
			pol->v.preferred_node = node;
328 329 330
			pol->flags &= ~MPOL_F_LOCAL;
		} else
			pol->flags |= MPOL_F_LOCAL;
331 332 333
	} else if (pol->flags & MPOL_F_RELATIVE_NODES) {
		mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
		pol->v.preferred_node = first_node(tmp);
334
	} else if (!(pol->flags & MPOL_F_LOCAL)) {
335 336 337 338 339
		pol->v.preferred_node = node_remap(pol->v.preferred_node,
						   pol->w.cpuset_mems_allowed,
						   *nodes);
		pol->w.cpuset_mems_allowed = *nodes;
	}
Linus Torvalds's avatar
Linus Torvalds committed
340 341
}

342 343 344
/*
 * mpol_rebind_policy - Migrate a policy to a different set of nodes
 *
345 346 347
 * Per-vma policies are protected by mmap_sem. Allocations using per-task
 * policies are protected by task->mems_allowed_seq to prevent a premature
 * OOM/allocation failure due to parallel nodemask modification.
348
 */
349
static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
350 351 352
{
	if (!pol)
		return;
353
	if (!mpol_store_user_nodemask(pol) &&
354 355
	    nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
		return;
356

357
	mpol_ops[pol->mode].rebind(pol, newmask);
358 359 360 361 362
}

/*
 * Wrapper for mpol_rebind_policy() that just requires task
 * pointer, and updates task mempolicy.
363 364
 *
 * Called with task's alloc_lock held.
365 366
 */

367
void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
368
{
369
	mpol_rebind_policy(tsk->mempolicy, new);
370 371 372 373 374 375 376 377 378 379 380 381 382 383
}

/*
 * Rebind each vma in mm to new nodemask.
 *
 * Call holding a reference to mm.  Takes mm->mmap_sem during call.
 */

void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
{
	struct vm_area_struct *vma;

	down_write(&mm->mmap_sem);
	for (vma = mm->mmap; vma; vma = vma->vm_next)
384
		mpol_rebind_policy(vma->vm_policy, new);
385 386 387
	up_write(&mm->mmap_sem);
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
	[MPOL_DEFAULT] = {
		.rebind = mpol_rebind_default,
	},
	[MPOL_INTERLEAVE] = {
		.create = mpol_new_interleave,
		.rebind = mpol_rebind_nodemask,
	},
	[MPOL_PREFERRED] = {
		.create = mpol_new_preferred,
		.rebind = mpol_rebind_preferred,
	},
	[MPOL_BIND] = {
		.create = mpol_new_bind,
		.rebind = mpol_rebind_nodemask,
	},
};

406 407
static void migrate_page_add(struct page *page, struct list_head *pagelist,
				unsigned long flags);
408

409 410 411 412 413 414 415
struct queue_pages {
	struct list_head *pagelist;
	unsigned long flags;
	nodemask_t *nmask;
	struct vm_area_struct *prev;
};

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
/*
 * Check if the page's nid is in qp->nmask.
 *
 * If MPOL_MF_INVERT is set in qp->flags, check if the nid is
 * in the invert of qp->nmask.
 */
static inline bool queue_pages_required(struct page *page,
					struct queue_pages *qp)
{
	int nid = page_to_nid(page);
	unsigned long flags = qp->flags;

	return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
}

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
static int queue_pages_pmd(pmd_t *pmd, spinlock_t *ptl, unsigned long addr,
				unsigned long end, struct mm_walk *walk)
{
	int ret = 0;
	struct page *page;
	struct queue_pages *qp = walk->private;
	unsigned long flags;

	if (unlikely(is_pmd_migration_entry(*pmd))) {
		ret = 1;
		goto unlock;
	}
	page = pmd_page(*pmd);
	if (is_huge_zero_page(page)) {
		spin_unlock(ptl);
		__split_huge_pmd(walk->vma, pmd, addr, false, NULL);
		goto out;
	}
	if (!thp_migration_supported()) {
		get_page(page);
		spin_unlock(ptl);
		lock_page(page);
		ret = split_huge_page(page);
		unlock_page(page);
		put_page(page);
		goto out;
	}
	if (!queue_pages_required(page, qp)) {
		ret = 1;
		goto unlock;
	}

	ret = 1;
	flags = qp->flags;
	/* go to thp migration */
	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
		migrate_page_add(page, qp->pagelist, flags);
unlock:
	spin_unlock(ptl);
out:
	return ret;
}

474 475 476 477
/*
 * Scan through pages checking if pages follow certain conditions,
 * and move them to the pagelist if they do.
 */
478 479
static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr,
			unsigned long end, struct mm_walk *walk)
Linus Torvalds's avatar
Linus Torvalds committed
480
{
481 482 483 484
	struct vm_area_struct *vma = walk->vma;
	struct page *page;
	struct queue_pages *qp = walk->private;
	unsigned long flags = qp->flags;
485
	int ret;
486
	pte_t *pte;
487
	spinlock_t *ptl;
488

489 490 491 492 493
	ptl = pmd_trans_huge_lock(pmd, vma);
	if (ptl) {
		ret = queue_pages_pmd(pmd, ptl, addr, end, walk);
		if (ret)
			return 0;
494
	}
495

496 497
	if (pmd_trans_unstable(pmd))
		return 0;
498
retry:
499 500
	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
	for (; addr != end; pte++, addr += PAGE_SIZE) {
501
		if (!pte_present(*pte))
Linus Torvalds's avatar
Linus Torvalds committed
502
			continue;
503 504
		page = vm_normal_page(vma, addr, *pte);
		if (!page)
Linus Torvalds's avatar
Linus Torvalds committed
505
			continue;
506
		/*
507 508
		 * vm_normal_page() filters out zero pages, but there might
		 * still be PageReserved pages to skip, perhaps in a VDSO.
509
		 */
Hugh Dickins's avatar
Hugh Dickins committed
510
		if (PageReserved(page))
511
			continue;
512
		if (!queue_pages_required(page, qp))
513
			continue;
514
		if (PageTransCompound(page) && !thp_migration_supported()) {
515 516 517 518 519 520 521 522 523 524 525 526 527 528
			get_page(page);
			pte_unmap_unlock(pte, ptl);
			lock_page(page);
			ret = split_huge_page(page);
			unlock_page(page);
			put_page(page);
			/* Failed to split -- skip. */
			if (ret) {
				pte = pte_offset_map_lock(walk->mm, pmd,
						addr, &ptl);
				continue;
			}
			goto retry;
		}
529

530
		migrate_page_add(page, qp->pagelist, flags);
531 532 533 534
	}
	pte_unmap_unlock(pte - 1, ptl);
	cond_resched();
	return 0;
535 536
}

537 538 539
static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
			       unsigned long addr, unsigned long end,
			       struct mm_walk *walk)
540 541
{
#ifdef CONFIG_HUGETLB_PAGE
542 543
	struct queue_pages *qp = walk->private;
	unsigned long flags = qp->flags;
544
	struct page *page;
545
	spinlock_t *ptl;
546
	pte_t entry;
547

548 549
	ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
	entry = huge_ptep_get(pte);
550 551 552
	if (!pte_present(entry))
		goto unlock;
	page = pte_page(entry);
553
	if (!queue_pages_required(page, qp))
554 555 556 557
		goto unlock;
	/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
	if (flags & (MPOL_MF_MOVE_ALL) ||
	    (flags & MPOL_MF_MOVE && page_mapcount(page) == 1))
558
		isolate_huge_page(page, qp->pagelist);
559
unlock:
560
	spin_unlock(ptl);
561 562 563
#else
	BUG();
#endif
564
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
565 566
}

567
#ifdef CONFIG_NUMA_BALANCING
568
/*
569 570 571 572 573 574 575
 * This is used to mark a range of virtual addresses to be inaccessible.
 * These are later cleared by a NUMA hinting fault. Depending on these
 * faults, pages may be migrated for better NUMA placement.
 *
 * This is assuming that NUMA faults are handled using PROT_NONE. If
 * an architecture makes a different choice, it will need further
 * changes to the core.
576
 */
577 578
unsigned long change_prot_numa(struct vm_area_struct *vma,
			unsigned long addr, unsigned long end)
579
{
580
	int nr_updated;
581

582
	nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1);
583 584
	if (nr_updated)
		count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
585

586
	return nr_updated;
587 588 589 590 591 592 593
}
#else
static unsigned long change_prot_numa(struct vm_area_struct *vma,
			unsigned long addr, unsigned long end)
{
	return 0;
}
594
#endif /* CONFIG_NUMA_BALANCING */
595

596 597 598 599 600 601 602 603
static int queue_pages_test_walk(unsigned long start, unsigned long end,
				struct mm_walk *walk)
{
	struct vm_area_struct *vma = walk->vma;
	struct queue_pages *qp = walk->private;
	unsigned long endvma = vma->vm_end;
	unsigned long flags = qp->flags;

604
	if (!vma_migratable(vma))
605 606
		return 1;

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
	if (endvma > end)
		endvma = end;
	if (vma->vm_start > start)
		start = vma->vm_start;

	if (!(flags & MPOL_MF_DISCONTIG_OK)) {
		if (!vma->vm_next && vma->vm_end < end)
			return -EFAULT;
		if (qp->prev && qp->prev->vm_end < vma->vm_start)
			return -EFAULT;
	}

	qp->prev = vma;

	if (flags & MPOL_MF_LAZY) {
		/* Similar to task_numa_work, skip inaccessible VMAs */
623 624 625
		if (!is_vm_hugetlb_page(vma) &&
			(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) &&
			!(vma->vm_flags & VM_MIXEDMAP))
626 627 628 629
			change_prot_numa(vma, start, endvma);
		return 1;
	}

630 631
	/* queue pages from current vma */
	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
632 633 634 635
		return 0;
	return 1;
}

636
/*
637 638 639 640 641
 * Walk through page tables and collect pages to be migrated.
 *
 * If pages found in a given range are on a set of nodes (determined by
 * @nodes and @flags,) it's isolated and queued to the pagelist which is
 * passed via @private.)
642
 */
643
static int
644
queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
645 646
		nodemask_t *nodes, unsigned long flags,
		struct list_head *pagelist)
Linus Torvalds's avatar
Linus Torvalds committed
647
{
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
	struct queue_pages qp = {
		.pagelist = pagelist,
		.flags = flags,
		.nmask = nodes,
		.prev = NULL,
	};
	struct mm_walk queue_pages_walk = {
		.hugetlb_entry = queue_pages_hugetlb,
		.pmd_entry = queue_pages_pte_range,
		.test_walk = queue_pages_test_walk,
		.mm = mm,
		.private = &qp,
	};

	return walk_page_range(start, end, &queue_pages_walk);
Linus Torvalds's avatar
Linus Torvalds committed
663 664
}

665 666 667 668 669 670
/*
 * Apply policy to a single VMA
 * This must be called with the mmap_sem held for writing.
 */
static int vma_replace_policy(struct vm_area_struct *vma,
						struct mempolicy *pol)
671
{
672 673 674
	int err;
	struct mempolicy *old;
	struct mempolicy *new;
675 676 677 678 679 680

	pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
		 vma->vm_start, vma->vm_end, vma->vm_pgoff,
		 vma->vm_ops, vma->vm_file,
		 vma->vm_ops ? vma->vm_ops->set_policy : NULL);

681 682 683 684 685
	new = mpol_dup(pol);
	if (IS_ERR(new))
		return PTR_ERR(new);

	if (vma->vm_ops && vma->vm_ops->set_policy) {
686
		err = vma->vm_ops->set_policy(vma, new);
687 688
		if (err)
			goto err_out;
689
	}
690 691 692 693 694 695 696 697

	old = vma->vm_policy;
	vma->vm_policy = new; /* protected by mmap_sem */
	mpol_put(old);

	return 0;
 err_out:
	mpol_put(new);
698 699 700
	return err;
}

Linus Torvalds's avatar
Linus Torvalds committed
701
/* Step 2: apply policy to a range and do splits. */
702 703
static int mbind_range(struct mm_struct *mm, unsigned long start,
		       unsigned long end, struct mempolicy *new_pol)
Linus Torvalds's avatar
Linus Torvalds committed
704 705
{
	struct vm_area_struct *next;
706 707 708
	struct vm_area_struct *prev;
	struct vm_area_struct *vma;
	int err = 0;
709
	pgoff_t pgoff;
710 711
	unsigned long vmstart;
	unsigned long vmend;
Linus Torvalds's avatar
Linus Torvalds committed
712

713
	vma = find_vma(mm, start);
714 715 716
	if (!vma || vma->vm_start > start)
		return -EFAULT;

717
	prev = vma->vm_prev;
718 719 720
	if (start > vma->vm_start)
		prev = vma;

721
	for (; vma && vma->vm_start < end; prev = vma, vma = next) {
Linus Torvalds's avatar
Linus Torvalds committed
722
		next = vma->vm_next;
723 724 725
		vmstart = max(start, vma->vm_start);
		vmend   = min(end, vma->vm_end);

726 727 728 729 730
		if (mpol_equal(vma_policy(vma), new_pol))
			continue;

		pgoff = vma->vm_pgoff +
			((vmstart - vma->vm_start) >> PAGE_SHIFT);
731
		prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags,
732 733
				 vma->anon_vma, vma->vm_file, pgoff,
				 new_pol, vma->vm_userfaultfd_ctx);
734 735 736
		if (prev) {
			vma = prev;
			next = vma->vm_next;
737 738 739 740
			if (mpol_equal(vma_policy(vma), new_pol))
				continue;
			/* vma_merge() joined vma && vma->next, case 8 */
			goto replace;
741 742 743 744 745 746 747 748 749 750 751
		}
		if (vma->vm_start != vmstart) {
			err = split_vma(vma->vm_mm, vma, vmstart, 1);
			if (err)
				goto out;
		}
		if (vma->vm_end != vmend) {
			err = split_vma(vma->vm_mm, vma, vmend, 0);
			if (err)
				goto out;
		}
752
 replace:
753
		err = vma_replace_policy(vma, new_pol);
754 755
		if (err)
			goto out;
Linus Torvalds's avatar
Linus Torvalds committed
756
	}
757 758

 out:
Linus Torvalds's avatar
Linus Torvalds committed
759 760 761 762
	return err;
}

/* Set the process memory policy */
763 764
static long do_set_mempolicy(unsigned short mode, unsigned short flags,
			     nodemask_t *nodes)
Linus Torvalds's avatar
Linus Torvalds committed
765
{
766
	struct mempolicy *new, *old;
767
	NODEMASK_SCRATCH(scratch);
768
	int ret;
Linus Torvalds's avatar
Linus Torvalds committed
769

770 771
	if (!scratch)
		return -ENOMEM;
772

773 774 775 776 777
	new = mpol_new(mode, flags, nodes);
	if (IS_ERR(new)) {
		ret = PTR_ERR(new);
		goto out;
	}
778

779
	task_lock(current);
780
	ret = mpol_set_nodemask(new, nodes, scratch);
781 782 783
	if (ret) {
		task_unlock(current);
		mpol_put(new);
784
		goto out;
785 786
	}
	old = current->mempolicy;
Linus Torvalds's avatar
Linus Torvalds committed
787
	current->mempolicy = new;
788 789
	if (new && new->mode == MPOL_INTERLEAVE)
		current->il_prev = MAX_NUMNODES-1;
790 791
	task_unlock(current);
	mpol_put(old);
792 793 794 795
	ret = 0;
out:
	NODEMASK_SCRATCH_FREE(scratch);
	return ret;
Linus Torvalds's avatar
Linus Torvalds committed
796 797
}

798 799
/*
 * Return nodemask for policy for get_mempolicy() query
800 801
 *
 * Called with task's alloc_lock held
802 803
 */
static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
Linus Torvalds's avatar
Linus Torvalds committed
804
{
805
	nodes_clear(*nodes);
806 807 808
	if (p == &default_policy)
		return;

809
	switch (p->mode) {
810 811
	case MPOL_BIND:
		/* Fall through */
Linus Torvalds's avatar
Linus Torvalds committed
812
	case MPOL_INTERLEAVE:
813
		*nodes = p->v.nodes;
Linus Torvalds's avatar
Linus Torvalds committed
814 815
		break;
	case MPOL_PREFERRED:
816
		if (!(p->flags & MPOL_F_LOCAL))
817
			node_set(p->v.preferred_node, *nodes);
818
		/* else return empty node mask for local allocation */
Linus Torvalds's avatar
Linus Torvalds committed
819 820 821 822 823 824
		break;
	default:
		BUG();
	}
}

825
static int lookup_node(unsigned long addr)
Linus Torvalds's avatar
Linus Torvalds committed
826 827 828 829
{
	struct page *p;
	int err;

830
	err = get_user_pages(addr & PAGE_MASK, 1, 0, &p, NULL);
Linus Torvalds's avatar
Linus Torvalds committed
831 832 833 834 835 836 837 838
	if (err >= 0) {
		err = page_to_nid(p);
		put_page(p);
	}
	return err;
}

/* Retrieve NUMA policy */
Adrian Bunk's avatar
Adrian Bunk committed
839 840
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
			     unsigned long addr, unsigned long flags)
Linus Torvalds's avatar
Linus Torvalds committed
841
{
842
	int err;
Linus Torvalds's avatar
Linus Torvalds committed
843 844 845 846
	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma = NULL;
	struct mempolicy *pol = current->mempolicy;

847 848
	if (flags &
		~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
Linus Torvalds's avatar
Linus Torvalds committed
849
		return -EINVAL;
850 851 852 853 854

	if (flags & MPOL_F_MEMS_ALLOWED) {
		if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
			return -EINVAL;
		*policy = 0;	/* just so it's initialized */
855
		task_lock(current);
856
		*nmask  = cpuset_current_mems_allowed;
857
		task_unlock(current);
858 859 860
		return 0;
	}

Linus Torvalds's avatar
Linus Torvalds committed
861
	if (flags & MPOL_F_ADDR) {
862 863 864 865 866
		/*
		 * Do NOT fall back to task policy if the
		 * vma/shared policy at addr is NULL.  We
		 * want to return MPOL_DEFAULT in this case.
		 */
Linus Torvalds's avatar
Linus Torvalds committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880
		down_read(&mm->mmap_sem);
		vma = find_vma_intersection(mm, addr, addr+1);
		if (!vma) {
			up_read(&mm->mmap_sem);
			return -EFAULT;
		}
		if (vma->vm_ops && vma->vm_ops->get_policy)
			pol = vma->vm_ops->get_policy(vma, addr);
		else
			pol = vma->vm_policy;
	} else if (addr)
		return -EINVAL;

	if (!pol)
881
		pol = &default_policy;	/* indicates default behavior */
Linus Torvalds's avatar
Linus Torvalds committed
882 883 884

	if (flags & MPOL_F_NODE) {
		if (flags & MPOL_F_ADDR) {
885
			err = lookup_node(addr);
Linus Torvalds's avatar
Linus Torvalds committed
886 887
			if (err < 0)
				goto out;
888
			*policy = err;
Linus Torvalds's avatar
Linus Torvalds committed
889
		} else if (pol == current->mempolicy &&
890
				pol->mode == MPOL_INTERLEAVE) {
891
			*policy = next_node_in(current->il_prev, pol->v.nodes);
Linus Torvalds's avatar
Linus Torvalds committed
892 893 894 895
		} else {
			err = -EINVAL;
			goto out;
		}
896 897 898
	} else {
		*policy = pol == &default_policy ? MPOL_DEFAULT :
						pol->mode;
899 900 901 902 903
		/*
		 * Internal mempolicy flags must be masked off before exposing
		 * the policy to userspace.
		 */
		*policy |= (pol->flags & MPOL_MODE_FLAGS);
904
	}
Linus Torvalds's avatar
Linus Torvalds committed
905 906

	err = 0;
907
	if (nmask) {
908 909 910 911 912 913 914
		if (mpol_store_user_nodemask(pol)) {
			*nmask = pol->w.user_nodemask;
		} else {
			task_lock(current);
			get_policy_nodemask(pol, nmask);
			task_unlock(current);
		}
915
	}
Linus Torvalds's avatar
Linus Torvalds committed
916 917

 out:
918
	mpol_cond_put(pol);
Linus Torvalds's avatar
Linus Torvalds committed
919 920 921 922 923
	if (vma)
		up_read(&current->mm->mmap_sem);
	return err;
}

924
#ifdef CONFIG_MIGRATION
925
/*
926
 * page migration, thp tail pages can be passed.
927
 */
928 929
static void migrate_page_add(struct page *page, struct list_head *pagelist,
				unsigned long flags)
930
{
931
	struct page *head = compound_head(page);
932
	/*
933
	 * Avoid migrating a page that is shared with others.
934
	 */
935 936 937 938 939 940
	if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(head) == 1) {
		if (!isolate_lru_page(head)) {
			list_add_tail(&head->lru, pagelist);
			mod_node_page_state(page_pgdat(head),
				NR_ISOLATED_ANON + page_is_file_cache(head),
				hpage_nr_pages(head));
941 942
		}
	}
943
}
944

945
static struct page *new_node_page(struct page *page, unsigned long node, int **x)
946
{
947 948 949
	if (PageHuge(page))
		return alloc_huge_page_node(page_hstate(compound_head(page)),
					node);
950 951 952 953 954 955 956 957 958 959 960
	else if (thp_migration_supported() && PageTransHuge(page)) {
		struct page *thp;

		thp = alloc_pages_node(node,
			(GFP_TRANSHUGE | __GFP_THISNODE),
			HPAGE_PMD_ORDER);
		if (!thp)
			return NULL;
		prep_transhuge_page(thp);
		return thp;
	} else
961
		return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE |
962
						    __GFP_THISNODE, 0);
963 964
}

965 966 967 968
/*
 * Migrate pages from one node to a target node.
 * Returns error or the number of pages not migrated.
 */
Adrian Bunk's avatar
Adrian Bunk committed
969 970
static int migrate_to_node(struct mm_struct *mm, int source, int dest,
			   int flags)
971 972 973 974 975 976 977
{
	nodemask_t nmask;
	LIST_HEAD(pagelist);
	int err = 0;

	nodes_clear(nmask);
	node_set(source, nmask);
978

979 980 981 982 983 984
	/*
	 * This does not "check" the range but isolates all pages that
	 * need migration.  Between passing in the full user address
	 * space range and MPOL_MF_DISCONTIG_OK, this call can not fail.
	 */
	VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
985
	queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask,
986 987
			flags | MPOL_MF_DISCONTIG_OK, &pagelist);

988
	if (!list_empty(&pagelist)) {
989
		err = migrate_pages(&pagelist, new_node_page, NULL, dest,
990
					MIGRATE_SYNC, MR_SYSCALL);
991
		if (err)
992
			putback_movable_pages(&pagelist);
993
	}
994

995
	return err;
996 997
}

998
/*
999 1000
 * Move pages between the two nodesets so as to preserve the physical
 * layout as much as possible.
1001 1002 1003
 *
 * Returns the number of page that could not be moved.
 */
1004 1005
int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
		     const nodemask_t *to, int flags)
1006
{
1007
	int busy = 0;
1008
	int err;
1009
	nodemask_t tmp;
1010

1011 1012 1013 1014
	err = migrate_prep();
	if (err)
		return err;

1015
	down_read(&mm->mmap_sem);
1016

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	/*
	 * Find a 'source' bit set in 'tmp' whose corresponding 'dest'
	 * bit in 'to' is not also set in 'tmp'.  Clear the found 'source'
	 * bit in 'tmp', and return that <source, dest> pair for migration.
	 * The pair of nodemasks 'to' and 'from' define the map.
	 *
	 * If no pair of bits is found that way, fallback to picking some
	 * pair of 'source' and 'dest' bits that are not the same.  If the
	 * 'source' and 'dest' bits are the same, this represents a node
	 * that will be migrating to itself, so no pages need move.
	 *
	 * If no bits are left in 'tmp', or if all remaining bits left
	 * in 'tmp' correspond to the same bit in 'to', return false
	 * (nothing left to migrate).
	 *
	 * This lets us pick a pair of nodes to migrate between, such that
	 * if possible the dest node is not already occupied by some other
	 * source node, minimizing the risk of overloading the memory on a
	 * node that would happen if we migrated incoming memory to a node
	 * before migrating outgoing memory source that same node.
	 *
	 * A single scan of tmp is sufficient.  As we go, we remember the
	 * most recent <s, d> pair that moved (s != d).  If we find a pair
	 * that not only moved, but what's better, moved to an empty slot
	 * (d is not set in tmp), then we break out then, with that pair.
1042
	 * Otherwise when we finish scanning from_tmp, we at least have the
1043 1044 1045 1046
	 * most recent <s, d> pair that moved.  If we get all the way through
	 * the scan of tmp without finding any node that moved, much less
	 * moved to an empty node, then there is nothing left worth migrating.
	 */
1047

1048
	tmp = *from;
1049 1050
	while (!nodes_empty(tmp)) {
		int s,d;
Jianguo Wu's avatar
Jianguo Wu committed
1051
		int source = NUMA_NO_NODE;
1052 1053 1054
		int dest = 0;

		for_each_node_mask(s, tmp) {
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

			/*
			 * do_migrate_pages() tries to maintain the relative
			 * node relationship of the pages established between
			 * threads and memory areas.
                         *
			 * However if the number of source nodes is not equal to
			 * the number of destination nodes we can not preserve
			 * this node relative relationship.  In that case, skip
			 * copying memory from a node that is in the destination
			 * mask.
			 *
			 * Example: [2,3,4] -> [3,4,5] moves everything.
			 *          [0-7] - > [3,4,5] moves only 0,1,2,6,7.
			 */

1071 1072
			if ((nodes_weight(*from) != nodes_weight(*to)) &&
						(node_isset(s, *to)))
1073 1074
				continue;

1075
			d = node_remap(s, *from, *to);
1076 1077 1078 1079