xref: /openbmc/linux/mm/mempolicy.c (revision cc424890b06ba1d41d7ec99984b65592184adf0b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Simple NUMA memory policy for the Linux kernel.
4  *
5  * Copyright 2003,2004 Andi Kleen, SuSE Labs.
6  * (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
7  *
8  * NUMA policy allows the user to give hints in which node(s) memory should
9  * be allocated.
10  *
11  * Support four policies per VMA and per process:
12  *
13  * The VMA policy has priority over the process policy for a page fault.
14  *
15  * interleave     Allocate memory interleaved over a set of nodes,
16  *                with normal fallback if it fails.
17  *                For VMA based allocations this interleaves based on the
18  *                offset into the backing object or offset into the mapping
19  *                for anonymous memory. For process policy an process counter
20  *                is used.
21  *
22  * bind           Only allocate memory on a specific set of nodes,
23  *                no fallback.
24  *                FIXME: memory is allocated starting with the first node
25  *                to the last. It would be better if bind would truly restrict
26  *                the allocation to memory nodes instead
27  *
28  * preferred       Try a specific node first before normal fallback.
29  *                As a special case NUMA_NO_NODE here means do the allocation
30  *                on the local CPU. This is normally identical to default,
31  *                but useful to set in a VMA when you have a non default
32  *                process policy.
33  *
34  * preferred many Try a set of nodes first before normal fallback. This is
35  *                similar to preferred without the special case.
36  *
37  * default        Allocate on the local node first, or when on a VMA
38  *                use the process policy. This is what Linux always did
39  *		  in a NUMA aware kernel and still does by, ahem, default.
40  *
41  * The process policy is applied for most non interrupt memory allocations
42  * in that process' context. Interrupts ignore the policies and always
43  * try to allocate on the local CPU. The VMA policy is only applied for memory
44  * allocations for a VMA in the VM.
45  *
46  * Currently there are a few corner cases in swapping where the policy
47  * is not applied, but the majority should be handled. When process policy
48  * is used it is not remembered over swap outs/swap ins.
49  *
50  * Only the highest zone in the zone hierarchy gets policied. Allocations
51  * requesting a lower zone just use default policy. This implies that
52  * on systems with highmem kernel lowmem allocation don't get policied.
53  * Same with GFP_DMA allocations.
54  *
55  * For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between
56  * all users and remembered even when nobody has memory mapped.
57  */
58 
59 /* Notebook:
60    fix mmap readahead to honour policy and enable policy for any page cache
61    object
62    statistics for bigpages
63    global policy for page cache? currently it uses process policy. Requires
64    first item above.
65    handle mremap for shared memory (currently ignored for the policy)
66    grows down?
67    make bind policy root only? It can trigger oom much faster and the
68    kernel is not always grateful with that.
69 */
70 
71 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
72 
73 #include <linux/mempolicy.h>
74 #include <linux/pagewalk.h>
75 #include <linux/highmem.h>
76 #include <linux/hugetlb.h>
77 #include <linux/kernel.h>
78 #include <linux/sched.h>
79 #include <linux/sched/mm.h>
80 #include <linux/sched/numa_balancing.h>
81 #include <linux/sched/task.h>
82 #include <linux/nodemask.h>
83 #include <linux/cpuset.h>
84 #include <linux/slab.h>
85 #include <linux/string.h>
86 #include <linux/export.h>
87 #include <linux/nsproxy.h>
88 #include <linux/interrupt.h>
89 #include <linux/init.h>
90 #include <linux/compat.h>
91 #include <linux/ptrace.h>
92 #include <linux/swap.h>
93 #include <linux/seq_file.h>
94 #include <linux/proc_fs.h>
95 #include <linux/migrate.h>
96 #include <linux/ksm.h>
97 #include <linux/rmap.h>
98 #include <linux/security.h>
99 #include <linux/syscalls.h>
100 #include <linux/ctype.h>
101 #include <linux/mm_inline.h>
102 #include <linux/mmu_notifier.h>
103 #include <linux/printk.h>
104 #include <linux/swapops.h>
105 
106 #include <asm/tlbflush.h>
107 #include <asm/tlb.h>
108 #include <linux/uaccess.h>
109 
110 #include "internal.h"
111 
112 /* Internal flags */
113 #define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0)	/* Skip checks for continuous vmas */
114 #define MPOL_MF_INVERT       (MPOL_MF_INTERNAL << 1)	/* Invert check for nodemask */
115 #define MPOL_MF_WRLOCK       (MPOL_MF_INTERNAL << 2)	/* Write-lock walked vmas */
116 
117 static struct kmem_cache *policy_cache;
118 static struct kmem_cache *sn_cache;
119 
120 /* Highest zone. An specific allocation for a zone below that is not
121    policied. */
122 enum zone_type policy_zone = 0;
123 
124 /*
125  * run-time system-wide default policy => local allocation
126  */
127 static struct mempolicy default_policy = {
128 	.refcnt = ATOMIC_INIT(1), /* never free it */
129 	.mode = MPOL_LOCAL,
130 };
131 
132 static struct mempolicy preferred_node_policy[MAX_NUMNODES];
133 
134 /**
135  * numa_nearest_node - Find nearest node by state
136  * @node: Node id to start the search
137  * @state: State to filter the search
138  *
139  * Lookup the closest node by distance if @nid is not in state.
140  *
141  * Return: this @node if it is in state, otherwise the closest node by distance
142  */
143 int numa_nearest_node(int node, unsigned int state)
144 {
145 	int min_dist = INT_MAX, dist, n, min_node;
146 
147 	if (state >= NR_NODE_STATES)
148 		return -EINVAL;
149 
150 	if (node == NUMA_NO_NODE || node_state(node, state))
151 		return node;
152 
153 	min_node = node;
154 	for_each_node_state(n, state) {
155 		dist = node_distance(node, n);
156 		if (dist < min_dist) {
157 			min_dist = dist;
158 			min_node = n;
159 		}
160 	}
161 
162 	return min_node;
163 }
164 EXPORT_SYMBOL_GPL(numa_nearest_node);
165 
166 struct mempolicy *get_task_policy(struct task_struct *p)
167 {
168 	struct mempolicy *pol = p->mempolicy;
169 	int node;
170 
171 	if (pol)
172 		return pol;
173 
174 	node = numa_node_id();
175 	if (node != NUMA_NO_NODE) {
176 		pol = &preferred_node_policy[node];
177 		/* preferred_node_policy is not initialised early in boot */
178 		if (pol->mode)
179 			return pol;
180 	}
181 
182 	return &default_policy;
183 }
184 
185 static const struct mempolicy_operations {
186 	int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
187 	void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
188 } mpol_ops[MPOL_MAX];
189 
190 static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
191 {
192 	return pol->flags & MPOL_MODE_FLAGS;
193 }
194 
195 static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
196 				   const nodemask_t *rel)
197 {
198 	nodemask_t tmp;
199 	nodes_fold(tmp, *orig, nodes_weight(*rel));
200 	nodes_onto(*ret, tmp, *rel);
201 }
202 
203 static int mpol_new_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
204 {
205 	if (nodes_empty(*nodes))
206 		return -EINVAL;
207 	pol->nodes = *nodes;
208 	return 0;
209 }
210 
211 static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
212 {
213 	if (nodes_empty(*nodes))
214 		return -EINVAL;
215 
216 	nodes_clear(pol->nodes);
217 	node_set(first_node(*nodes), pol->nodes);
218 	return 0;
219 }
220 
221 /*
222  * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
223  * any, for the new policy.  mpol_new() has already validated the nodes
224  * parameter with respect to the policy mode and flags.
225  *
226  * Must be called holding task's alloc_lock to protect task's mems_allowed
227  * and mempolicy.  May also be called holding the mmap_lock for write.
228  */
229 static int mpol_set_nodemask(struct mempolicy *pol,
230 		     const nodemask_t *nodes, struct nodemask_scratch *nsc)
231 {
232 	int ret;
233 
234 	/*
235 	 * Default (pol==NULL) resp. local memory policies are not a
236 	 * subject of any remapping. They also do not need any special
237 	 * constructor.
238 	 */
239 	if (!pol || pol->mode == MPOL_LOCAL)
240 		return 0;
241 
242 	/* Check N_MEMORY */
243 	nodes_and(nsc->mask1,
244 		  cpuset_current_mems_allowed, node_states[N_MEMORY]);
245 
246 	VM_BUG_ON(!nodes);
247 
248 	if (pol->flags & MPOL_F_RELATIVE_NODES)
249 		mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
250 	else
251 		nodes_and(nsc->mask2, *nodes, nsc->mask1);
252 
253 	if (mpol_store_user_nodemask(pol))
254 		pol->w.user_nodemask = *nodes;
255 	else
256 		pol->w.cpuset_mems_allowed = cpuset_current_mems_allowed;
257 
258 	ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
259 	return ret;
260 }
261 
262 /*
263  * This function just creates a new policy, does some check and simple
264  * initialization. You must invoke mpol_set_nodemask() to set nodes.
265  */
266 static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
267 				  nodemask_t *nodes)
268 {
269 	struct mempolicy *policy;
270 
271 	pr_debug("setting mode %d flags %d nodes[0] %lx\n",
272 		 mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE);
273 
274 	if (mode == MPOL_DEFAULT) {
275 		if (nodes && !nodes_empty(*nodes))
276 			return ERR_PTR(-EINVAL);
277 		return NULL;
278 	}
279 	VM_BUG_ON(!nodes);
280 
281 	/*
282 	 * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
283 	 * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
284 	 * All other modes require a valid pointer to a non-empty nodemask.
285 	 */
286 	if (mode == MPOL_PREFERRED) {
287 		if (nodes_empty(*nodes)) {
288 			if (((flags & MPOL_F_STATIC_NODES) ||
289 			     (flags & MPOL_F_RELATIVE_NODES)))
290 				return ERR_PTR(-EINVAL);
291 
292 			mode = MPOL_LOCAL;
293 		}
294 	} else if (mode == MPOL_LOCAL) {
295 		if (!nodes_empty(*nodes) ||
296 		    (flags & MPOL_F_STATIC_NODES) ||
297 		    (flags & MPOL_F_RELATIVE_NODES))
298 			return ERR_PTR(-EINVAL);
299 	} else if (nodes_empty(*nodes))
300 		return ERR_PTR(-EINVAL);
301 	policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
302 	if (!policy)
303 		return ERR_PTR(-ENOMEM);
304 	atomic_set(&policy->refcnt, 1);
305 	policy->mode = mode;
306 	policy->flags = flags;
307 	policy->home_node = NUMA_NO_NODE;
308 
309 	return policy;
310 }
311 
312 /* Slow path of a mpol destructor. */
313 void __mpol_put(struct mempolicy *p)
314 {
315 	if (!atomic_dec_and_test(&p->refcnt))
316 		return;
317 	kmem_cache_free(policy_cache, p);
318 }
319 
320 static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
321 {
322 }
323 
324 static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
325 {
326 	nodemask_t tmp;
327 
328 	if (pol->flags & MPOL_F_STATIC_NODES)
329 		nodes_and(tmp, pol->w.user_nodemask, *nodes);
330 	else if (pol->flags & MPOL_F_RELATIVE_NODES)
331 		mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
332 	else {
333 		nodes_remap(tmp, pol->nodes, pol->w.cpuset_mems_allowed,
334 								*nodes);
335 		pol->w.cpuset_mems_allowed = *nodes;
336 	}
337 
338 	if (nodes_empty(tmp))
339 		tmp = *nodes;
340 
341 	pol->nodes = tmp;
342 }
343 
344 static void mpol_rebind_preferred(struct mempolicy *pol,
345 						const nodemask_t *nodes)
346 {
347 	pol->w.cpuset_mems_allowed = *nodes;
348 }
349 
350 /*
351  * mpol_rebind_policy - Migrate a policy to a different set of nodes
352  *
353  * Per-vma policies are protected by mmap_lock. Allocations using per-task
354  * policies are protected by task->mems_allowed_seq to prevent a premature
355  * OOM/allocation failure due to parallel nodemask modification.
356  */
357 static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
358 {
359 	if (!pol || pol->mode == MPOL_LOCAL)
360 		return;
361 	if (!mpol_store_user_nodemask(pol) &&
362 	    nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
363 		return;
364 
365 	mpol_ops[pol->mode].rebind(pol, newmask);
366 }
367 
368 /*
369  * Wrapper for mpol_rebind_policy() that just requires task
370  * pointer, and updates task mempolicy.
371  *
372  * Called with task's alloc_lock held.
373  */
374 
375 void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
376 {
377 	mpol_rebind_policy(tsk->mempolicy, new);
378 }
379 
380 /*
381  * Rebind each vma in mm to new nodemask.
382  *
383  * Call holding a reference to mm.  Takes mm->mmap_lock during call.
384  */
385 
386 void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
387 {
388 	struct vm_area_struct *vma;
389 	VMA_ITERATOR(vmi, mm, 0);
390 
391 	mmap_write_lock(mm);
392 	for_each_vma(vmi, vma) {
393 		vma_start_write(vma);
394 		mpol_rebind_policy(vma->vm_policy, new);
395 	}
396 	mmap_write_unlock(mm);
397 }
398 
399 static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
400 	[MPOL_DEFAULT] = {
401 		.rebind = mpol_rebind_default,
402 	},
403 	[MPOL_INTERLEAVE] = {
404 		.create = mpol_new_nodemask,
405 		.rebind = mpol_rebind_nodemask,
406 	},
407 	[MPOL_PREFERRED] = {
408 		.create = mpol_new_preferred,
409 		.rebind = mpol_rebind_preferred,
410 	},
411 	[MPOL_BIND] = {
412 		.create = mpol_new_nodemask,
413 		.rebind = mpol_rebind_nodemask,
414 	},
415 	[MPOL_LOCAL] = {
416 		.rebind = mpol_rebind_default,
417 	},
418 	[MPOL_PREFERRED_MANY] = {
419 		.create = mpol_new_nodemask,
420 		.rebind = mpol_rebind_preferred,
421 	},
422 };
423 
424 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
425 				unsigned long flags);
426 
427 static bool strictly_unmovable(unsigned long flags)
428 {
429 	/*
430 	 * STRICT without MOVE flags lets do_mbind() fail immediately with -EIO
431 	 * if any misplaced page is found.
432 	 */
433 	return (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ==
434 			 MPOL_MF_STRICT;
435 }
436 
437 struct queue_pages {
438 	struct list_head *pagelist;
439 	unsigned long flags;
440 	nodemask_t *nmask;
441 	unsigned long start;
442 	unsigned long end;
443 	struct vm_area_struct *first;
444 	struct folio *large;		/* note last large folio encountered */
445 	long nr_failed;			/* could not be isolated at this time */
446 };
447 
448 /*
449  * Check if the folio's nid is in qp->nmask.
450  *
451  * If MPOL_MF_INVERT is set in qp->flags, check if the nid is
452  * in the invert of qp->nmask.
453  */
454 static inline bool queue_folio_required(struct folio *folio,
455 					struct queue_pages *qp)
456 {
457 	int nid = folio_nid(folio);
458 	unsigned long flags = qp->flags;
459 
460 	return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
461 }
462 
463 static void queue_folios_pmd(pmd_t *pmd, struct mm_walk *walk)
464 {
465 	struct folio *folio;
466 	struct queue_pages *qp = walk->private;
467 
468 	if (unlikely(is_pmd_migration_entry(*pmd))) {
469 		qp->nr_failed++;
470 		return;
471 	}
472 	folio = pfn_folio(pmd_pfn(*pmd));
473 	if (is_huge_zero_page(&folio->page)) {
474 		walk->action = ACTION_CONTINUE;
475 		return;
476 	}
477 	if (!queue_folio_required(folio, qp))
478 		return;
479 	if (!(qp->flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
480 	    !vma_migratable(walk->vma) ||
481 	    !migrate_folio_add(folio, qp->pagelist, qp->flags))
482 		qp->nr_failed++;
483 }
484 
485 /*
486  * Scan through folios, checking if they satisfy the required conditions,
487  * moving them from LRU to local pagelist for migration if they do (or not).
488  *
489  * queue_folios_pte_range() has two possible return values:
490  * 0 - continue walking to scan for more, even if an existing folio on the
491  *     wrong node could not be isolated and queued for migration.
492  * -EIO - only MPOL_MF_STRICT was specified, without MPOL_MF_MOVE or ..._ALL,
493  *        and an existing folio was on a node that does not follow the policy.
494  */
495 static int queue_folios_pte_range(pmd_t *pmd, unsigned long addr,
496 			unsigned long end, struct mm_walk *walk)
497 {
498 	struct vm_area_struct *vma = walk->vma;
499 	struct folio *folio;
500 	struct queue_pages *qp = walk->private;
501 	unsigned long flags = qp->flags;
502 	pte_t *pte, *mapped_pte;
503 	pte_t ptent;
504 	spinlock_t *ptl;
505 
506 	ptl = pmd_trans_huge_lock(pmd, vma);
507 	if (ptl) {
508 		queue_folios_pmd(pmd, walk);
509 		spin_unlock(ptl);
510 		goto out;
511 	}
512 
513 	mapped_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
514 	if (!pte) {
515 		walk->action = ACTION_AGAIN;
516 		return 0;
517 	}
518 	for (; addr != end; pte++, addr += PAGE_SIZE) {
519 		ptent = ptep_get(pte);
520 		if (pte_none(ptent))
521 			continue;
522 		if (!pte_present(ptent)) {
523 			if (is_migration_entry(pte_to_swp_entry(ptent)))
524 				qp->nr_failed++;
525 			continue;
526 		}
527 		folio = vm_normal_folio(vma, addr, ptent);
528 		if (!folio || folio_is_zone_device(folio))
529 			continue;
530 		/*
531 		 * vm_normal_folio() filters out zero pages, but there might
532 		 * still be reserved folios to skip, perhaps in a VDSO.
533 		 */
534 		if (folio_test_reserved(folio))
535 			continue;
536 		if (!queue_folio_required(folio, qp))
537 			continue;
538 		if (folio_test_large(folio)) {
539 			/*
540 			 * A large folio can only be isolated from LRU once,
541 			 * but may be mapped by many PTEs (and Copy-On-Write may
542 			 * intersperse PTEs of other, order 0, folios).  This is
543 			 * a common case, so don't mistake it for failure (but
544 			 * there can be other cases of multi-mapped pages which
545 			 * this quick check does not help to filter out - and a
546 			 * search of the pagelist might grow to be prohibitive).
547 			 *
548 			 * migrate_pages(&pagelist) returns nr_failed folios, so
549 			 * check "large" now so that queue_pages_range() returns
550 			 * a comparable nr_failed folios.  This does imply that
551 			 * if folio could not be isolated for some racy reason
552 			 * at its first PTE, later PTEs will not give it another
553 			 * chance of isolation; but keeps the accounting simple.
554 			 */
555 			if (folio == qp->large)
556 				continue;
557 			qp->large = folio;
558 		}
559 		if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
560 		    !vma_migratable(vma) ||
561 		    !migrate_folio_add(folio, qp->pagelist, flags)) {
562 			qp->nr_failed++;
563 			if (strictly_unmovable(flags))
564 				break;
565 		}
566 	}
567 	pte_unmap_unlock(mapped_pte, ptl);
568 	cond_resched();
569 out:
570 	if (qp->nr_failed && strictly_unmovable(flags))
571 		return -EIO;
572 	return 0;
573 }
574 
575 static int queue_folios_hugetlb(pte_t *pte, unsigned long hmask,
576 			       unsigned long addr, unsigned long end,
577 			       struct mm_walk *walk)
578 {
579 #ifdef CONFIG_HUGETLB_PAGE
580 	struct queue_pages *qp = walk->private;
581 	unsigned long flags = qp->flags;
582 	struct folio *folio;
583 	spinlock_t *ptl;
584 	pte_t entry;
585 
586 	ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
587 	entry = huge_ptep_get(pte);
588 	if (!pte_present(entry)) {
589 		if (unlikely(is_hugetlb_entry_migration(entry)))
590 			qp->nr_failed++;
591 		goto unlock;
592 	}
593 	folio = pfn_folio(pte_pfn(entry));
594 	if (!queue_folio_required(folio, qp))
595 		goto unlock;
596 	if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
597 	    !vma_migratable(walk->vma)) {
598 		qp->nr_failed++;
599 		goto unlock;
600 	}
601 	/*
602 	 * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
603 	 * Choosing not to migrate a shared folio is not counted as a failure.
604 	 *
605 	 * To check if the folio is shared, ideally we want to make sure
606 	 * every page is mapped to the same process. Doing that is very
607 	 * expensive, so check the estimated sharers of the folio instead.
608 	 */
609 	if ((flags & MPOL_MF_MOVE_ALL) ||
610 	    (folio_estimated_sharers(folio) == 1 && !hugetlb_pmd_shared(pte)))
611 		if (!isolate_hugetlb(folio, qp->pagelist))
612 			qp->nr_failed++;
613 unlock:
614 	spin_unlock(ptl);
615 	if (qp->nr_failed && strictly_unmovable(flags))
616 		return -EIO;
617 #endif
618 	return 0;
619 }
620 
621 #ifdef CONFIG_NUMA_BALANCING
622 /*
623  * This is used to mark a range of virtual addresses to be inaccessible.
624  * These are later cleared by a NUMA hinting fault. Depending on these
625  * faults, pages may be migrated for better NUMA placement.
626  *
627  * This is assuming that NUMA faults are handled using PROT_NONE. If
628  * an architecture makes a different choice, it will need further
629  * changes to the core.
630  */
631 unsigned long change_prot_numa(struct vm_area_struct *vma,
632 			unsigned long addr, unsigned long end)
633 {
634 	struct mmu_gather tlb;
635 	long nr_updated;
636 
637 	tlb_gather_mmu(&tlb, vma->vm_mm);
638 
639 	nr_updated = change_protection(&tlb, vma, addr, end, MM_CP_PROT_NUMA);
640 	if (nr_updated > 0)
641 		count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
642 
643 	tlb_finish_mmu(&tlb);
644 
645 	return nr_updated;
646 }
647 #else
648 static unsigned long change_prot_numa(struct vm_area_struct *vma,
649 			unsigned long addr, unsigned long end)
650 {
651 	return 0;
652 }
653 #endif /* CONFIG_NUMA_BALANCING */
654 
655 static int queue_pages_test_walk(unsigned long start, unsigned long end,
656 				struct mm_walk *walk)
657 {
658 	struct vm_area_struct *next, *vma = walk->vma;
659 	struct queue_pages *qp = walk->private;
660 	unsigned long endvma = vma->vm_end;
661 	unsigned long flags = qp->flags;
662 
663 	/* range check first */
664 	VM_BUG_ON_VMA(!range_in_vma(vma, start, end), vma);
665 
666 	if (!qp->first) {
667 		qp->first = vma;
668 		if (!(flags & MPOL_MF_DISCONTIG_OK) &&
669 			(qp->start < vma->vm_start))
670 			/* hole at head side of range */
671 			return -EFAULT;
672 	}
673 	next = find_vma(vma->vm_mm, vma->vm_end);
674 	if (!(flags & MPOL_MF_DISCONTIG_OK) &&
675 		((vma->vm_end < qp->end) &&
676 		(!next || vma->vm_end < next->vm_start)))
677 		/* hole at middle or tail of range */
678 		return -EFAULT;
679 
680 	/*
681 	 * Need check MPOL_MF_STRICT to return -EIO if possible
682 	 * regardless of vma_migratable
683 	 */
684 	if (!vma_migratable(vma) &&
685 	    !(flags & MPOL_MF_STRICT))
686 		return 1;
687 
688 	if (endvma > end)
689 		endvma = end;
690 
691 	if (flags & MPOL_MF_LAZY) {
692 		/* Similar to task_numa_work, skip inaccessible VMAs */
693 		if (!is_vm_hugetlb_page(vma) && vma_is_accessible(vma) &&
694 			!(vma->vm_flags & VM_MIXEDMAP))
695 			change_prot_numa(vma, start, endvma);
696 		return 1;
697 	}
698 
699 	/*
700 	 * Check page nodes, and queue pages to move, in the current vma.
701 	 * But if no moving, and no strict checking, the scan can be skipped.
702 	 */
703 	if (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
704 		return 0;
705 	return 1;
706 }
707 
708 static const struct mm_walk_ops queue_pages_walk_ops = {
709 	.hugetlb_entry		= queue_folios_hugetlb,
710 	.pmd_entry		= queue_folios_pte_range,
711 	.test_walk		= queue_pages_test_walk,
712 	.walk_lock		= PGWALK_RDLOCK,
713 };
714 
715 static const struct mm_walk_ops queue_pages_lock_vma_walk_ops = {
716 	.hugetlb_entry		= queue_folios_hugetlb,
717 	.pmd_entry		= queue_folios_pte_range,
718 	.test_walk		= queue_pages_test_walk,
719 	.walk_lock		= PGWALK_WRLOCK,
720 };
721 
722 /*
723  * Walk through page tables and collect pages to be migrated.
724  *
725  * If pages found in a given range are not on the required set of @nodes,
726  * and migration is allowed, they are isolated and queued to @pagelist.
727  *
728  * queue_pages_range() may return:
729  * 0 - all pages already on the right node, or successfully queued for moving
730  *     (or neither strict checking nor moving requested: only range checking).
731  * >0 - this number of misplaced folios could not be queued for moving
732  *      (a hugetlbfs page or a transparent huge page being counted as 1).
733  * -EIO - a misplaced page found, when MPOL_MF_STRICT specified without MOVEs.
734  * -EFAULT - a hole in the memory range, when MPOL_MF_DISCONTIG_OK unspecified.
735  */
736 static long
737 queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
738 		nodemask_t *nodes, unsigned long flags,
739 		struct list_head *pagelist)
740 {
741 	int err;
742 	struct queue_pages qp = {
743 		.pagelist = pagelist,
744 		.flags = flags,
745 		.nmask = nodes,
746 		.start = start,
747 		.end = end,
748 		.first = NULL,
749 	};
750 	const struct mm_walk_ops *ops = (flags & MPOL_MF_WRLOCK) ?
751 			&queue_pages_lock_vma_walk_ops : &queue_pages_walk_ops;
752 
753 	err = walk_page_range(mm, start, end, ops, &qp);
754 
755 	if (!qp.first)
756 		/* whole range in hole */
757 		err = -EFAULT;
758 
759 	return err ? : qp.nr_failed;
760 }
761 
762 /*
763  * Apply policy to a single VMA
764  * This must be called with the mmap_lock held for writing.
765  */
766 static int vma_replace_policy(struct vm_area_struct *vma,
767 						struct mempolicy *pol)
768 {
769 	int err;
770 	struct mempolicy *old;
771 	struct mempolicy *new;
772 
773 	vma_assert_write_locked(vma);
774 
775 	pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n",
776 		 vma->vm_start, vma->vm_end, vma->vm_pgoff,
777 		 vma->vm_ops, vma->vm_file,
778 		 vma->vm_ops ? vma->vm_ops->set_policy : NULL);
779 
780 	new = mpol_dup(pol);
781 	if (IS_ERR(new))
782 		return PTR_ERR(new);
783 
784 	if (vma->vm_ops && vma->vm_ops->set_policy) {
785 		err = vma->vm_ops->set_policy(vma, new);
786 		if (err)
787 			goto err_out;
788 	}
789 
790 	old = vma->vm_policy;
791 	vma->vm_policy = new; /* protected by mmap_lock */
792 	mpol_put(old);
793 
794 	return 0;
795  err_out:
796 	mpol_put(new);
797 	return err;
798 }
799 
800 /* Split or merge the VMA (if required) and apply the new policy */
801 static int mbind_range(struct vma_iterator *vmi, struct vm_area_struct *vma,
802 		struct vm_area_struct **prev, unsigned long start,
803 		unsigned long end, struct mempolicy *new_pol)
804 {
805 	struct vm_area_struct *merged;
806 	unsigned long vmstart, vmend;
807 	pgoff_t pgoff;
808 	int err;
809 
810 	vmend = min(end, vma->vm_end);
811 	if (start > vma->vm_start) {
812 		*prev = vma;
813 		vmstart = start;
814 	} else {
815 		vmstart = vma->vm_start;
816 	}
817 
818 	if (mpol_equal(vma_policy(vma), new_pol)) {
819 		*prev = vma;
820 		return 0;
821 	}
822 
823 	pgoff = vma->vm_pgoff + ((vmstart - vma->vm_start) >> PAGE_SHIFT);
824 	merged = vma_merge(vmi, vma->vm_mm, *prev, vmstart, vmend, vma->vm_flags,
825 			 vma->anon_vma, vma->vm_file, pgoff, new_pol,
826 			 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
827 	if (merged) {
828 		*prev = merged;
829 		return vma_replace_policy(merged, new_pol);
830 	}
831 
832 	if (vma->vm_start != vmstart) {
833 		err = split_vma(vmi, vma, vmstart, 1);
834 		if (err)
835 			return err;
836 	}
837 
838 	if (vma->vm_end != vmend) {
839 		err = split_vma(vmi, vma, vmend, 0);
840 		if (err)
841 			return err;
842 	}
843 
844 	*prev = vma;
845 	return vma_replace_policy(vma, new_pol);
846 }
847 
848 /* Set the process memory policy */
849 static long do_set_mempolicy(unsigned short mode, unsigned short flags,
850 			     nodemask_t *nodes)
851 {
852 	struct mempolicy *new, *old;
853 	NODEMASK_SCRATCH(scratch);
854 	int ret;
855 
856 	if (!scratch)
857 		return -ENOMEM;
858 
859 	new = mpol_new(mode, flags, nodes);
860 	if (IS_ERR(new)) {
861 		ret = PTR_ERR(new);
862 		goto out;
863 	}
864 
865 	task_lock(current);
866 	ret = mpol_set_nodemask(new, nodes, scratch);
867 	if (ret) {
868 		task_unlock(current);
869 		mpol_put(new);
870 		goto out;
871 	}
872 
873 	old = current->mempolicy;
874 	current->mempolicy = new;
875 	if (new && new->mode == MPOL_INTERLEAVE)
876 		current->il_prev = MAX_NUMNODES-1;
877 	task_unlock(current);
878 	mpol_put(old);
879 	ret = 0;
880 out:
881 	NODEMASK_SCRATCH_FREE(scratch);
882 	return ret;
883 }
884 
885 /*
886  * Return nodemask for policy for get_mempolicy() query
887  *
888  * Called with task's alloc_lock held
889  */
890 static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes)
891 {
892 	nodes_clear(*nodes);
893 	if (p == &default_policy)
894 		return;
895 
896 	switch (p->mode) {
897 	case MPOL_BIND:
898 	case MPOL_INTERLEAVE:
899 	case MPOL_PREFERRED:
900 	case MPOL_PREFERRED_MANY:
901 		*nodes = p->nodes;
902 		break;
903 	case MPOL_LOCAL:
904 		/* return empty node mask for local allocation */
905 		break;
906 	default:
907 		BUG();
908 	}
909 }
910 
911 static int lookup_node(struct mm_struct *mm, unsigned long addr)
912 {
913 	struct page *p = NULL;
914 	int ret;
915 
916 	ret = get_user_pages_fast(addr & PAGE_MASK, 1, 0, &p);
917 	if (ret > 0) {
918 		ret = page_to_nid(p);
919 		put_page(p);
920 	}
921 	return ret;
922 }
923 
924 /* Retrieve NUMA policy */
925 static long do_get_mempolicy(int *policy, nodemask_t *nmask,
926 			     unsigned long addr, unsigned long flags)
927 {
928 	int err;
929 	struct mm_struct *mm = current->mm;
930 	struct vm_area_struct *vma = NULL;
931 	struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL;
932 
933 	if (flags &
934 		~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
935 		return -EINVAL;
936 
937 	if (flags & MPOL_F_MEMS_ALLOWED) {
938 		if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
939 			return -EINVAL;
940 		*policy = 0;	/* just so it's initialized */
941 		task_lock(current);
942 		*nmask  = cpuset_current_mems_allowed;
943 		task_unlock(current);
944 		return 0;
945 	}
946 
947 	if (flags & MPOL_F_ADDR) {
948 		/*
949 		 * Do NOT fall back to task policy if the
950 		 * vma/shared policy at addr is NULL.  We
951 		 * want to return MPOL_DEFAULT in this case.
952 		 */
953 		mmap_read_lock(mm);
954 		vma = vma_lookup(mm, addr);
955 		if (!vma) {
956 			mmap_read_unlock(mm);
957 			return -EFAULT;
958 		}
959 		if (vma->vm_ops && vma->vm_ops->get_policy)
960 			pol = vma->vm_ops->get_policy(vma, addr);
961 		else
962 			pol = vma->vm_policy;
963 	} else if (addr)
964 		return -EINVAL;
965 
966 	if (!pol)
967 		pol = &default_policy;	/* indicates default behavior */
968 
969 	if (flags & MPOL_F_NODE) {
970 		if (flags & MPOL_F_ADDR) {
971 			/*
972 			 * Take a refcount on the mpol, because we are about to
973 			 * drop the mmap_lock, after which only "pol" remains
974 			 * valid, "vma" is stale.
975 			 */
976 			pol_refcount = pol;
977 			vma = NULL;
978 			mpol_get(pol);
979 			mmap_read_unlock(mm);
980 			err = lookup_node(mm, addr);
981 			if (err < 0)
982 				goto out;
983 			*policy = err;
984 		} else if (pol == current->mempolicy &&
985 				pol->mode == MPOL_INTERLEAVE) {
986 			*policy = next_node_in(current->il_prev, pol->nodes);
987 		} else {
988 			err = -EINVAL;
989 			goto out;
990 		}
991 	} else {
992 		*policy = pol == &default_policy ? MPOL_DEFAULT :
993 						pol->mode;
994 		/*
995 		 * Internal mempolicy flags must be masked off before exposing
996 		 * the policy to userspace.
997 		 */
998 		*policy |= (pol->flags & MPOL_MODE_FLAGS);
999 	}
1000 
1001 	err = 0;
1002 	if (nmask) {
1003 		if (mpol_store_user_nodemask(pol)) {
1004 			*nmask = pol->w.user_nodemask;
1005 		} else {
1006 			task_lock(current);
1007 			get_policy_nodemask(pol, nmask);
1008 			task_unlock(current);
1009 		}
1010 	}
1011 
1012  out:
1013 	mpol_cond_put(pol);
1014 	if (vma)
1015 		mmap_read_unlock(mm);
1016 	if (pol_refcount)
1017 		mpol_put(pol_refcount);
1018 	return err;
1019 }
1020 
1021 #ifdef CONFIG_MIGRATION
1022 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
1023 				unsigned long flags)
1024 {
1025 	/*
1026 	 * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
1027 	 * Choosing not to migrate a shared folio is not counted as a failure.
1028 	 *
1029 	 * To check if the folio is shared, ideally we want to make sure
1030 	 * every page is mapped to the same process. Doing that is very
1031 	 * expensive, so check the estimated sharers of the folio instead.
1032 	 */
1033 	if ((flags & MPOL_MF_MOVE_ALL) || folio_estimated_sharers(folio) == 1) {
1034 		if (folio_isolate_lru(folio)) {
1035 			list_add_tail(&folio->lru, foliolist);
1036 			node_stat_mod_folio(folio,
1037 				NR_ISOLATED_ANON + folio_is_file_lru(folio),
1038 				folio_nr_pages(folio));
1039 		} else {
1040 			/*
1041 			 * Non-movable folio may reach here.  And, there may be
1042 			 * temporary off LRU folios or non-LRU movable folios.
1043 			 * Treat them as unmovable folios since they can't be
1044 			 * isolated, so they can't be moved at the moment.
1045 			 */
1046 			return false;
1047 		}
1048 	}
1049 	return true;
1050 }
1051 
1052 /*
1053  * Migrate pages from one node to a target node.
1054  * Returns error or the number of pages not migrated.
1055  */
1056 static long migrate_to_node(struct mm_struct *mm, int source, int dest,
1057 			    int flags)
1058 {
1059 	nodemask_t nmask;
1060 	struct vm_area_struct *vma;
1061 	LIST_HEAD(pagelist);
1062 	long nr_failed;
1063 	long err = 0;
1064 	struct migration_target_control mtc = {
1065 		.nid = dest,
1066 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1067 	};
1068 
1069 	nodes_clear(nmask);
1070 	node_set(source, nmask);
1071 
1072 	VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
1073 	vma = find_vma(mm, 0);
1074 
1075 	/*
1076 	 * This does not migrate the range, but isolates all pages that
1077 	 * need migration.  Between passing in the full user address
1078 	 * space range and MPOL_MF_DISCONTIG_OK, this call cannot fail,
1079 	 * but passes back the count of pages which could not be isolated.
1080 	 */
1081 	nr_failed = queue_pages_range(mm, vma->vm_start, mm->task_size, &nmask,
1082 				      flags | MPOL_MF_DISCONTIG_OK, &pagelist);
1083 
1084 	if (!list_empty(&pagelist)) {
1085 		err = migrate_pages(&pagelist, alloc_migration_target, NULL,
1086 			(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1087 		if (err)
1088 			putback_movable_pages(&pagelist);
1089 	}
1090 
1091 	if (err >= 0)
1092 		err += nr_failed;
1093 	return err;
1094 }
1095 
1096 /*
1097  * Move pages between the two nodesets so as to preserve the physical
1098  * layout as much as possible.
1099  *
1100  * Returns the number of page that could not be moved.
1101  */
1102 int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
1103 		     const nodemask_t *to, int flags)
1104 {
1105 	long nr_failed = 0;
1106 	long err = 0;
1107 	nodemask_t tmp;
1108 
1109 	lru_cache_disable();
1110 
1111 	mmap_read_lock(mm);
1112 
1113 	/*
1114 	 * Find a 'source' bit set in 'tmp' whose corresponding 'dest'
1115 	 * bit in 'to' is not also set in 'tmp'.  Clear the found 'source'
1116 	 * bit in 'tmp', and return that <source, dest> pair for migration.
1117 	 * The pair of nodemasks 'to' and 'from' define the map.
1118 	 *
1119 	 * If no pair of bits is found that way, fallback to picking some
1120 	 * pair of 'source' and 'dest' bits that are not the same.  If the
1121 	 * 'source' and 'dest' bits are the same, this represents a node
1122 	 * that will be migrating to itself, so no pages need move.
1123 	 *
1124 	 * If no bits are left in 'tmp', or if all remaining bits left
1125 	 * in 'tmp' correspond to the same bit in 'to', return false
1126 	 * (nothing left to migrate).
1127 	 *
1128 	 * This lets us pick a pair of nodes to migrate between, such that
1129 	 * if possible the dest node is not already occupied by some other
1130 	 * source node, minimizing the risk of overloading the memory on a
1131 	 * node that would happen if we migrated incoming memory to a node
1132 	 * before migrating outgoing memory source that same node.
1133 	 *
1134 	 * A single scan of tmp is sufficient.  As we go, we remember the
1135 	 * most recent <s, d> pair that moved (s != d).  If we find a pair
1136 	 * that not only moved, but what's better, moved to an empty slot
1137 	 * (d is not set in tmp), then we break out then, with that pair.
1138 	 * Otherwise when we finish scanning from_tmp, we at least have the
1139 	 * most recent <s, d> pair that moved.  If we get all the way through
1140 	 * the scan of tmp without finding any node that moved, much less
1141 	 * moved to an empty node, then there is nothing left worth migrating.
1142 	 */
1143 
1144 	tmp = *from;
1145 	while (!nodes_empty(tmp)) {
1146 		int s, d;
1147 		int source = NUMA_NO_NODE;
1148 		int dest = 0;
1149 
1150 		for_each_node_mask(s, tmp) {
1151 
1152 			/*
1153 			 * do_migrate_pages() tries to maintain the relative
1154 			 * node relationship of the pages established between
1155 			 * threads and memory areas.
1156                          *
1157 			 * However if the number of source nodes is not equal to
1158 			 * the number of destination nodes we can not preserve
1159 			 * this node relative relationship.  In that case, skip
1160 			 * copying memory from a node that is in the destination
1161 			 * mask.
1162 			 *
1163 			 * Example: [2,3,4] -> [3,4,5] moves everything.
1164 			 *          [0-7] - > [3,4,5] moves only 0,1,2,6,7.
1165 			 */
1166 
1167 			if ((nodes_weight(*from) != nodes_weight(*to)) &&
1168 						(node_isset(s, *to)))
1169 				continue;
1170 
1171 			d = node_remap(s, *from, *to);
1172 			if (s == d)
1173 				continue;
1174 
1175 			source = s;	/* Node moved. Memorize */
1176 			dest = d;
1177 
1178 			/* dest not in remaining from nodes? */
1179 			if (!node_isset(dest, tmp))
1180 				break;
1181 		}
1182 		if (source == NUMA_NO_NODE)
1183 			break;
1184 
1185 		node_clear(source, tmp);
1186 		err = migrate_to_node(mm, source, dest, flags);
1187 		if (err > 0)
1188 			nr_failed += err;
1189 		if (err < 0)
1190 			break;
1191 	}
1192 	mmap_read_unlock(mm);
1193 
1194 	lru_cache_enable();
1195 	if (err < 0)
1196 		return err;
1197 	return (nr_failed < INT_MAX) ? nr_failed : INT_MAX;
1198 }
1199 
1200 /*
1201  * Allocate a new page for page migration based on vma policy.
1202  * Start by assuming the page is mapped by the same vma as contains @start.
1203  * Search forward from there, if not.  N.B., this assumes that the
1204  * list of pages handed to migrate_pages()--which is how we get here--
1205  * is in virtual address order.
1206  */
1207 static struct folio *new_folio(struct folio *src, unsigned long start)
1208 {
1209 	struct vm_area_struct *vma;
1210 	unsigned long address;
1211 	VMA_ITERATOR(vmi, current->mm, start);
1212 	gfp_t gfp = GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL;
1213 
1214 	for_each_vma(vmi, vma) {
1215 		address = page_address_in_vma(&src->page, vma);
1216 		if (address != -EFAULT)
1217 			break;
1218 	}
1219 
1220 	if (folio_test_hugetlb(src)) {
1221 		return alloc_hugetlb_folio_vma(folio_hstate(src),
1222 				vma, address);
1223 	}
1224 
1225 	if (folio_test_large(src))
1226 		gfp = GFP_TRANSHUGE;
1227 
1228 	/*
1229 	 * if !vma, vma_alloc_folio() will use task or system default policy
1230 	 */
1231 	return vma_alloc_folio(gfp, folio_order(src), vma, address,
1232 			folio_test_large(src));
1233 }
1234 #else
1235 
1236 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
1237 				unsigned long flags)
1238 {
1239 	return false;
1240 }
1241 
1242 int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
1243 		     const nodemask_t *to, int flags)
1244 {
1245 	return -ENOSYS;
1246 }
1247 
1248 static struct folio *new_folio(struct folio *src, unsigned long start)
1249 {
1250 	return NULL;
1251 }
1252 #endif
1253 
1254 static long do_mbind(unsigned long start, unsigned long len,
1255 		     unsigned short mode, unsigned short mode_flags,
1256 		     nodemask_t *nmask, unsigned long flags)
1257 {
1258 	struct mm_struct *mm = current->mm;
1259 	struct vm_area_struct *vma, *prev;
1260 	struct vma_iterator vmi;
1261 	struct mempolicy *new;
1262 	unsigned long end;
1263 	long err;
1264 	long nr_failed;
1265 	LIST_HEAD(pagelist);
1266 
1267 	if (flags & ~(unsigned long)MPOL_MF_VALID)
1268 		return -EINVAL;
1269 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1270 		return -EPERM;
1271 
1272 	if (start & ~PAGE_MASK)
1273 		return -EINVAL;
1274 
1275 	if (mode == MPOL_DEFAULT)
1276 		flags &= ~MPOL_MF_STRICT;
1277 
1278 	len = PAGE_ALIGN(len);
1279 	end = start + len;
1280 
1281 	if (end < start)
1282 		return -EINVAL;
1283 	if (end == start)
1284 		return 0;
1285 
1286 	new = mpol_new(mode, mode_flags, nmask);
1287 	if (IS_ERR(new))
1288 		return PTR_ERR(new);
1289 
1290 	if (flags & MPOL_MF_LAZY)
1291 		new->flags |= MPOL_F_MOF;
1292 
1293 	/*
1294 	 * If we are using the default policy then operation
1295 	 * on discontinuous address spaces is okay after all
1296 	 */
1297 	if (!new)
1298 		flags |= MPOL_MF_DISCONTIG_OK;
1299 
1300 	pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n",
1301 		 start, start + len, mode, mode_flags,
1302 		 nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE);
1303 
1304 	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
1305 		lru_cache_disable();
1306 	{
1307 		NODEMASK_SCRATCH(scratch);
1308 		if (scratch) {
1309 			mmap_write_lock(mm);
1310 			err = mpol_set_nodemask(new, nmask, scratch);
1311 			if (err)
1312 				mmap_write_unlock(mm);
1313 		} else
1314 			err = -ENOMEM;
1315 		NODEMASK_SCRATCH_FREE(scratch);
1316 	}
1317 	if (err)
1318 		goto mpol_out;
1319 
1320 	/*
1321 	 * Lock the VMAs before scanning for pages to migrate,
1322 	 * to ensure we don't miss a concurrently inserted page.
1323 	 */
1324 	nr_failed = queue_pages_range(mm, start, end, nmask,
1325 			flags | MPOL_MF_INVERT | MPOL_MF_WRLOCK, &pagelist);
1326 
1327 	if (nr_failed < 0) {
1328 		err = nr_failed;
1329 	} else {
1330 		vma_iter_init(&vmi, mm, start);
1331 		prev = vma_prev(&vmi);
1332 		for_each_vma_range(vmi, vma, end) {
1333 			err = mbind_range(&vmi, vma, &prev, start, end, new);
1334 			if (err)
1335 				break;
1336 		}
1337 	}
1338 
1339 	if (!err) {
1340 		if (!list_empty(&pagelist)) {
1341 			WARN_ON_ONCE(flags & MPOL_MF_LAZY);
1342 			nr_failed |= migrate_pages(&pagelist, new_folio, NULL,
1343 				start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND, NULL);
1344 		}
1345 		if (nr_failed && (flags & MPOL_MF_STRICT))
1346 			err = -EIO;
1347 	}
1348 
1349 	if (!list_empty(&pagelist))
1350 		putback_movable_pages(&pagelist);
1351 
1352 	mmap_write_unlock(mm);
1353 mpol_out:
1354 	mpol_put(new);
1355 	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
1356 		lru_cache_enable();
1357 	return err;
1358 }
1359 
1360 /*
1361  * User space interface with variable sized bitmaps for nodelists.
1362  */
1363 static int get_bitmap(unsigned long *mask, const unsigned long __user *nmask,
1364 		      unsigned long maxnode)
1365 {
1366 	unsigned long nlongs = BITS_TO_LONGS(maxnode);
1367 	int ret;
1368 
1369 	if (in_compat_syscall())
1370 		ret = compat_get_bitmap(mask,
1371 					(const compat_ulong_t __user *)nmask,
1372 					maxnode);
1373 	else
1374 		ret = copy_from_user(mask, nmask,
1375 				     nlongs * sizeof(unsigned long));
1376 
1377 	if (ret)
1378 		return -EFAULT;
1379 
1380 	if (maxnode % BITS_PER_LONG)
1381 		mask[nlongs - 1] &= (1UL << (maxnode % BITS_PER_LONG)) - 1;
1382 
1383 	return 0;
1384 }
1385 
1386 /* Copy a node mask from user space. */
1387 static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
1388 		     unsigned long maxnode)
1389 {
1390 	--maxnode;
1391 	nodes_clear(*nodes);
1392 	if (maxnode == 0 || !nmask)
1393 		return 0;
1394 	if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
1395 		return -EINVAL;
1396 
1397 	/*
1398 	 * When the user specified more nodes than supported just check
1399 	 * if the non supported part is all zero, one word at a time,
1400 	 * starting at the end.
1401 	 */
1402 	while (maxnode > MAX_NUMNODES) {
1403 		unsigned long bits = min_t(unsigned long, maxnode, BITS_PER_LONG);
1404 		unsigned long t;
1405 
1406 		if (get_bitmap(&t, &nmask[(maxnode - 1) / BITS_PER_LONG], bits))
1407 			return -EFAULT;
1408 
1409 		if (maxnode - bits >= MAX_NUMNODES) {
1410 			maxnode -= bits;
1411 		} else {
1412 			maxnode = MAX_NUMNODES;
1413 			t &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1);
1414 		}
1415 		if (t)
1416 			return -EINVAL;
1417 	}
1418 
1419 	return get_bitmap(nodes_addr(*nodes), nmask, maxnode);
1420 }
1421 
1422 /* Copy a kernel node mask to user space */
1423 static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
1424 			      nodemask_t *nodes)
1425 {
1426 	unsigned long copy = ALIGN(maxnode-1, 64) / 8;
1427 	unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
1428 	bool compat = in_compat_syscall();
1429 
1430 	if (compat)
1431 		nbytes = BITS_TO_COMPAT_LONGS(nr_node_ids) * sizeof(compat_long_t);
1432 
1433 	if (copy > nbytes) {
1434 		if (copy > PAGE_SIZE)
1435 			return -EINVAL;
1436 		if (clear_user((char __user *)mask + nbytes, copy - nbytes))
1437 			return -EFAULT;
1438 		copy = nbytes;
1439 		maxnode = nr_node_ids;
1440 	}
1441 
1442 	if (compat)
1443 		return compat_put_bitmap((compat_ulong_t __user *)mask,
1444 					 nodes_addr(*nodes), maxnode);
1445 
1446 	return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
1447 }
1448 
1449 /* Basic parameter sanity check used by both mbind() and set_mempolicy() */
1450 static inline int sanitize_mpol_flags(int *mode, unsigned short *flags)
1451 {
1452 	*flags = *mode & MPOL_MODE_FLAGS;
1453 	*mode &= ~MPOL_MODE_FLAGS;
1454 
1455 	if ((unsigned int)(*mode) >=  MPOL_MAX)
1456 		return -EINVAL;
1457 	if ((*flags & MPOL_F_STATIC_NODES) && (*flags & MPOL_F_RELATIVE_NODES))
1458 		return -EINVAL;
1459 	if (*flags & MPOL_F_NUMA_BALANCING) {
1460 		if (*mode != MPOL_BIND)
1461 			return -EINVAL;
1462 		*flags |= (MPOL_F_MOF | MPOL_F_MORON);
1463 	}
1464 	return 0;
1465 }
1466 
1467 static long kernel_mbind(unsigned long start, unsigned long len,
1468 			 unsigned long mode, const unsigned long __user *nmask,
1469 			 unsigned long maxnode, unsigned int flags)
1470 {
1471 	unsigned short mode_flags;
1472 	nodemask_t nodes;
1473 	int lmode = mode;
1474 	int err;
1475 
1476 	start = untagged_addr(start);
1477 	err = sanitize_mpol_flags(&lmode, &mode_flags);
1478 	if (err)
1479 		return err;
1480 
1481 	err = get_nodes(&nodes, nmask, maxnode);
1482 	if (err)
1483 		return err;
1484 
1485 	return do_mbind(start, len, lmode, mode_flags, &nodes, flags);
1486 }
1487 
1488 SYSCALL_DEFINE4(set_mempolicy_home_node, unsigned long, start, unsigned long, len,
1489 		unsigned long, home_node, unsigned long, flags)
1490 {
1491 	struct mm_struct *mm = current->mm;
1492 	struct vm_area_struct *vma, *prev;
1493 	struct mempolicy *new, *old;
1494 	unsigned long end;
1495 	int err = -ENOENT;
1496 	VMA_ITERATOR(vmi, mm, start);
1497 
1498 	start = untagged_addr(start);
1499 	if (start & ~PAGE_MASK)
1500 		return -EINVAL;
1501 	/*
1502 	 * flags is used for future extension if any.
1503 	 */
1504 	if (flags != 0)
1505 		return -EINVAL;
1506 
1507 	/*
1508 	 * Check home_node is online to avoid accessing uninitialized
1509 	 * NODE_DATA.
1510 	 */
1511 	if (home_node >= MAX_NUMNODES || !node_online(home_node))
1512 		return -EINVAL;
1513 
1514 	len = PAGE_ALIGN(len);
1515 	end = start + len;
1516 
1517 	if (end < start)
1518 		return -EINVAL;
1519 	if (end == start)
1520 		return 0;
1521 	mmap_write_lock(mm);
1522 	prev = vma_prev(&vmi);
1523 	for_each_vma_range(vmi, vma, end) {
1524 		/*
1525 		 * If any vma in the range got policy other than MPOL_BIND
1526 		 * or MPOL_PREFERRED_MANY we return error. We don't reset
1527 		 * the home node for vmas we already updated before.
1528 		 */
1529 		old = vma_policy(vma);
1530 		if (!old) {
1531 			prev = vma;
1532 			continue;
1533 		}
1534 		if (old->mode != MPOL_BIND && old->mode != MPOL_PREFERRED_MANY) {
1535 			err = -EOPNOTSUPP;
1536 			break;
1537 		}
1538 		new = mpol_dup(old);
1539 		if (IS_ERR(new)) {
1540 			err = PTR_ERR(new);
1541 			break;
1542 		}
1543 
1544 		vma_start_write(vma);
1545 		new->home_node = home_node;
1546 		err = mbind_range(&vmi, vma, &prev, start, end, new);
1547 		mpol_put(new);
1548 		if (err)
1549 			break;
1550 	}
1551 	mmap_write_unlock(mm);
1552 	return err;
1553 }
1554 
1555 SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
1556 		unsigned long, mode, const unsigned long __user *, nmask,
1557 		unsigned long, maxnode, unsigned int, flags)
1558 {
1559 	return kernel_mbind(start, len, mode, nmask, maxnode, flags);
1560 }
1561 
1562 /* Set the process memory policy */
1563 static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask,
1564 				 unsigned long maxnode)
1565 {
1566 	unsigned short mode_flags;
1567 	nodemask_t nodes;
1568 	int lmode = mode;
1569 	int err;
1570 
1571 	err = sanitize_mpol_flags(&lmode, &mode_flags);
1572 	if (err)
1573 		return err;
1574 
1575 	err = get_nodes(&nodes, nmask, maxnode);
1576 	if (err)
1577 		return err;
1578 
1579 	return do_set_mempolicy(lmode, mode_flags, &nodes);
1580 }
1581 
1582 SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
1583 		unsigned long, maxnode)
1584 {
1585 	return kernel_set_mempolicy(mode, nmask, maxnode);
1586 }
1587 
1588 static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
1589 				const unsigned long __user *old_nodes,
1590 				const unsigned long __user *new_nodes)
1591 {
1592 	struct mm_struct *mm = NULL;
1593 	struct task_struct *task;
1594 	nodemask_t task_nodes;
1595 	int err;
1596 	nodemask_t *old;
1597 	nodemask_t *new;
1598 	NODEMASK_SCRATCH(scratch);
1599 
1600 	if (!scratch)
1601 		return -ENOMEM;
1602 
1603 	old = &scratch->mask1;
1604 	new = &scratch->mask2;
1605 
1606 	err = get_nodes(old, old_nodes, maxnode);
1607 	if (err)
1608 		goto out;
1609 
1610 	err = get_nodes(new, new_nodes, maxnode);
1611 	if (err)
1612 		goto out;
1613 
1614 	/* Find the mm_struct */
1615 	rcu_read_lock();
1616 	task = pid ? find_task_by_vpid(pid) : current;
1617 	if (!task) {
1618 		rcu_read_unlock();
1619 		err = -ESRCH;
1620 		goto out;
1621 	}
1622 	get_task_struct(task);
1623 
1624 	err = -EINVAL;
1625 
1626 	/*
1627 	 * Check if this process has the right to modify the specified process.
1628 	 * Use the regular "ptrace_may_access()" checks.
1629 	 */
1630 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1631 		rcu_read_unlock();
1632 		err = -EPERM;
1633 		goto out_put;
1634 	}
1635 	rcu_read_unlock();
1636 
1637 	task_nodes = cpuset_mems_allowed(task);
1638 	/* Is the user allowed to access the target nodes? */
1639 	if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
1640 		err = -EPERM;
1641 		goto out_put;
1642 	}
1643 
1644 	task_nodes = cpuset_mems_allowed(current);
1645 	nodes_and(*new, *new, task_nodes);
1646 	if (nodes_empty(*new))
1647 		goto out_put;
1648 
1649 	err = security_task_movememory(task);
1650 	if (err)
1651 		goto out_put;
1652 
1653 	mm = get_task_mm(task);
1654 	put_task_struct(task);
1655 
1656 	if (!mm) {
1657 		err = -EINVAL;
1658 		goto out;
1659 	}
1660 
1661 	err = do_migrate_pages(mm, old, new,
1662 		capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
1663 
1664 	mmput(mm);
1665 out:
1666 	NODEMASK_SCRATCH_FREE(scratch);
1667 
1668 	return err;
1669 
1670 out_put:
1671 	put_task_struct(task);
1672 	goto out;
1673 
1674 }
1675 
1676 SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
1677 		const unsigned long __user *, old_nodes,
1678 		const unsigned long __user *, new_nodes)
1679 {
1680 	return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes);
1681 }
1682 
1683 
1684 /* Retrieve NUMA policy */
1685 static int kernel_get_mempolicy(int __user *policy,
1686 				unsigned long __user *nmask,
1687 				unsigned long maxnode,
1688 				unsigned long addr,
1689 				unsigned long flags)
1690 {
1691 	int err;
1692 	int pval;
1693 	nodemask_t nodes;
1694 
1695 	if (nmask != NULL && maxnode < nr_node_ids)
1696 		return -EINVAL;
1697 
1698 	addr = untagged_addr(addr);
1699 
1700 	err = do_get_mempolicy(&pval, &nodes, addr, flags);
1701 
1702 	if (err)
1703 		return err;
1704 
1705 	if (policy && put_user(pval, policy))
1706 		return -EFAULT;
1707 
1708 	if (nmask)
1709 		err = copy_nodes_to_user(nmask, maxnode, &nodes);
1710 
1711 	return err;
1712 }
1713 
1714 SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
1715 		unsigned long __user *, nmask, unsigned long, maxnode,
1716 		unsigned long, addr, unsigned long, flags)
1717 {
1718 	return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags);
1719 }
1720 
1721 bool vma_migratable(struct vm_area_struct *vma)
1722 {
1723 	if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1724 		return false;
1725 
1726 	/*
1727 	 * DAX device mappings require predictable access latency, so avoid
1728 	 * incurring periodic faults.
1729 	 */
1730 	if (vma_is_dax(vma))
1731 		return false;
1732 
1733 	if (is_vm_hugetlb_page(vma) &&
1734 		!hugepage_migration_supported(hstate_vma(vma)))
1735 		return false;
1736 
1737 	/*
1738 	 * Migration allocates pages in the highest zone. If we cannot
1739 	 * do so then migration (at least from node to node) is not
1740 	 * possible.
1741 	 */
1742 	if (vma->vm_file &&
1743 		gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping))
1744 			< policy_zone)
1745 		return false;
1746 	return true;
1747 }
1748 
1749 struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
1750 						unsigned long addr)
1751 {
1752 	struct mempolicy *pol = NULL;
1753 
1754 	if (vma) {
1755 		if (vma->vm_ops && vma->vm_ops->get_policy) {
1756 			pol = vma->vm_ops->get_policy(vma, addr);
1757 		} else if (vma->vm_policy) {
1758 			pol = vma->vm_policy;
1759 
1760 			/*
1761 			 * shmem_alloc_page() passes MPOL_F_SHARED policy with
1762 			 * a pseudo vma whose vma->vm_ops=NULL. Take a reference
1763 			 * count on these policies which will be dropped by
1764 			 * mpol_cond_put() later
1765 			 */
1766 			if (mpol_needs_cond_ref(pol))
1767 				mpol_get(pol);
1768 		}
1769 	}
1770 
1771 	return pol;
1772 }
1773 
1774 /*
1775  * get_vma_policy(@vma, @addr)
1776  * @vma: virtual memory area whose policy is sought
1777  * @addr: address in @vma for shared policy lookup
1778  *
1779  * Returns effective policy for a VMA at specified address.
1780  * Falls back to current->mempolicy or system default policy, as necessary.
1781  * Shared policies [those marked as MPOL_F_SHARED] require an extra reference
1782  * count--added by the get_policy() vm_op, as appropriate--to protect against
1783  * freeing by another task.  It is the caller's responsibility to free the
1784  * extra reference for shared policies.
1785  */
1786 static struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
1787 						unsigned long addr)
1788 {
1789 	struct mempolicy *pol = __get_vma_policy(vma, addr);
1790 
1791 	if (!pol)
1792 		pol = get_task_policy(current);
1793 
1794 	return pol;
1795 }
1796 
1797 bool vma_policy_mof(struct vm_area_struct *vma)
1798 {
1799 	struct mempolicy *pol;
1800 
1801 	if (vma->vm_ops && vma->vm_ops->get_policy) {
1802 		bool ret = false;
1803 
1804 		pol = vma->vm_ops->get_policy(vma, vma->vm_start);
1805 		if (pol && (pol->flags & MPOL_F_MOF))
1806 			ret = true;
1807 		mpol_cond_put(pol);
1808 
1809 		return ret;
1810 	}
1811 
1812 	pol = vma->vm_policy;
1813 	if (!pol)
1814 		pol = get_task_policy(current);
1815 
1816 	return pol->flags & MPOL_F_MOF;
1817 }
1818 
1819 bool apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
1820 {
1821 	enum zone_type dynamic_policy_zone = policy_zone;
1822 
1823 	BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
1824 
1825 	/*
1826 	 * if policy->nodes has movable memory only,
1827 	 * we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
1828 	 *
1829 	 * policy->nodes is intersect with node_states[N_MEMORY].
1830 	 * so if the following test fails, it implies
1831 	 * policy->nodes has movable memory only.
1832 	 */
1833 	if (!nodes_intersects(policy->nodes, node_states[N_HIGH_MEMORY]))
1834 		dynamic_policy_zone = ZONE_MOVABLE;
1835 
1836 	return zone >= dynamic_policy_zone;
1837 }
1838 
1839 /*
1840  * Return a nodemask representing a mempolicy for filtering nodes for
1841  * page allocation
1842  */
1843 nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy)
1844 {
1845 	int mode = policy->mode;
1846 
1847 	/* Lower zones don't get a nodemask applied for MPOL_BIND */
1848 	if (unlikely(mode == MPOL_BIND) &&
1849 		apply_policy_zone(policy, gfp_zone(gfp)) &&
1850 		cpuset_nodemask_valid_mems_allowed(&policy->nodes))
1851 		return &policy->nodes;
1852 
1853 	if (mode == MPOL_PREFERRED_MANY)
1854 		return &policy->nodes;
1855 
1856 	return NULL;
1857 }
1858 
1859 /*
1860  * Return the  preferred node id for 'prefer' mempolicy, and return
1861  * the given id for all other policies.
1862  *
1863  * policy_node() is always coupled with policy_nodemask(), which
1864  * secures the nodemask limit for 'bind' and 'prefer-many' policy.
1865  */
1866 static int policy_node(gfp_t gfp, struct mempolicy *policy, int nd)
1867 {
1868 	if (policy->mode == MPOL_PREFERRED) {
1869 		nd = first_node(policy->nodes);
1870 	} else {
1871 		/*
1872 		 * __GFP_THISNODE shouldn't even be used with the bind policy
1873 		 * because we might easily break the expectation to stay on the
1874 		 * requested node and not break the policy.
1875 		 */
1876 		WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE));
1877 	}
1878 
1879 	if ((policy->mode == MPOL_BIND ||
1880 	     policy->mode == MPOL_PREFERRED_MANY) &&
1881 	    policy->home_node != NUMA_NO_NODE)
1882 		return policy->home_node;
1883 
1884 	return nd;
1885 }
1886 
1887 /* Do dynamic interleaving for a process */
1888 static unsigned interleave_nodes(struct mempolicy *policy)
1889 {
1890 	unsigned next;
1891 	struct task_struct *me = current;
1892 
1893 	next = next_node_in(me->il_prev, policy->nodes);
1894 	if (next < MAX_NUMNODES)
1895 		me->il_prev = next;
1896 	return next;
1897 }
1898 
1899 /*
1900  * Depending on the memory policy provide a node from which to allocate the
1901  * next slab entry.
1902  */
1903 unsigned int mempolicy_slab_node(void)
1904 {
1905 	struct mempolicy *policy;
1906 	int node = numa_mem_id();
1907 
1908 	if (!in_task())
1909 		return node;
1910 
1911 	policy = current->mempolicy;
1912 	if (!policy)
1913 		return node;
1914 
1915 	switch (policy->mode) {
1916 	case MPOL_PREFERRED:
1917 		return first_node(policy->nodes);
1918 
1919 	case MPOL_INTERLEAVE:
1920 		return interleave_nodes(policy);
1921 
1922 	case MPOL_BIND:
1923 	case MPOL_PREFERRED_MANY:
1924 	{
1925 		struct zoneref *z;
1926 
1927 		/*
1928 		 * Follow bind policy behavior and start allocation at the
1929 		 * first node.
1930 		 */
1931 		struct zonelist *zonelist;
1932 		enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
1933 		zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
1934 		z = first_zones_zonelist(zonelist, highest_zoneidx,
1935 							&policy->nodes);
1936 		return z->zone ? zone_to_nid(z->zone) : node;
1937 	}
1938 	case MPOL_LOCAL:
1939 		return node;
1940 
1941 	default:
1942 		BUG();
1943 	}
1944 }
1945 
1946 /*
1947  * Do static interleaving for a VMA with known offset @n.  Returns the n'th
1948  * node in pol->nodes (starting from n=0), wrapping around if n exceeds the
1949  * number of present nodes.
1950  */
1951 static unsigned offset_il_node(struct mempolicy *pol, unsigned long n)
1952 {
1953 	nodemask_t nodemask = pol->nodes;
1954 	unsigned int target, nnodes;
1955 	int i;
1956 	int nid;
1957 	/*
1958 	 * The barrier will stabilize the nodemask in a register or on
1959 	 * the stack so that it will stop changing under the code.
1960 	 *
1961 	 * Between first_node() and next_node(), pol->nodes could be changed
1962 	 * by other threads. So we put pol->nodes in a local stack.
1963 	 */
1964 	barrier();
1965 
1966 	nnodes = nodes_weight(nodemask);
1967 	if (!nnodes)
1968 		return numa_node_id();
1969 	target = (unsigned int)n % nnodes;
1970 	nid = first_node(nodemask);
1971 	for (i = 0; i < target; i++)
1972 		nid = next_node(nid, nodemask);
1973 	return nid;
1974 }
1975 
1976 /* Determine a node number for interleave */
1977 static inline unsigned interleave_nid(struct mempolicy *pol,
1978 		 struct vm_area_struct *vma, unsigned long addr, int shift)
1979 {
1980 	if (vma) {
1981 		unsigned long off;
1982 
1983 		/*
1984 		 * for small pages, there is no difference between
1985 		 * shift and PAGE_SHIFT, so the bit-shift is safe.
1986 		 * for huge pages, since vm_pgoff is in units of small
1987 		 * pages, we need to shift off the always 0 bits to get
1988 		 * a useful offset.
1989 		 */
1990 		BUG_ON(shift < PAGE_SHIFT);
1991 		off = vma->vm_pgoff >> (shift - PAGE_SHIFT);
1992 		off += (addr - vma->vm_start) >> shift;
1993 		return offset_il_node(pol, off);
1994 	} else
1995 		return interleave_nodes(pol);
1996 }
1997 
1998 #ifdef CONFIG_HUGETLBFS
1999 /*
2000  * huge_node(@vma, @addr, @gfp_flags, @mpol)
2001  * @vma: virtual memory area whose policy is sought
2002  * @addr: address in @vma for shared policy lookup and interleave policy
2003  * @gfp_flags: for requested zone
2004  * @mpol: pointer to mempolicy pointer for reference counted mempolicy
2005  * @nodemask: pointer to nodemask pointer for 'bind' and 'prefer-many' policy
2006  *
2007  * Returns a nid suitable for a huge page allocation and a pointer
2008  * to the struct mempolicy for conditional unref after allocation.
2009  * If the effective policy is 'bind' or 'prefer-many', returns a pointer
2010  * to the mempolicy's @nodemask for filtering the zonelist.
2011  *
2012  * Must be protected by read_mems_allowed_begin()
2013  */
2014 int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags,
2015 				struct mempolicy **mpol, nodemask_t **nodemask)
2016 {
2017 	int nid;
2018 	int mode;
2019 
2020 	*mpol = get_vma_policy(vma, addr);
2021 	*nodemask = NULL;
2022 	mode = (*mpol)->mode;
2023 
2024 	if (unlikely(mode == MPOL_INTERLEAVE)) {
2025 		nid = interleave_nid(*mpol, vma, addr,
2026 					huge_page_shift(hstate_vma(vma)));
2027 	} else {
2028 		nid = policy_node(gfp_flags, *mpol, numa_node_id());
2029 		if (mode == MPOL_BIND || mode == MPOL_PREFERRED_MANY)
2030 			*nodemask = &(*mpol)->nodes;
2031 	}
2032 	return nid;
2033 }
2034 
2035 /*
2036  * init_nodemask_of_mempolicy
2037  *
2038  * If the current task's mempolicy is "default" [NULL], return 'false'
2039  * to indicate default policy.  Otherwise, extract the policy nodemask
2040  * for 'bind' or 'interleave' policy into the argument nodemask, or
2041  * initialize the argument nodemask to contain the single node for
2042  * 'preferred' or 'local' policy and return 'true' to indicate presence
2043  * of non-default mempolicy.
2044  *
2045  * We don't bother with reference counting the mempolicy [mpol_get/put]
2046  * because the current task is examining it's own mempolicy and a task's
2047  * mempolicy is only ever changed by the task itself.
2048  *
2049  * N.B., it is the caller's responsibility to free a returned nodemask.
2050  */
2051 bool init_nodemask_of_mempolicy(nodemask_t *mask)
2052 {
2053 	struct mempolicy *mempolicy;
2054 
2055 	if (!(mask && current->mempolicy))
2056 		return false;
2057 
2058 	task_lock(current);
2059 	mempolicy = current->mempolicy;
2060 	switch (mempolicy->mode) {
2061 	case MPOL_PREFERRED:
2062 	case MPOL_PREFERRED_MANY:
2063 	case MPOL_BIND:
2064 	case MPOL_INTERLEAVE:
2065 		*mask = mempolicy->nodes;
2066 		break;
2067 
2068 	case MPOL_LOCAL:
2069 		init_nodemask_of_node(mask, numa_node_id());
2070 		break;
2071 
2072 	default:
2073 		BUG();
2074 	}
2075 	task_unlock(current);
2076 
2077 	return true;
2078 }
2079 #endif
2080 
2081 /*
2082  * mempolicy_in_oom_domain
2083  *
2084  * If tsk's mempolicy is "bind", check for intersection between mask and
2085  * the policy nodemask. Otherwise, return true for all other policies
2086  * including "interleave", as a tsk with "interleave" policy may have
2087  * memory allocated from all nodes in system.
2088  *
2089  * Takes task_lock(tsk) to prevent freeing of its mempolicy.
2090  */
2091 bool mempolicy_in_oom_domain(struct task_struct *tsk,
2092 					const nodemask_t *mask)
2093 {
2094 	struct mempolicy *mempolicy;
2095 	bool ret = true;
2096 
2097 	if (!mask)
2098 		return ret;
2099 
2100 	task_lock(tsk);
2101 	mempolicy = tsk->mempolicy;
2102 	if (mempolicy && mempolicy->mode == MPOL_BIND)
2103 		ret = nodes_intersects(mempolicy->nodes, *mask);
2104 	task_unlock(tsk);
2105 
2106 	return ret;
2107 }
2108 
2109 /* Allocate a page in interleaved policy.
2110    Own path because it needs to do special accounting. */
2111 static struct page *alloc_page_interleave(gfp_t gfp, unsigned order,
2112 					unsigned nid)
2113 {
2114 	struct page *page;
2115 
2116 	page = __alloc_pages(gfp, order, nid, NULL);
2117 	/* skip NUMA_INTERLEAVE_HIT counter update if numa stats is disabled */
2118 	if (!static_branch_likely(&vm_numa_stat_key))
2119 		return page;
2120 	if (page && page_to_nid(page) == nid) {
2121 		preempt_disable();
2122 		__count_numa_event(page_zone(page), NUMA_INTERLEAVE_HIT);
2123 		preempt_enable();
2124 	}
2125 	return page;
2126 }
2127 
2128 static struct page *alloc_pages_preferred_many(gfp_t gfp, unsigned int order,
2129 						int nid, struct mempolicy *pol)
2130 {
2131 	struct page *page;
2132 	gfp_t preferred_gfp;
2133 
2134 	/*
2135 	 * This is a two pass approach. The first pass will only try the
2136 	 * preferred nodes but skip the direct reclaim and allow the
2137 	 * allocation to fail, while the second pass will try all the
2138 	 * nodes in system.
2139 	 */
2140 	preferred_gfp = gfp | __GFP_NOWARN;
2141 	preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2142 	page = __alloc_pages(preferred_gfp, order, nid, &pol->nodes);
2143 	if (!page)
2144 		page = __alloc_pages(gfp, order, nid, NULL);
2145 
2146 	return page;
2147 }
2148 
2149 /**
2150  * vma_alloc_folio - Allocate a folio for a VMA.
2151  * @gfp: GFP flags.
2152  * @order: Order of the folio.
2153  * @vma: Pointer to VMA or NULL if not available.
2154  * @addr: Virtual address of the allocation.  Must be inside @vma.
2155  * @hugepage: For hugepages try only the preferred node if possible.
2156  *
2157  * Allocate a folio for a specific address in @vma, using the appropriate
2158  * NUMA policy.  When @vma is not NULL the caller must hold the mmap_lock
2159  * of the mm_struct of the VMA to prevent it from going away.  Should be
2160  * used for all allocations for folios that will be mapped into user space.
2161  *
2162  * Return: The folio on success or NULL if allocation fails.
2163  */
2164 struct folio *vma_alloc_folio(gfp_t gfp, int order, struct vm_area_struct *vma,
2165 		unsigned long addr, bool hugepage)
2166 {
2167 	struct mempolicy *pol;
2168 	int node = numa_node_id();
2169 	struct folio *folio;
2170 	int preferred_nid;
2171 	nodemask_t *nmask;
2172 
2173 	pol = get_vma_policy(vma, addr);
2174 
2175 	if (pol->mode == MPOL_INTERLEAVE) {
2176 		struct page *page;
2177 		unsigned nid;
2178 
2179 		nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order);
2180 		mpol_cond_put(pol);
2181 		gfp |= __GFP_COMP;
2182 		page = alloc_page_interleave(gfp, order, nid);
2183 		return page_rmappable_folio(page);
2184 	}
2185 
2186 	if (pol->mode == MPOL_PREFERRED_MANY) {
2187 		struct page *page;
2188 
2189 		node = policy_node(gfp, pol, node);
2190 		gfp |= __GFP_COMP;
2191 		page = alloc_pages_preferred_many(gfp, order, node, pol);
2192 		mpol_cond_put(pol);
2193 		return page_rmappable_folio(page);
2194 	}
2195 
2196 	if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) {
2197 		int hpage_node = node;
2198 
2199 		/*
2200 		 * For hugepage allocation and non-interleave policy which
2201 		 * allows the current node (or other explicitly preferred
2202 		 * node) we only try to allocate from the current/preferred
2203 		 * node and don't fall back to other nodes, as the cost of
2204 		 * remote accesses would likely offset THP benefits.
2205 		 *
2206 		 * If the policy is interleave or does not allow the current
2207 		 * node in its nodemask, we allocate the standard way.
2208 		 */
2209 		if (pol->mode == MPOL_PREFERRED)
2210 			hpage_node = first_node(pol->nodes);
2211 
2212 		nmask = policy_nodemask(gfp, pol);
2213 		if (!nmask || node_isset(hpage_node, *nmask)) {
2214 			mpol_cond_put(pol);
2215 			/*
2216 			 * First, try to allocate THP only on local node, but
2217 			 * don't reclaim unnecessarily, just compact.
2218 			 */
2219 			folio = __folio_alloc_node(gfp | __GFP_THISNODE |
2220 					__GFP_NORETRY, order, hpage_node);
2221 
2222 			/*
2223 			 * If hugepage allocations are configured to always
2224 			 * synchronous compact or the vma has been madvised
2225 			 * to prefer hugepage backing, retry allowing remote
2226 			 * memory with both reclaim and compact as well.
2227 			 */
2228 			if (!folio && (gfp & __GFP_DIRECT_RECLAIM))
2229 				folio = __folio_alloc(gfp, order, hpage_node,
2230 						      nmask);
2231 
2232 			goto out;
2233 		}
2234 	}
2235 
2236 	nmask = policy_nodemask(gfp, pol);
2237 	preferred_nid = policy_node(gfp, pol, node);
2238 	folio = __folio_alloc(gfp, order, preferred_nid, nmask);
2239 	mpol_cond_put(pol);
2240 out:
2241 	return folio;
2242 }
2243 EXPORT_SYMBOL(vma_alloc_folio);
2244 
2245 /**
2246  * alloc_pages - Allocate pages.
2247  * @gfp: GFP flags.
2248  * @order: Power of two of number of pages to allocate.
2249  *
2250  * Allocate 1 << @order contiguous pages.  The physical address of the
2251  * first page is naturally aligned (eg an order-3 allocation will be aligned
2252  * to a multiple of 8 * PAGE_SIZE bytes).  The NUMA policy of the current
2253  * process is honoured when in process context.
2254  *
2255  * Context: Can be called from any context, providing the appropriate GFP
2256  * flags are used.
2257  * Return: The page on success or NULL if allocation fails.
2258  */
2259 struct page *alloc_pages(gfp_t gfp, unsigned order)
2260 {
2261 	struct mempolicy *pol = &default_policy;
2262 	struct page *page;
2263 
2264 	if (!in_interrupt() && !(gfp & __GFP_THISNODE))
2265 		pol = get_task_policy(current);
2266 
2267 	/*
2268 	 * No reference counting needed for current->mempolicy
2269 	 * nor system default_policy
2270 	 */
2271 	if (pol->mode == MPOL_INTERLEAVE)
2272 		page = alloc_page_interleave(gfp, order, interleave_nodes(pol));
2273 	else if (pol->mode == MPOL_PREFERRED_MANY)
2274 		page = alloc_pages_preferred_many(gfp, order,
2275 				  policy_node(gfp, pol, numa_node_id()), pol);
2276 	else
2277 		page = __alloc_pages(gfp, order,
2278 				policy_node(gfp, pol, numa_node_id()),
2279 				policy_nodemask(gfp, pol));
2280 
2281 	return page;
2282 }
2283 EXPORT_SYMBOL(alloc_pages);
2284 
2285 struct folio *folio_alloc(gfp_t gfp, unsigned order)
2286 {
2287 	return page_rmappable_folio(alloc_pages(gfp | __GFP_COMP, order));
2288 }
2289 EXPORT_SYMBOL(folio_alloc);
2290 
2291 static unsigned long alloc_pages_bulk_array_interleave(gfp_t gfp,
2292 		struct mempolicy *pol, unsigned long nr_pages,
2293 		struct page **page_array)
2294 {
2295 	int nodes;
2296 	unsigned long nr_pages_per_node;
2297 	int delta;
2298 	int i;
2299 	unsigned long nr_allocated;
2300 	unsigned long total_allocated = 0;
2301 
2302 	nodes = nodes_weight(pol->nodes);
2303 	nr_pages_per_node = nr_pages / nodes;
2304 	delta = nr_pages - nodes * nr_pages_per_node;
2305 
2306 	for (i = 0; i < nodes; i++) {
2307 		if (delta) {
2308 			nr_allocated = __alloc_pages_bulk(gfp,
2309 					interleave_nodes(pol), NULL,
2310 					nr_pages_per_node + 1, NULL,
2311 					page_array);
2312 			delta--;
2313 		} else {
2314 			nr_allocated = __alloc_pages_bulk(gfp,
2315 					interleave_nodes(pol), NULL,
2316 					nr_pages_per_node, NULL, page_array);
2317 		}
2318 
2319 		page_array += nr_allocated;
2320 		total_allocated += nr_allocated;
2321 	}
2322 
2323 	return total_allocated;
2324 }
2325 
2326 static unsigned long alloc_pages_bulk_array_preferred_many(gfp_t gfp, int nid,
2327 		struct mempolicy *pol, unsigned long nr_pages,
2328 		struct page **page_array)
2329 {
2330 	gfp_t preferred_gfp;
2331 	unsigned long nr_allocated = 0;
2332 
2333 	preferred_gfp = gfp | __GFP_NOWARN;
2334 	preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2335 
2336 	nr_allocated  = __alloc_pages_bulk(preferred_gfp, nid, &pol->nodes,
2337 					   nr_pages, NULL, page_array);
2338 
2339 	if (nr_allocated < nr_pages)
2340 		nr_allocated += __alloc_pages_bulk(gfp, numa_node_id(), NULL,
2341 				nr_pages - nr_allocated, NULL,
2342 				page_array + nr_allocated);
2343 	return nr_allocated;
2344 }
2345 
2346 /* alloc pages bulk and mempolicy should be considered at the
2347  * same time in some situation such as vmalloc.
2348  *
2349  * It can accelerate memory allocation especially interleaving
2350  * allocate memory.
2351  */
2352 unsigned long alloc_pages_bulk_array_mempolicy(gfp_t gfp,
2353 		unsigned long nr_pages, struct page **page_array)
2354 {
2355 	struct mempolicy *pol = &default_policy;
2356 
2357 	if (!in_interrupt() && !(gfp & __GFP_THISNODE))
2358 		pol = get_task_policy(current);
2359 
2360 	if (pol->mode == MPOL_INTERLEAVE)
2361 		return alloc_pages_bulk_array_interleave(gfp, pol,
2362 							 nr_pages, page_array);
2363 
2364 	if (pol->mode == MPOL_PREFERRED_MANY)
2365 		return alloc_pages_bulk_array_preferred_many(gfp,
2366 				numa_node_id(), pol, nr_pages, page_array);
2367 
2368 	return __alloc_pages_bulk(gfp, policy_node(gfp, pol, numa_node_id()),
2369 				  policy_nodemask(gfp, pol), nr_pages, NULL,
2370 				  page_array);
2371 }
2372 
2373 int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
2374 {
2375 	struct mempolicy *pol = mpol_dup(vma_policy(src));
2376 
2377 	if (IS_ERR(pol))
2378 		return PTR_ERR(pol);
2379 	dst->vm_policy = pol;
2380 	return 0;
2381 }
2382 
2383 /*
2384  * If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
2385  * rebinds the mempolicy its copying by calling mpol_rebind_policy()
2386  * with the mems_allowed returned by cpuset_mems_allowed().  This
2387  * keeps mempolicies cpuset relative after its cpuset moves.  See
2388  * further kernel/cpuset.c update_nodemask().
2389  *
2390  * current's mempolicy may be rebinded by the other task(the task that changes
2391  * cpuset's mems), so we needn't do rebind work for current task.
2392  */
2393 
2394 /* Slow path of a mempolicy duplicate */
2395 struct mempolicy *__mpol_dup(struct mempolicy *old)
2396 {
2397 	struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
2398 
2399 	if (!new)
2400 		return ERR_PTR(-ENOMEM);
2401 
2402 	/* task's mempolicy is protected by alloc_lock */
2403 	if (old == current->mempolicy) {
2404 		task_lock(current);
2405 		*new = *old;
2406 		task_unlock(current);
2407 	} else
2408 		*new = *old;
2409 
2410 	if (current_cpuset_is_being_rebound()) {
2411 		nodemask_t mems = cpuset_mems_allowed(current);
2412 		mpol_rebind_policy(new, &mems);
2413 	}
2414 	atomic_set(&new->refcnt, 1);
2415 	return new;
2416 }
2417 
2418 /* Slow path of a mempolicy comparison */
2419 bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
2420 {
2421 	if (!a || !b)
2422 		return false;
2423 	if (a->mode != b->mode)
2424 		return false;
2425 	if (a->flags != b->flags)
2426 		return false;
2427 	if (a->home_node != b->home_node)
2428 		return false;
2429 	if (mpol_store_user_nodemask(a))
2430 		if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
2431 			return false;
2432 
2433 	switch (a->mode) {
2434 	case MPOL_BIND:
2435 	case MPOL_INTERLEAVE:
2436 	case MPOL_PREFERRED:
2437 	case MPOL_PREFERRED_MANY:
2438 		return !!nodes_equal(a->nodes, b->nodes);
2439 	case MPOL_LOCAL:
2440 		return true;
2441 	default:
2442 		BUG();
2443 		return false;
2444 	}
2445 }
2446 
2447 /*
2448  * Shared memory backing store policy support.
2449  *
2450  * Remember policies even when nobody has shared memory mapped.
2451  * The policies are kept in Red-Black tree linked from the inode.
2452  * They are protected by the sp->lock rwlock, which should be held
2453  * for any accesses to the tree.
2454  */
2455 
2456 /*
2457  * lookup first element intersecting start-end.  Caller holds sp->lock for
2458  * reading or for writing
2459  */
2460 static struct sp_node *
2461 sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end)
2462 {
2463 	struct rb_node *n = sp->root.rb_node;
2464 
2465 	while (n) {
2466 		struct sp_node *p = rb_entry(n, struct sp_node, nd);
2467 
2468 		if (start >= p->end)
2469 			n = n->rb_right;
2470 		else if (end <= p->start)
2471 			n = n->rb_left;
2472 		else
2473 			break;
2474 	}
2475 	if (!n)
2476 		return NULL;
2477 	for (;;) {
2478 		struct sp_node *w = NULL;
2479 		struct rb_node *prev = rb_prev(n);
2480 		if (!prev)
2481 			break;
2482 		w = rb_entry(prev, struct sp_node, nd);
2483 		if (w->end <= start)
2484 			break;
2485 		n = prev;
2486 	}
2487 	return rb_entry(n, struct sp_node, nd);
2488 }
2489 
2490 /*
2491  * Insert a new shared policy into the list.  Caller holds sp->lock for
2492  * writing.
2493  */
2494 static void sp_insert(struct shared_policy *sp, struct sp_node *new)
2495 {
2496 	struct rb_node **p = &sp->root.rb_node;
2497 	struct rb_node *parent = NULL;
2498 	struct sp_node *nd;
2499 
2500 	while (*p) {
2501 		parent = *p;
2502 		nd = rb_entry(parent, struct sp_node, nd);
2503 		if (new->start < nd->start)
2504 			p = &(*p)->rb_left;
2505 		else if (new->end > nd->end)
2506 			p = &(*p)->rb_right;
2507 		else
2508 			BUG();
2509 	}
2510 	rb_link_node(&new->nd, parent, p);
2511 	rb_insert_color(&new->nd, &sp->root);
2512 	pr_debug("inserting %lx-%lx: %d\n", new->start, new->end,
2513 		 new->policy ? new->policy->mode : 0);
2514 }
2515 
2516 /* Find shared policy intersecting idx */
2517 struct mempolicy *
2518 mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx)
2519 {
2520 	struct mempolicy *pol = NULL;
2521 	struct sp_node *sn;
2522 
2523 	if (!sp->root.rb_node)
2524 		return NULL;
2525 	read_lock(&sp->lock);
2526 	sn = sp_lookup(sp, idx, idx+1);
2527 	if (sn) {
2528 		mpol_get(sn->policy);
2529 		pol = sn->policy;
2530 	}
2531 	read_unlock(&sp->lock);
2532 	return pol;
2533 }
2534 
2535 static void sp_free(struct sp_node *n)
2536 {
2537 	mpol_put(n->policy);
2538 	kmem_cache_free(sn_cache, n);
2539 }
2540 
2541 /**
2542  * mpol_misplaced - check whether current page node is valid in policy
2543  *
2544  * @page: page to be checked
2545  * @vma: vm area where page mapped
2546  * @addr: virtual address where page mapped
2547  *
2548  * Lookup current policy node id for vma,addr and "compare to" page's
2549  * node id.  Policy determination "mimics" alloc_page_vma().
2550  * Called from fault path where we know the vma and faulting address.
2551  *
2552  * Return: NUMA_NO_NODE if the page is in a node that is valid for this
2553  * policy, or a suitable node ID to allocate a replacement page from.
2554  */
2555 int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr)
2556 {
2557 	struct mempolicy *pol;
2558 	struct zoneref *z;
2559 	int curnid = page_to_nid(page);
2560 	unsigned long pgoff;
2561 	int thiscpu = raw_smp_processor_id();
2562 	int thisnid = cpu_to_node(thiscpu);
2563 	int polnid = NUMA_NO_NODE;
2564 	int ret = NUMA_NO_NODE;
2565 
2566 	pol = get_vma_policy(vma, addr);
2567 	if (!(pol->flags & MPOL_F_MOF))
2568 		goto out;
2569 
2570 	switch (pol->mode) {
2571 	case MPOL_INTERLEAVE:
2572 		pgoff = vma->vm_pgoff;
2573 		pgoff += (addr - vma->vm_start) >> PAGE_SHIFT;
2574 		polnid = offset_il_node(pol, pgoff);
2575 		break;
2576 
2577 	case MPOL_PREFERRED:
2578 		if (node_isset(curnid, pol->nodes))
2579 			goto out;
2580 		polnid = first_node(pol->nodes);
2581 		break;
2582 
2583 	case MPOL_LOCAL:
2584 		polnid = numa_node_id();
2585 		break;
2586 
2587 	case MPOL_BIND:
2588 		/* Optimize placement among multiple nodes via NUMA balancing */
2589 		if (pol->flags & MPOL_F_MORON) {
2590 			if (node_isset(thisnid, pol->nodes))
2591 				break;
2592 			goto out;
2593 		}
2594 		fallthrough;
2595 
2596 	case MPOL_PREFERRED_MANY:
2597 		/*
2598 		 * use current page if in policy nodemask,
2599 		 * else select nearest allowed node, if any.
2600 		 * If no allowed nodes, use current [!misplaced].
2601 		 */
2602 		if (node_isset(curnid, pol->nodes))
2603 			goto out;
2604 		z = first_zones_zonelist(
2605 				node_zonelist(numa_node_id(), GFP_HIGHUSER),
2606 				gfp_zone(GFP_HIGHUSER),
2607 				&pol->nodes);
2608 		polnid = zone_to_nid(z->zone);
2609 		break;
2610 
2611 	default:
2612 		BUG();
2613 	}
2614 
2615 	/* Migrate the page towards the node whose CPU is referencing it */
2616 	if (pol->flags & MPOL_F_MORON) {
2617 		polnid = thisnid;
2618 
2619 		if (!should_numa_migrate_memory(current, page, curnid, thiscpu))
2620 			goto out;
2621 	}
2622 
2623 	if (curnid != polnid)
2624 		ret = polnid;
2625 out:
2626 	mpol_cond_put(pol);
2627 
2628 	return ret;
2629 }
2630 
2631 /*
2632  * Drop the (possibly final) reference to task->mempolicy.  It needs to be
2633  * dropped after task->mempolicy is set to NULL so that any allocation done as
2634  * part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
2635  * policy.
2636  */
2637 void mpol_put_task_policy(struct task_struct *task)
2638 {
2639 	struct mempolicy *pol;
2640 
2641 	task_lock(task);
2642 	pol = task->mempolicy;
2643 	task->mempolicy = NULL;
2644 	task_unlock(task);
2645 	mpol_put(pol);
2646 }
2647 
2648 static void sp_delete(struct shared_policy *sp, struct sp_node *n)
2649 {
2650 	pr_debug("deleting %lx-l%lx\n", n->start, n->end);
2651 	rb_erase(&n->nd, &sp->root);
2652 	sp_free(n);
2653 }
2654 
2655 static void sp_node_init(struct sp_node *node, unsigned long start,
2656 			unsigned long end, struct mempolicy *pol)
2657 {
2658 	node->start = start;
2659 	node->end = end;
2660 	node->policy = pol;
2661 }
2662 
2663 static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
2664 				struct mempolicy *pol)
2665 {
2666 	struct sp_node *n;
2667 	struct mempolicy *newpol;
2668 
2669 	n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
2670 	if (!n)
2671 		return NULL;
2672 
2673 	newpol = mpol_dup(pol);
2674 	if (IS_ERR(newpol)) {
2675 		kmem_cache_free(sn_cache, n);
2676 		return NULL;
2677 	}
2678 	newpol->flags |= MPOL_F_SHARED;
2679 	sp_node_init(n, start, end, newpol);
2680 
2681 	return n;
2682 }
2683 
2684 /* Replace a policy range. */
2685 static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
2686 				 unsigned long end, struct sp_node *new)
2687 {
2688 	struct sp_node *n;
2689 	struct sp_node *n_new = NULL;
2690 	struct mempolicy *mpol_new = NULL;
2691 	int ret = 0;
2692 
2693 restart:
2694 	write_lock(&sp->lock);
2695 	n = sp_lookup(sp, start, end);
2696 	/* Take care of old policies in the same range. */
2697 	while (n && n->start < end) {
2698 		struct rb_node *next = rb_next(&n->nd);
2699 		if (n->start >= start) {
2700 			if (n->end <= end)
2701 				sp_delete(sp, n);
2702 			else
2703 				n->start = end;
2704 		} else {
2705 			/* Old policy spanning whole new range. */
2706 			if (n->end > end) {
2707 				if (!n_new)
2708 					goto alloc_new;
2709 
2710 				*mpol_new = *n->policy;
2711 				atomic_set(&mpol_new->refcnt, 1);
2712 				sp_node_init(n_new, end, n->end, mpol_new);
2713 				n->end = start;
2714 				sp_insert(sp, n_new);
2715 				n_new = NULL;
2716 				mpol_new = NULL;
2717 				break;
2718 			} else
2719 				n->end = start;
2720 		}
2721 		if (!next)
2722 			break;
2723 		n = rb_entry(next, struct sp_node, nd);
2724 	}
2725 	if (new)
2726 		sp_insert(sp, new);
2727 	write_unlock(&sp->lock);
2728 	ret = 0;
2729 
2730 err_out:
2731 	if (mpol_new)
2732 		mpol_put(mpol_new);
2733 	if (n_new)
2734 		kmem_cache_free(sn_cache, n_new);
2735 
2736 	return ret;
2737 
2738 alloc_new:
2739 	write_unlock(&sp->lock);
2740 	ret = -ENOMEM;
2741 	n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
2742 	if (!n_new)
2743 		goto err_out;
2744 	mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
2745 	if (!mpol_new)
2746 		goto err_out;
2747 	atomic_set(&mpol_new->refcnt, 1);
2748 	goto restart;
2749 }
2750 
2751 /**
2752  * mpol_shared_policy_init - initialize shared policy for inode
2753  * @sp: pointer to inode shared policy
2754  * @mpol:  struct mempolicy to install
2755  *
2756  * Install non-NULL @mpol in inode's shared policy rb-tree.
2757  * On entry, the current task has a reference on a non-NULL @mpol.
2758  * This must be released on exit.
2759  * This is called at get_inode() calls and we can use GFP_KERNEL.
2760  */
2761 void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
2762 {
2763 	int ret;
2764 
2765 	sp->root = RB_ROOT;		/* empty tree == default mempolicy */
2766 	rwlock_init(&sp->lock);
2767 
2768 	if (mpol) {
2769 		struct vm_area_struct pvma;
2770 		struct mempolicy *new;
2771 		NODEMASK_SCRATCH(scratch);
2772 
2773 		if (!scratch)
2774 			goto put_mpol;
2775 		/* contextualize the tmpfs mount point mempolicy */
2776 		new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
2777 		if (IS_ERR(new))
2778 			goto free_scratch; /* no valid nodemask intersection */
2779 
2780 		task_lock(current);
2781 		ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch);
2782 		task_unlock(current);
2783 		if (ret)
2784 			goto put_new;
2785 
2786 		/* Create pseudo-vma that contains just the policy */
2787 		vma_init(&pvma, NULL);
2788 		pvma.vm_end = TASK_SIZE;	/* policy covers entire file */
2789 		mpol_set_shared_policy(sp, &pvma, new); /* adds ref */
2790 
2791 put_new:
2792 		mpol_put(new);			/* drop initial ref */
2793 free_scratch:
2794 		NODEMASK_SCRATCH_FREE(scratch);
2795 put_mpol:
2796 		mpol_put(mpol);	/* drop our incoming ref on sb mpol */
2797 	}
2798 }
2799 
2800 int mpol_set_shared_policy(struct shared_policy *info,
2801 			struct vm_area_struct *vma, struct mempolicy *npol)
2802 {
2803 	int err;
2804 	struct sp_node *new = NULL;
2805 	unsigned long sz = vma_pages(vma);
2806 
2807 	pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n",
2808 		 vma->vm_pgoff,
2809 		 sz, npol ? npol->mode : -1,
2810 		 npol ? npol->flags : -1,
2811 		 npol ? nodes_addr(npol->nodes)[0] : NUMA_NO_NODE);
2812 
2813 	if (npol) {
2814 		new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol);
2815 		if (!new)
2816 			return -ENOMEM;
2817 	}
2818 	err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new);
2819 	if (err && new)
2820 		sp_free(new);
2821 	return err;
2822 }
2823 
2824 /* Free a backing policy store on inode delete. */
2825 void mpol_free_shared_policy(struct shared_policy *p)
2826 {
2827 	struct sp_node *n;
2828 	struct rb_node *next;
2829 
2830 	if (!p->root.rb_node)
2831 		return;
2832 	write_lock(&p->lock);
2833 	next = rb_first(&p->root);
2834 	while (next) {
2835 		n = rb_entry(next, struct sp_node, nd);
2836 		next = rb_next(&n->nd);
2837 		sp_delete(p, n);
2838 	}
2839 	write_unlock(&p->lock);
2840 }
2841 
2842 #ifdef CONFIG_NUMA_BALANCING
2843 static int __initdata numabalancing_override;
2844 
2845 static void __init check_numabalancing_enable(void)
2846 {
2847 	bool numabalancing_default = false;
2848 
2849 	if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
2850 		numabalancing_default = true;
2851 
2852 	/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
2853 	if (numabalancing_override)
2854 		set_numabalancing_state(numabalancing_override == 1);
2855 
2856 	if (num_online_nodes() > 1 && !numabalancing_override) {
2857 		pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
2858 			numabalancing_default ? "Enabling" : "Disabling");
2859 		set_numabalancing_state(numabalancing_default);
2860 	}
2861 }
2862 
2863 static int __init setup_numabalancing(char *str)
2864 {
2865 	int ret = 0;
2866 	if (!str)
2867 		goto out;
2868 
2869 	if (!strcmp(str, "enable")) {
2870 		numabalancing_override = 1;
2871 		ret = 1;
2872 	} else if (!strcmp(str, "disable")) {
2873 		numabalancing_override = -1;
2874 		ret = 1;
2875 	}
2876 out:
2877 	if (!ret)
2878 		pr_warn("Unable to parse numa_balancing=\n");
2879 
2880 	return ret;
2881 }
2882 __setup("numa_balancing=", setup_numabalancing);
2883 #else
2884 static inline void __init check_numabalancing_enable(void)
2885 {
2886 }
2887 #endif /* CONFIG_NUMA_BALANCING */
2888 
2889 /* assumes fs == KERNEL_DS */
2890 void __init numa_policy_init(void)
2891 {
2892 	nodemask_t interleave_nodes;
2893 	unsigned long largest = 0;
2894 	int nid, prefer = 0;
2895 
2896 	policy_cache = kmem_cache_create("numa_policy",
2897 					 sizeof(struct mempolicy),
2898 					 0, SLAB_PANIC, NULL);
2899 
2900 	sn_cache = kmem_cache_create("shared_policy_node",
2901 				     sizeof(struct sp_node),
2902 				     0, SLAB_PANIC, NULL);
2903 
2904 	for_each_node(nid) {
2905 		preferred_node_policy[nid] = (struct mempolicy) {
2906 			.refcnt = ATOMIC_INIT(1),
2907 			.mode = MPOL_PREFERRED,
2908 			.flags = MPOL_F_MOF | MPOL_F_MORON,
2909 			.nodes = nodemask_of_node(nid),
2910 		};
2911 	}
2912 
2913 	/*
2914 	 * Set interleaving policy for system init. Interleaving is only
2915 	 * enabled across suitably sized nodes (default is >= 16MB), or
2916 	 * fall back to the largest node if they're all smaller.
2917 	 */
2918 	nodes_clear(interleave_nodes);
2919 	for_each_node_state(nid, N_MEMORY) {
2920 		unsigned long total_pages = node_present_pages(nid);
2921 
2922 		/* Preserve the largest node */
2923 		if (largest < total_pages) {
2924 			largest = total_pages;
2925 			prefer = nid;
2926 		}
2927 
2928 		/* Interleave this node? */
2929 		if ((total_pages << PAGE_SHIFT) >= (16 << 20))
2930 			node_set(nid, interleave_nodes);
2931 	}
2932 
2933 	/* All too small, use the largest */
2934 	if (unlikely(nodes_empty(interleave_nodes)))
2935 		node_set(prefer, interleave_nodes);
2936 
2937 	if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
2938 		pr_err("%s: interleaving failed\n", __func__);
2939 
2940 	check_numabalancing_enable();
2941 }
2942 
2943 /* Reset policy of current process to default */
2944 void numa_default_policy(void)
2945 {
2946 	do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
2947 }
2948 
2949 /*
2950  * Parse and format mempolicy from/to strings
2951  */
2952 
2953 static const char * const policy_modes[] =
2954 {
2955 	[MPOL_DEFAULT]    = "default",
2956 	[MPOL_PREFERRED]  = "prefer",
2957 	[MPOL_BIND]       = "bind",
2958 	[MPOL_INTERLEAVE] = "interleave",
2959 	[MPOL_LOCAL]      = "local",
2960 	[MPOL_PREFERRED_MANY]  = "prefer (many)",
2961 };
2962 
2963 
2964 #ifdef CONFIG_TMPFS
2965 /**
2966  * mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
2967  * @str:  string containing mempolicy to parse
2968  * @mpol:  pointer to struct mempolicy pointer, returned on success.
2969  *
2970  * Format of input:
2971  *	<mode>[=<flags>][:<nodelist>]
2972  *
2973  * Return: %0 on success, else %1
2974  */
2975 int mpol_parse_str(char *str, struct mempolicy **mpol)
2976 {
2977 	struct mempolicy *new = NULL;
2978 	unsigned short mode_flags;
2979 	nodemask_t nodes;
2980 	char *nodelist = strchr(str, ':');
2981 	char *flags = strchr(str, '=');
2982 	int err = 1, mode;
2983 
2984 	if (flags)
2985 		*flags++ = '\0';	/* terminate mode string */
2986 
2987 	if (nodelist) {
2988 		/* NUL-terminate mode or flags string */
2989 		*nodelist++ = '\0';
2990 		if (nodelist_parse(nodelist, nodes))
2991 			goto out;
2992 		if (!nodes_subset(nodes, node_states[N_MEMORY]))
2993 			goto out;
2994 	} else
2995 		nodes_clear(nodes);
2996 
2997 	mode = match_string(policy_modes, MPOL_MAX, str);
2998 	if (mode < 0)
2999 		goto out;
3000 
3001 	switch (mode) {
3002 	case MPOL_PREFERRED:
3003 		/*
3004 		 * Insist on a nodelist of one node only, although later
3005 		 * we use first_node(nodes) to grab a single node, so here
3006 		 * nodelist (or nodes) cannot be empty.
3007 		 */
3008 		if (nodelist) {
3009 			char *rest = nodelist;
3010 			while (isdigit(*rest))
3011 				rest++;
3012 			if (*rest)
3013 				goto out;
3014 			if (nodes_empty(nodes))
3015 				goto out;
3016 		}
3017 		break;
3018 	case MPOL_INTERLEAVE:
3019 		/*
3020 		 * Default to online nodes with memory if no nodelist
3021 		 */
3022 		if (!nodelist)
3023 			nodes = node_states[N_MEMORY];
3024 		break;
3025 	case MPOL_LOCAL:
3026 		/*
3027 		 * Don't allow a nodelist;  mpol_new() checks flags
3028 		 */
3029 		if (nodelist)
3030 			goto out;
3031 		break;
3032 	case MPOL_DEFAULT:
3033 		/*
3034 		 * Insist on a empty nodelist
3035 		 */
3036 		if (!nodelist)
3037 			err = 0;
3038 		goto out;
3039 	case MPOL_PREFERRED_MANY:
3040 	case MPOL_BIND:
3041 		/*
3042 		 * Insist on a nodelist
3043 		 */
3044 		if (!nodelist)
3045 			goto out;
3046 	}
3047 
3048 	mode_flags = 0;
3049 	if (flags) {
3050 		/*
3051 		 * Currently, we only support two mutually exclusive
3052 		 * mode flags.
3053 		 */
3054 		if (!strcmp(flags, "static"))
3055 			mode_flags |= MPOL_F_STATIC_NODES;
3056 		else if (!strcmp(flags, "relative"))
3057 			mode_flags |= MPOL_F_RELATIVE_NODES;
3058 		else
3059 			goto out;
3060 	}
3061 
3062 	new = mpol_new(mode, mode_flags, &nodes);
3063 	if (IS_ERR(new))
3064 		goto out;
3065 
3066 	/*
3067 	 * Save nodes for mpol_to_str() to show the tmpfs mount options
3068 	 * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
3069 	 */
3070 	if (mode != MPOL_PREFERRED) {
3071 		new->nodes = nodes;
3072 	} else if (nodelist) {
3073 		nodes_clear(new->nodes);
3074 		node_set(first_node(nodes), new->nodes);
3075 	} else {
3076 		new->mode = MPOL_LOCAL;
3077 	}
3078 
3079 	/*
3080 	 * Save nodes for contextualization: this will be used to "clone"
3081 	 * the mempolicy in a specific context [cpuset] at a later time.
3082 	 */
3083 	new->w.user_nodemask = nodes;
3084 
3085 	err = 0;
3086 
3087 out:
3088 	/* Restore string for error message */
3089 	if (nodelist)
3090 		*--nodelist = ':';
3091 	if (flags)
3092 		*--flags = '=';
3093 	if (!err)
3094 		*mpol = new;
3095 	return err;
3096 }
3097 #endif /* CONFIG_TMPFS */
3098 
3099 /**
3100  * mpol_to_str - format a mempolicy structure for printing
3101  * @buffer:  to contain formatted mempolicy string
3102  * @maxlen:  length of @buffer
3103  * @pol:  pointer to mempolicy to be formatted
3104  *
3105  * Convert @pol into a string.  If @buffer is too short, truncate the string.
3106  * Recommend a @maxlen of at least 51 for the longest mode, "weighted
3107  * interleave", plus the longest flag flags, "relative|balancing", and to
3108  * display at least a few node ids.
3109  */
3110 void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
3111 {
3112 	char *p = buffer;
3113 	nodemask_t nodes = NODE_MASK_NONE;
3114 	unsigned short mode = MPOL_DEFAULT;
3115 	unsigned short flags = 0;
3116 
3117 	if (pol &&
3118 	    pol != &default_policy &&
3119 	    !(pol >= &preferred_node_policy[0] &&
3120 	      pol <= &preferred_node_policy[ARRAY_SIZE(preferred_node_policy) - 1])) {
3121 		mode = pol->mode;
3122 		flags = pol->flags;
3123 	}
3124 
3125 	switch (mode) {
3126 	case MPOL_DEFAULT:
3127 	case MPOL_LOCAL:
3128 		break;
3129 	case MPOL_PREFERRED:
3130 	case MPOL_PREFERRED_MANY:
3131 	case MPOL_BIND:
3132 	case MPOL_INTERLEAVE:
3133 		nodes = pol->nodes;
3134 		break;
3135 	default:
3136 		WARN_ON_ONCE(1);
3137 		snprintf(p, maxlen, "unknown");
3138 		return;
3139 	}
3140 
3141 	p += snprintf(p, maxlen, "%s", policy_modes[mode]);
3142 
3143 	if (flags & MPOL_MODE_FLAGS) {
3144 		p += snprintf(p, buffer + maxlen - p, "=");
3145 
3146 		/*
3147 		 * Static and relative are mutually exclusive.
3148 		 */
3149 		if (flags & MPOL_F_STATIC_NODES)
3150 			p += snprintf(p, buffer + maxlen - p, "static");
3151 		else if (flags & MPOL_F_RELATIVE_NODES)
3152 			p += snprintf(p, buffer + maxlen - p, "relative");
3153 
3154 		if (flags & MPOL_F_NUMA_BALANCING) {
3155 			if (!is_power_of_2(flags & MPOL_MODE_FLAGS))
3156 				p += snprintf(p, buffer + maxlen - p, "|");
3157 			p += snprintf(p, buffer + maxlen - p, "balancing");
3158 		}
3159 	}
3160 
3161 	if (!nodes_empty(nodes))
3162 		p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
3163 			       nodemask_pr_args(&nodes));
3164 }
3165