xref: /linux/mm/mempolicy.c (revision d866d5bafc5e1417032255002e95f8ec3121754b)
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 six 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  * weighted interleave
23  *                Allocate memory interleaved over a set of nodes based on
24  *                a set of weights (per-node), with normal fallback if it
25  *                fails.  Otherwise operates the same as interleave.
26  *                Example: nodeset(0,1) & weights (2,1) - 2 pages allocated
27  *                on node 0 for every 1 page allocated on node 1.
28  *
29  * bind           Only allocate memory on a specific set of nodes,
30  *                no fallback.
31  *                FIXME: memory is allocated starting with the first node
32  *                to the last. It would be better if bind would truly restrict
33  *                the allocation to memory nodes instead
34  *
35  * preferred      Try a specific node first before normal fallback.
36  *                As a special case NUMA_NO_NODE here means do the allocation
37  *                on the local CPU. This is normally identical to default,
38  *                but useful to set in a VMA when you have a non default
39  *                process policy.
40  *
41  * preferred many Try a set of nodes first before normal fallback. This is
42  *                similar to preferred without the special case.
43  *
44  * default        Allocate on the local node first, or when on a VMA
45  *                use the process policy. This is what Linux always did
46  *		  in a NUMA aware kernel and still does by, ahem, default.
47  *
48  * The process policy is applied for most non interrupt memory allocations
49  * in that process' context. Interrupts ignore the policies and always
50  * try to allocate on the local CPU. The VMA policy is only applied for memory
51  * allocations for a VMA in the VM.
52  *
53  * Currently there are a few corner cases in swapping where the policy
54  * is not applied, but the majority should be handled. When process policy
55  * is used it is not remembered over swap outs/swap ins.
56  *
57  * Only the highest zone in the zone hierarchy gets policied. Allocations
58  * requesting a lower zone just use default policy. This implies that
59  * on systems with highmem kernel lowmem allocation don't get policied.
60  * Same with GFP_DMA allocations.
61  *
62  * For shmem/tmpfs shared memory the policy is shared between
63  * all users and remembered even when nobody has memory mapped.
64  */
65 
66 /* Notebook:
67    fix mmap readahead to honour policy and enable policy for any page cache
68    object
69    statistics for bigpages
70    global policy for page cache? currently it uses process policy. Requires
71    first item above.
72    handle mremap for shared memory (currently ignored for the policy)
73    grows down?
74    make bind policy root only? It can trigger oom much faster and the
75    kernel is not always grateful with that.
76 */
77 
78 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
79 
80 #include <linux/mempolicy.h>
81 #include <linux/pagewalk.h>
82 #include <linux/highmem.h>
83 #include <linux/hugetlb.h>
84 #include <linux/kernel.h>
85 #include <linux/sched.h>
86 #include <linux/sched/mm.h>
87 #include <linux/sched/numa_balancing.h>
88 #include <linux/sched/sysctl.h>
89 #include <linux/sched/task.h>
90 #include <linux/nodemask.h>
91 #include <linux/cpuset.h>
92 #include <linux/slab.h>
93 #include <linux/string.h>
94 #include <linux/export.h>
95 #include <linux/nsproxy.h>
96 #include <linux/interrupt.h>
97 #include <linux/init.h>
98 #include <linux/compat.h>
99 #include <linux/ptrace.h>
100 #include <linux/swap.h>
101 #include <linux/seq_file.h>
102 #include <linux/proc_fs.h>
103 #include <linux/memory-tiers.h>
104 #include <linux/migrate.h>
105 #include <linux/ksm.h>
106 #include <linux/rmap.h>
107 #include <linux/security.h>
108 #include <linux/syscalls.h>
109 #include <linux/ctype.h>
110 #include <linux/mm_inline.h>
111 #include <linux/mmu_notifier.h>
112 #include <linux/printk.h>
113 #include <linux/leafops.h>
114 #include <linux/gcd.h>
115 #include <linux/srcu.h>
116 
117 #include <asm/tlbflush.h>
118 #include <asm/tlb.h>
119 #include <linux/uaccess.h>
120 #include <linux/memory.h>
121 
122 #include "internal.h"
123 #include "page_alloc.h"
124 
125 /* Internal flags */
126 #define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0)	/* Skip checks for continuous vmas */
127 #define MPOL_MF_INVERT       (MPOL_MF_INTERNAL << 1)	/* Invert check for nodemask */
128 #define MPOL_MF_WRLOCK       (MPOL_MF_INTERNAL << 2)	/* Write-lock walked vmas */
129 
130 static struct kmem_cache *policy_cache;
131 static struct kmem_cache *sn_cache;
132 
133 /* Highest zone. An specific allocation for a zone below that is not
134    policied. */
135 enum zone_type policy_zone = 0;
136 
137 /*
138  * run-time system-wide default policy => local allocation
139  */
140 static struct mempolicy default_policy = {
141 	.refcnt = ATOMIC_INIT(1), /* never free it */
142 	.mode = MPOL_LOCAL,
143 };
144 
145 static struct mempolicy preferred_node_policy[MAX_NUMNODES];
146 
147 /*
148  * weightiness balances the tradeoff between small weights (cycles through nodes
149  * faster, more fair/even distribution) and large weights (smaller errors
150  * between actual bandwidth ratios and weight ratios). 32 is a number that has
151  * been found to perform at a reasonable compromise between the two goals.
152  */
153 static const int weightiness = 32;
154 
155 /*
156  * A null weighted_interleave_state is interpreted as having .mode="auto",
157  * and .iw_table is interpreted as an array of 1s with length nr_node_ids.
158  */
159 struct weighted_interleave_state {
160 	bool mode_auto;
161 	struct rcu_head rcu;
162 	u8 iw_table[];
163 };
164 static struct weighted_interleave_state __rcu *wi_state;
165 static unsigned int *node_bw_table;
166 
167 /*
168  * wi_state_lock protects both wi_state and node_bw_table.
169  * node_bw_table is only used by writers to update wi_state.
170  */
171 static DEFINE_MUTEX(wi_state_lock);
172 
173 /* Readers that sleep while walking iw_table hold this instead */
174 DEFINE_STATIC_SRCU_FAST(wi_srcu);
175 
176 static void wi_state_free_rcu(struct rcu_head *head)
177 {
178 	struct weighted_interleave_state *state =
179 		container_of(head, struct weighted_interleave_state, rcu);
180 
181 	kfree_rcu(state, rcu);
182 }
183 
184 /* Retire through both flavors: sleeping readers use SRCU, the rest RCU */
185 static void wi_state_retire(struct weighted_interleave_state *state)
186 {
187 	if (state)
188 		call_srcu(&wi_srcu, &state->rcu, wi_state_free_rcu);
189 }
190 
191 static u8 get_il_weight(int node)
192 {
193 	struct weighted_interleave_state *state;
194 	u8 weight = 1;
195 
196 	rcu_read_lock();
197 	state = rcu_dereference(wi_state);
198 	if (state)
199 		weight = state->iw_table[node];
200 	rcu_read_unlock();
201 	return weight;
202 }
203 
204 /*
205  * Convert bandwidth values into weighted interleave weights.
206  * Call with wi_state_lock.
207  */
208 static void reduce_interleave_weights(unsigned int *bw, u8 *new_iw)
209 {
210 	nodemask_t nodes = NODE_MASK_NONE;
211 	u64 sum_bw = 0;
212 	unsigned int cast_sum_bw, scaling_factor = 1, iw_gcd = 0;
213 	int nid;
214 
215 	/*
216 	 * N_MEMORY can change while wi_state_lock is held. Remember the
217 	 * nodes contributing to sum_bw so all passes use the same set.
218 	 */
219 	for_each_node_state(nid, N_MEMORY) {
220 		node_set(nid, nodes);
221 		sum_bw += bw[nid];
222 	}
223 
224 	/* Scale bandwidths to whole numbers in the range [1, weightiness] */
225 	for_each_node_mask(nid, nodes) {
226 		/*
227 		 * Try not to perform 64-bit division.
228 		 * If sum_bw < scaling_factor, then sum_bw < U32_MAX.
229 		 * If sum_bw > scaling_factor, then round the weight up to 1.
230 		 */
231 		scaling_factor = weightiness * bw[nid];
232 		if (bw[nid] && sum_bw < scaling_factor) {
233 			cast_sum_bw = (unsigned int)sum_bw;
234 			new_iw[nid] = scaling_factor / cast_sum_bw;
235 		} else {
236 			new_iw[nid] = 1;
237 		}
238 		if (!iw_gcd)
239 			iw_gcd = new_iw[nid];
240 		iw_gcd = gcd(iw_gcd, new_iw[nid]);
241 	}
242 
243 	/* 1:2 is strictly better than 16:32. Reduce by the weights' GCD. */
244 	for_each_node_mask(nid, nodes)
245 		new_iw[nid] /= iw_gcd;
246 }
247 
248 int mempolicy_set_node_perf(unsigned int node, struct access_coordinate *coords)
249 {
250 	struct weighted_interleave_state *new_wi_state, *old_wi_state = NULL;
251 	unsigned int *old_bw, *new_bw;
252 	unsigned int bw_val;
253 	int i;
254 
255 	bw_val = min(coords->read_bandwidth, coords->write_bandwidth);
256 	new_bw = kzalloc_objs(unsigned int, nr_node_ids);
257 	if (!new_bw)
258 		return -ENOMEM;
259 
260 	new_wi_state = kmalloc_flex(*new_wi_state, iw_table, nr_node_ids);
261 	if (!new_wi_state) {
262 		kfree(new_bw);
263 		return -ENOMEM;
264 	}
265 	new_wi_state->mode_auto = true;
266 	for (i = 0; i < nr_node_ids; i++)
267 		new_wi_state->iw_table[i] = 1;
268 
269 	/*
270 	 * Update bandwidth info, even in manual mode. That way, when switching
271 	 * to auto mode in the future, iw_table can be overwritten using
272 	 * accurate bw data.
273 	 */
274 	mutex_lock(&wi_state_lock);
275 
276 	old_bw = node_bw_table;
277 	if (old_bw)
278 		memcpy(new_bw, old_bw, nr_node_ids * sizeof(*old_bw));
279 	new_bw[node] = bw_val;
280 	node_bw_table = new_bw;
281 
282 	old_wi_state = rcu_dereference_protected(wi_state,
283 					lockdep_is_held(&wi_state_lock));
284 	if (old_wi_state && !old_wi_state->mode_auto) {
285 		/* Manual mode; skip reducing weights and updating wi_state */
286 		mutex_unlock(&wi_state_lock);
287 		kfree(new_wi_state);
288 		goto out;
289 	}
290 
291 	/* NULL wi_state assumes auto=true; reduce weights and update wi_state*/
292 	reduce_interleave_weights(new_bw, new_wi_state->iw_table);
293 	rcu_assign_pointer(wi_state, new_wi_state);
294 
295 	mutex_unlock(&wi_state_lock);
296 	wi_state_retire(old_wi_state);
297 out:
298 	kfree(old_bw);
299 	return 0;
300 }
301 
302 /**
303  * numa_nearest_node - Find nearest node by state
304  * @node: Node id to start the search
305  * @state: State to filter the search
306  *
307  * Lookup the closest node by distance if @nid is not in state.
308  *
309  * Return: this @node if it is in state, otherwise the closest node by distance
310  */
311 int numa_nearest_node(int node, unsigned int state)
312 {
313 	int min_dist = INT_MAX, dist, n, min_node;
314 
315 	if (state >= NR_NODE_STATES)
316 		return -EINVAL;
317 
318 	if (node == NUMA_NO_NODE || node_state(node, state))
319 		return node;
320 
321 	min_node = node;
322 	for_each_node_state(n, state) {
323 		dist = node_distance(node, n);
324 		if (dist < min_dist) {
325 			min_dist = dist;
326 			min_node = n;
327 		}
328 	}
329 
330 	return min_node;
331 }
332 EXPORT_SYMBOL_GPL(numa_nearest_node);
333 
334 /**
335  * nearest_node_nodemask - Find the node in @mask at the nearest distance
336  *			   from @node.
337  *
338  * @node: a valid node ID to start the search from.
339  * @mask: a pointer to a nodemask representing the allowed nodes.
340  *
341  * This function iterates over all nodes in @mask and calculates the
342  * distance from the starting @node, then it returns the node ID that is
343  * the closest to @node, or MAX_NUMNODES if no node is found.
344  *
345  * Note that @node must be a valid node ID usable with node_distance(),
346  * providing an invalid node ID (e.g., NUMA_NO_NODE) may result in crashes
347  * or unexpected behavior.
348  */
349 int nearest_node_nodemask(int node, nodemask_t *mask)
350 {
351 	int dist, n, min_dist = INT_MAX, min_node = MAX_NUMNODES;
352 
353 	for_each_node_mask(n, *mask) {
354 		dist = node_distance(node, n);
355 		if (dist < min_dist) {
356 			min_dist = dist;
357 			min_node = n;
358 		}
359 	}
360 
361 	return min_node;
362 }
363 EXPORT_SYMBOL_GPL(nearest_node_nodemask);
364 
365 struct mempolicy *get_task_policy(struct task_struct *p)
366 {
367 	struct mempolicy *pol = p->mempolicy;
368 	int node;
369 
370 	if (pol)
371 		return pol;
372 
373 	node = numa_node_id();
374 	if (node != NUMA_NO_NODE) {
375 		pol = &preferred_node_policy[node];
376 		/* preferred_node_policy is not initialised early in boot */
377 		if (pol->mode)
378 			return pol;
379 	}
380 
381 	return &default_policy;
382 }
383 EXPORT_SYMBOL_FOR_MODULES(get_task_policy, "kvm");
384 
385 static const struct mempolicy_operations {
386 	int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
387 	void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
388 } mpol_ops[MPOL_MAX];
389 
390 static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
391 {
392 	return pol->flags & MPOL_USER_NODEMASK_FLAGS;
393 }
394 
395 static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
396 				   const nodemask_t *rel)
397 {
398 	nodemask_t tmp;
399 	nodes_fold(tmp, *orig, nodes_weight(*rel));
400 	nodes_onto(*ret, tmp, *rel);
401 }
402 
403 static int mpol_new_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
404 {
405 	if (nodes_empty(*nodes))
406 		return -EINVAL;
407 	pol->nodes = *nodes;
408 	return 0;
409 }
410 
411 static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
412 {
413 	if (nodes_empty(*nodes))
414 		return -EINVAL;
415 
416 	nodes_clear(pol->nodes);
417 	node_set(first_node(*nodes), pol->nodes);
418 	return 0;
419 }
420 
421 /*
422  * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
423  * any, for the new policy.  mpol_new() has already validated the nodes
424  * parameter with respect to the policy mode and flags.
425  *
426  * Must be called holding task's alloc_lock to protect task's mems_allowed
427  * and mempolicy.  May also be called holding the mmap_lock for write.
428  */
429 static int mpol_set_nodemask(struct mempolicy *pol,
430 		     const nodemask_t *nodes, struct nodemask_scratch *nsc)
431 {
432 	int ret;
433 
434 	/*
435 	 * Default (pol==NULL) resp. local memory policies are not a
436 	 * subject of any remapping. They also do not need any special
437 	 * constructor.
438 	 */
439 	if (!pol || pol->mode == MPOL_LOCAL)
440 		return 0;
441 
442 	/* Check N_MEMORY */
443 	nodes_and(nsc->mask1,
444 		  cpuset_current_mems_allowed, node_states[N_MEMORY]);
445 
446 	VM_BUG_ON(!nodes);
447 
448 	if (pol->flags & MPOL_F_RELATIVE_NODES)
449 		mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
450 	else
451 		nodes_and(nsc->mask2, *nodes, nsc->mask1);
452 
453 	if (mpol_store_user_nodemask(pol))
454 		pol->w.user_nodemask = *nodes;
455 	else
456 		pol->w.cpuset_mems_allowed = cpuset_current_mems_allowed;
457 
458 	ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
459 	return ret;
460 }
461 
462 /*
463  * This function just creates a new policy, does some check and simple
464  * initialization. You must invoke mpol_set_nodemask() to set nodes.
465  */
466 static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
467 				  nodemask_t *nodes)
468 {
469 	struct mempolicy *policy;
470 
471 	if (mode == MPOL_DEFAULT) {
472 		if (nodes && !nodes_empty(*nodes))
473 			return ERR_PTR(-EINVAL);
474 		return NULL;
475 	}
476 	VM_BUG_ON(!nodes);
477 
478 	/*
479 	 * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
480 	 * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
481 	 * All other modes require a valid pointer to a non-empty nodemask.
482 	 */
483 	if (mode == MPOL_PREFERRED) {
484 		if (nodes_empty(*nodes)) {
485 			if (((flags & MPOL_F_STATIC_NODES) ||
486 			     (flags & MPOL_F_RELATIVE_NODES)))
487 				return ERR_PTR(-EINVAL);
488 
489 			mode = MPOL_LOCAL;
490 		}
491 	} else if (mode == MPOL_LOCAL) {
492 		if (!nodes_empty(*nodes) ||
493 		    (flags & MPOL_F_STATIC_NODES) ||
494 		    (flags & MPOL_F_RELATIVE_NODES))
495 			return ERR_PTR(-EINVAL);
496 	} else if (nodes_empty(*nodes))
497 		return ERR_PTR(-EINVAL);
498 
499 	policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
500 	if (!policy)
501 		return ERR_PTR(-ENOMEM);
502 	atomic_set(&policy->refcnt, 1);
503 	policy->mode = mode;
504 	policy->flags = flags;
505 	policy->home_node = NUMA_NO_NODE;
506 
507 	return policy;
508 }
509 
510 /* Slow path of a mpol destructor. */
511 void __mpol_put(struct mempolicy *pol)
512 {
513 	if (!atomic_dec_and_test(&pol->refcnt))
514 		return;
515 	/*
516 	 * Required to allow mmap_lock_speculative*() access, see for example
517 	 * futex_key_to_node_opt(). All accesses are serialized by mmap_lock,
518 	 * however the speculative lock section unbound by the normal lock
519 	 * boundaries, requiring RCU freeing.
520 	 */
521 	kfree_rcu(pol, rcu);
522 }
523 EXPORT_SYMBOL_FOR_MODULES(__mpol_put, "kvm");
524 
525 static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
526 {
527 }
528 
529 static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
530 {
531 	nodemask_t tmp;
532 
533 	if (pol->flags & MPOL_F_STATIC_NODES)
534 		nodes_and(tmp, pol->w.user_nodemask, *nodes);
535 	else if (pol->flags & MPOL_F_RELATIVE_NODES)
536 		mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
537 	else {
538 		nodes_remap(tmp, pol->nodes, pol->w.cpuset_mems_allowed,
539 								*nodes);
540 		pol->w.cpuset_mems_allowed = *nodes;
541 	}
542 
543 	if (nodes_empty(tmp))
544 		tmp = *nodes;
545 
546 	pol->nodes = tmp;
547 }
548 
549 static void mpol_rebind_preferred(struct mempolicy *pol,
550 						const nodemask_t *nodes)
551 {
552 	pol->w.cpuset_mems_allowed = *nodes;
553 }
554 
555 /*
556  * mpol_rebind_policy - Migrate a policy to a different set of nodes
557  *
558  * Per-vma policies are protected by mmap_lock. Allocations using per-task
559  * policies are protected by task->mems_allowed_seq to prevent a premature
560  * OOM/allocation failure due to parallel nodemask modification.
561  */
562 static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
563 {
564 	if (!pol || pol->mode == MPOL_LOCAL)
565 		return;
566 	if (!mpol_store_user_nodemask(pol) &&
567 	    nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
568 		return;
569 
570 	mpol_ops[pol->mode].rebind(pol, newmask);
571 }
572 
573 /*
574  * Wrapper for mpol_rebind_policy() that just requires task
575  * pointer, and updates task mempolicy.
576  *
577  * Called with task's alloc_lock held.
578  */
579 void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
580 {
581 	mpol_rebind_policy(tsk->mempolicy, new);
582 }
583 
584 /*
585  * Rebind each vma in mm to new nodemask.
586  *
587  * Call holding a reference to mm.  Takes mm->mmap_lock during call.
588  */
589 void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
590 {
591 	struct vm_area_struct *vma;
592 	VMA_ITERATOR(vmi, mm, 0);
593 
594 	mmap_write_lock(mm);
595 	for_each_vma(vmi, vma) {
596 		vma_start_write(vma);
597 		mpol_rebind_policy(vma->vm_policy, new);
598 	}
599 	mmap_write_unlock(mm);
600 }
601 
602 static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
603 	[MPOL_DEFAULT] = {
604 		.rebind = mpol_rebind_default,
605 	},
606 	[MPOL_INTERLEAVE] = {
607 		.create = mpol_new_nodemask,
608 		.rebind = mpol_rebind_nodemask,
609 	},
610 	[MPOL_PREFERRED] = {
611 		.create = mpol_new_preferred,
612 		.rebind = mpol_rebind_preferred,
613 	},
614 	[MPOL_BIND] = {
615 		.create = mpol_new_nodemask,
616 		.rebind = mpol_rebind_nodemask,
617 	},
618 	[MPOL_LOCAL] = {
619 		.rebind = mpol_rebind_default,
620 	},
621 	[MPOL_PREFERRED_MANY] = {
622 		.create = mpol_new_nodemask,
623 		.rebind = mpol_rebind_preferred,
624 	},
625 	[MPOL_WEIGHTED_INTERLEAVE] = {
626 		.create = mpol_new_nodemask,
627 		.rebind = mpol_rebind_nodemask,
628 	},
629 };
630 
631 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
632 				unsigned long flags);
633 static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,
634 				pgoff_t ilx, int *nid);
635 
636 static bool strictly_unmovable(unsigned long flags)
637 {
638 	/*
639 	 * STRICT without MOVE flags lets do_mbind() fail immediately with -EIO
640 	 * if any misplaced page is found.
641 	 */
642 	return (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ==
643 			 MPOL_MF_STRICT;
644 }
645 
646 struct migration_mpol {		/* for alloc_migration_target_by_mpol() */
647 	struct mempolicy *pol;
648 	pgoff_t ilx;
649 };
650 
651 struct queue_pages {
652 	struct list_head *pagelist;
653 	unsigned long flags;
654 	nodemask_t *nmask;
655 	unsigned long start;
656 	unsigned long end;
657 	struct vm_area_struct *first;
658 	struct folio *large;		/* note last large folio encountered */
659 	long nr_failed;			/* could not be isolated at this time */
660 };
661 
662 /*
663  * Check if the folio's nid is in qp->nmask.
664  *
665  * If MPOL_MF_INVERT is set in qp->flags, check if the nid is
666  * in the invert of qp->nmask.
667  */
668 static inline bool queue_folio_required(struct folio *folio,
669 					struct queue_pages *qp)
670 {
671 	int nid = folio_nid(folio);
672 	unsigned long flags = qp->flags;
673 
674 	return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
675 }
676 
677 static void queue_folios_pmd(pmd_t *pmd, unsigned long addr,
678 		struct mm_walk *walk)
679 {
680 	struct folio *folio;
681 	struct queue_pages *qp = walk->private;
682 	pmd_t pmdval = pmdp_get(pmd);
683 
684 	if (unlikely(!pmd_present(pmdval))) {
685 		if (pmd_is_migration_entry(pmdval))
686 			qp->nr_failed++;
687 		return;
688 	}
689 	folio = vm_normal_folio_pmd(walk->vma, addr, pmdval);
690 	if (!folio || folio_is_zone_device(folio))
691 		return;
692 	if (!queue_folio_required(folio, qp))
693 		return;
694 	if (!(qp->flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
695 	    !vma_migratable(walk->vma) ||
696 	    !migrate_folio_add(folio, qp->pagelist, qp->flags))
697 		qp->nr_failed++;
698 }
699 
700 /*
701  * Scan through folios, checking if they satisfy the required conditions,
702  * moving them from LRU to local pagelist for migration if they do (or not).
703  *
704  * queue_folios_pte_range() has two possible return values:
705  * 0 - continue walking to scan for more, even if an existing folio on the
706  *     wrong node could not be isolated and queued for migration.
707  * -EIO - only MPOL_MF_STRICT was specified, without MPOL_MF_MOVE or ..._ALL,
708  *        and an existing folio was on a node that does not follow the policy.
709  */
710 static int queue_folios_pte_range(pmd_t *pmd, unsigned long addr,
711 			unsigned long end, struct mm_walk *walk)
712 {
713 	struct vm_area_struct *vma = walk->vma;
714 	struct folio *folio;
715 	struct queue_pages *qp = walk->private;
716 	unsigned long flags = qp->flags;
717 	pte_t *pte, *mapped_pte;
718 	pte_t ptent;
719 	spinlock_t *ptl;
720 	int max_nr, nr;
721 
722 	ptl = pmd_trans_huge_lock(pmd, vma);
723 	if (ptl) {
724 		queue_folios_pmd(pmd, addr, walk);
725 		spin_unlock(ptl);
726 		goto out;
727 	}
728 
729 	mapped_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
730 	if (!pte) {
731 		walk->action = ACTION_AGAIN;
732 		return 0;
733 	}
734 	for (; addr != end; pte += nr, addr += nr * PAGE_SIZE) {
735 		max_nr = (end - addr) >> PAGE_SHIFT;
736 		nr = 1;
737 		ptent = ptep_get(pte);
738 		if (pte_none(ptent))
739 			continue;
740 		if (!pte_present(ptent)) {
741 			const softleaf_t entry = softleaf_from_pte(ptent);
742 
743 			if (softleaf_is_migration(entry))
744 				qp->nr_failed++;
745 			continue;
746 		}
747 		folio = vm_normal_folio(vma, addr, ptent);
748 		if (!folio || folio_is_zone_device(folio))
749 			continue;
750 		if (folio_test_large(folio) && max_nr != 1)
751 			nr = folio_pte_batch(folio, pte, ptent, max_nr);
752 		/*
753 		 * vm_normal_folio() filters out zero pages, but there might
754 		 * still be reserved folios to skip, perhaps in a VDSO.
755 		 */
756 		if (folio_test_reserved(folio))
757 			continue;
758 		if (!queue_folio_required(folio, qp))
759 			continue;
760 		if (folio_test_large(folio)) {
761 			/*
762 			 * A large folio can only be isolated from LRU once,
763 			 * but may be mapped by many PTEs (and Copy-On-Write may
764 			 * intersperse PTEs of other, order 0, folios).  This is
765 			 * a common case, so don't mistake it for failure (but
766 			 * there can be other cases of multi-mapped pages which
767 			 * this quick check does not help to filter out - and a
768 			 * search of the pagelist might grow to be prohibitive).
769 			 *
770 			 * migrate_pages(&pagelist) returns nr_failed folios, so
771 			 * check "large" now so that queue_pages_range() returns
772 			 * a comparable nr_failed folios.  This does imply that
773 			 * if folio could not be isolated for some racy reason
774 			 * at its first PTE, later PTEs will not give it another
775 			 * chance of isolation; but keeps the accounting simple.
776 			 */
777 			if (folio == qp->large)
778 				continue;
779 			qp->large = folio;
780 		}
781 		if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
782 		    !vma_migratable(vma) ||
783 		    !migrate_folio_add(folio, qp->pagelist, flags)) {
784 			qp->nr_failed += nr;
785 			if (strictly_unmovable(flags))
786 				break;
787 		}
788 	}
789 	pte_unmap_unlock(mapped_pte, ptl);
790 	cond_resched();
791 out:
792 	if (qp->nr_failed && strictly_unmovable(flags))
793 		return -EIO;
794 	return 0;
795 }
796 
797 static int queue_folios_hugetlb(pte_t *pte, unsigned long hmask,
798 			       unsigned long addr, unsigned long end,
799 			       struct mm_walk *walk)
800 {
801 #ifdef CONFIG_HUGETLB_PAGE
802 	struct queue_pages *qp = walk->private;
803 	unsigned long flags = qp->flags;
804 	struct folio *folio;
805 	spinlock_t *ptl;
806 	pte_t ptep;
807 
808 	ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
809 	ptep = huge_ptep_get(walk->mm, addr, pte);
810 	if (!pte_present(ptep)) {
811 		if (!huge_pte_none(ptep)) {
812 			const softleaf_t entry = softleaf_from_pte(ptep);
813 
814 			if (unlikely(softleaf_is_migration(entry)))
815 				qp->nr_failed++;
816 		}
817 
818 		goto unlock;
819 	}
820 	folio = pfn_folio(pte_pfn(ptep));
821 	if (!queue_folio_required(folio, qp))
822 		goto unlock;
823 	if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
824 	    !vma_migratable(walk->vma)) {
825 		qp->nr_failed++;
826 		goto unlock;
827 	}
828 	/*
829 	 * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
830 	 * Choosing not to migrate a shared folio is not counted as a failure.
831 	 *
832 	 * See folio_maybe_mapped_shared() on possible imprecision when we
833 	 * cannot easily detect if a folio is shared.
834 	 */
835 	if ((flags & MPOL_MF_MOVE_ALL) ||
836 	    (!folio_maybe_mapped_shared(folio) && !hugetlb_pmd_shared(pte)))
837 		if (!folio_isolate_hugetlb(folio, qp->pagelist))
838 			qp->nr_failed++;
839 unlock:
840 	spin_unlock(ptl);
841 	if (qp->nr_failed && strictly_unmovable(flags))
842 		return -EIO;
843 #endif
844 	return 0;
845 }
846 
847 #ifdef CONFIG_NUMA_BALANCING
848 /**
849  * folio_can_map_prot_numa() - check whether the folio can map prot numa
850  * @folio: The folio whose mapping considered for being made NUMA hintable
851  * @vma: The VMA that the folio belongs to.
852  * @is_private_single_threaded: Is this a single-threaded private VMA or not
853  *
854  * This function checks to see if the folio actually indicates that
855  * we need to make the mapping one which causes a NUMA hinting fault,
856  * as there are cases where it's simply unnecessary, and the folio's
857  * access time is adjusted for memory tiering if prot numa needed.
858  *
859  * Return: True if the mapping of the folio needs to be changed, false otherwise.
860  */
861 bool folio_can_map_prot_numa(struct folio *folio, struct vm_area_struct *vma,
862 		bool is_private_single_threaded)
863 {
864 	int nid;
865 
866 	if (!folio || folio_is_zone_device(folio) || folio_test_ksm(folio))
867 		return false;
868 
869 	/* Also skip shared copy-on-write folios */
870 	if (vma_is_cow_mapping(vma) && folio_maybe_mapped_shared(folio))
871 		return false;
872 
873 	/* Folios are pinned and can't be migrated */
874 	if (folio_maybe_dma_pinned(folio))
875 		return false;
876 
877 	/*
878 	 * While migration can move some dirty folios,
879 	 * it cannot move them all from MIGRATE_ASYNC
880 	 * context.
881 	 */
882 	if (folio_is_file_lru(folio) && folio_test_dirty(folio))
883 		return false;
884 
885 	/*
886 	 * Don't mess with PTEs if folio is already on the node
887 	 * a single-threaded process is running on.
888 	 */
889 	nid = folio_nid(folio);
890 	if (is_private_single_threaded && (nid == numa_node_id()))
891 		return false;
892 
893 	/*
894 	 * Skip scanning top tier node if normal numa
895 	 * balancing is disabled
896 	 */
897 	if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) &&
898 	    node_is_toptier(nid))
899 		return false;
900 
901 	if (folio_use_access_time(folio))
902 		folio_xchg_access_time(folio, jiffies_to_msecs(jiffies));
903 
904 	return true;
905 }
906 
907 /*
908  * This is used to mark a range of virtual addresses to be inaccessible.
909  * These are later cleared by a NUMA hinting fault. Depending on these
910  * faults, pages may be migrated for better NUMA placement.
911  *
912  * This is assuming that NUMA faults are handled using PROT_NONE. If
913  * an architecture makes a different choice, it will need further
914  * changes to the core.
915  */
916 unsigned long change_prot_numa(struct vm_area_struct *vma,
917 			unsigned long addr, unsigned long end)
918 {
919 	struct mmu_gather tlb;
920 	long nr_updated;
921 
922 	tlb_gather_mmu(&tlb, vma->vm_mm);
923 
924 	nr_updated = change_protection(&tlb, vma, addr, end, MM_CP_PROT_NUMA);
925 	if (nr_updated > 0) {
926 		count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
927 		count_memcg_events_mm(vma->vm_mm, NUMA_PTE_UPDATES, nr_updated);
928 	}
929 
930 	tlb_finish_mmu(&tlb);
931 
932 	return nr_updated;
933 }
934 #endif /* CONFIG_NUMA_BALANCING */
935 
936 static int queue_pages_test_walk(unsigned long start, unsigned long end,
937 				struct mm_walk *walk)
938 {
939 	struct vm_area_struct *next, *vma = walk->vma;
940 	struct queue_pages *qp = walk->private;
941 	unsigned long flags = qp->flags;
942 
943 	/* range check first */
944 	VM_BUG_ON_VMA(!range_in_vma(vma, start, end), vma);
945 
946 	if (!qp->first) {
947 		qp->first = vma;
948 		if (!(flags & MPOL_MF_DISCONTIG_OK) &&
949 			(qp->start < vma->vm_start))
950 			/* hole at head side of range */
951 			return -EFAULT;
952 	}
953 	next = find_vma(vma->vm_mm, vma->vm_end);
954 	if (!(flags & MPOL_MF_DISCONTIG_OK) &&
955 		((vma->vm_end < qp->end) &&
956 		(!next || vma->vm_end < next->vm_start)))
957 		/* hole at middle or tail of range */
958 		return -EFAULT;
959 
960 	/*
961 	 * Need check MPOL_MF_STRICT to return -EIO if possible
962 	 * regardless of vma_migratable
963 	 */
964 	if (!vma_migratable(vma) &&
965 	    !(flags & MPOL_MF_STRICT))
966 		return 1;
967 
968 	/*
969 	 * Check page nodes, and queue pages to move, in the current vma.
970 	 * But if no moving, and no strict checking, the scan can be skipped.
971 	 */
972 	if (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
973 		return 0;
974 	return 1;
975 }
976 
977 static const struct mm_walk_ops queue_pages_walk_ops = {
978 	.hugetlb_entry		= queue_folios_hugetlb,
979 	.pmd_entry		= queue_folios_pte_range,
980 	.test_walk		= queue_pages_test_walk,
981 	.walk_lock		= PGWALK_RDLOCK,
982 };
983 
984 static const struct mm_walk_ops queue_pages_lock_vma_walk_ops = {
985 	.hugetlb_entry		= queue_folios_hugetlb,
986 	.pmd_entry		= queue_folios_pte_range,
987 	.test_walk		= queue_pages_test_walk,
988 	.walk_lock		= PGWALK_WRLOCK,
989 };
990 
991 /*
992  * Walk through page tables and collect pages to be migrated.
993  *
994  * If pages found in a given range are not on the required set of @nodes,
995  * and migration is allowed, they are isolated and queued to @pagelist.
996  *
997  * queue_pages_range() may return:
998  * 0 - all pages already on the right node, or successfully queued for moving
999  *     (or neither strict checking nor moving requested: only range checking).
1000  * >0 - this number of misplaced folios could not be queued for moving
1001  *      (a hugetlbfs page or a transparent huge page being counted as 1).
1002  * -EIO - a misplaced page found, when MPOL_MF_STRICT specified without MOVEs.
1003  * -EFAULT - a hole in the memory range, when MPOL_MF_DISCONTIG_OK unspecified.
1004  */
1005 static long
1006 queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
1007 		nodemask_t *nodes, unsigned long flags,
1008 		struct list_head *pagelist)
1009 {
1010 	int err;
1011 	struct queue_pages qp = {
1012 		.pagelist = pagelist,
1013 		.flags = flags,
1014 		.nmask = nodes,
1015 		.start = start,
1016 		.end = end,
1017 		.first = NULL,
1018 	};
1019 	const struct mm_walk_ops *ops = (flags & MPOL_MF_WRLOCK) ?
1020 			&queue_pages_lock_vma_walk_ops : &queue_pages_walk_ops;
1021 
1022 	err = walk_page_range(mm, start, end, ops, &qp);
1023 
1024 	if (!qp.first)
1025 		/* whole range in hole */
1026 		err = -EFAULT;
1027 
1028 	return err ? : qp.nr_failed;
1029 }
1030 
1031 /*
1032  * Apply policy to a single VMA
1033  * This must be called with the mmap_lock held for writing.
1034  */
1035 static int vma_replace_policy(struct vm_area_struct *vma,
1036 				struct mempolicy *pol)
1037 {
1038 	int err;
1039 	struct mempolicy *old;
1040 	struct mempolicy *new;
1041 
1042 	vma_assert_write_locked(vma);
1043 
1044 	new = mpol_dup(pol);
1045 	if (IS_ERR(new))
1046 		return PTR_ERR(new);
1047 
1048 	if (vma->vm_ops && vma->vm_ops->set_policy) {
1049 		err = vma->vm_ops->set_policy(vma, new);
1050 		if (err)
1051 			goto err_out;
1052 	}
1053 
1054 	old = vma->vm_policy;
1055 	WRITE_ONCE(vma->vm_policy, new); /* protected by mmap_lock */
1056 	mpol_put(old);
1057 
1058 	return 0;
1059  err_out:
1060 	mpol_put(new);
1061 	return err;
1062 }
1063 
1064 /* Split or merge the VMA (if required) and apply the new policy */
1065 static int mbind_range(struct vma_iterator *vmi, struct vm_area_struct *vma,
1066 		struct vm_area_struct **prev, unsigned long start,
1067 		unsigned long end, struct mempolicy *new_pol)
1068 {
1069 	unsigned long vmstart, vmend;
1070 
1071 	vmend = min(end, vma->vm_end);
1072 	if (start > vma->vm_start) {
1073 		*prev = vma;
1074 		vmstart = start;
1075 	} else {
1076 		vmstart = vma->vm_start;
1077 	}
1078 
1079 	if (mpol_equal(vma->vm_policy, new_pol)) {
1080 		*prev = vma;
1081 		return 0;
1082 	}
1083 
1084 	vma =  vma_modify_policy(vmi, *prev, vma, vmstart, vmend, new_pol);
1085 	if (IS_ERR(vma))
1086 		return PTR_ERR(vma);
1087 
1088 	*prev = vma;
1089 	return vma_replace_policy(vma, new_pol);
1090 }
1091 
1092 /* Set the process memory policy */
1093 static long do_set_mempolicy(unsigned short mode, unsigned short flags,
1094 			     nodemask_t *nodes)
1095 {
1096 	struct mempolicy *new, *old;
1097 	NODEMASK_SCRATCH(scratch);
1098 	int ret;
1099 
1100 	if (!scratch)
1101 		return -ENOMEM;
1102 
1103 	new = mpol_new(mode, flags, nodes);
1104 	if (IS_ERR(new)) {
1105 		ret = PTR_ERR(new);
1106 		goto out;
1107 	}
1108 
1109 	task_lock(current);
1110 	ret = mpol_set_nodemask(new, nodes, scratch);
1111 	if (ret) {
1112 		task_unlock(current);
1113 		mpol_put(new);
1114 		goto out;
1115 	}
1116 
1117 	old = current->mempolicy;
1118 	current->mempolicy = new;
1119 	if (new && (new->mode == MPOL_INTERLEAVE ||
1120 		    new->mode == MPOL_WEIGHTED_INTERLEAVE)) {
1121 		current->il_prev = MAX_NUMNODES-1;
1122 		current->il_weight = 0;
1123 	}
1124 	task_unlock(current);
1125 	mpol_put(old);
1126 	ret = 0;
1127 out:
1128 	NODEMASK_SCRATCH_FREE(scratch);
1129 	return ret;
1130 }
1131 
1132 /*
1133  * Return nodemask for policy for get_mempolicy() query
1134  *
1135  * Called with task's alloc_lock held
1136  */
1137 static void get_policy_nodemask(struct mempolicy *pol, nodemask_t *nodes)
1138 {
1139 	nodes_clear(*nodes);
1140 	if (pol == &default_policy)
1141 		return;
1142 
1143 	switch (pol->mode) {
1144 	case MPOL_BIND:
1145 	case MPOL_INTERLEAVE:
1146 	case MPOL_PREFERRED:
1147 	case MPOL_PREFERRED_MANY:
1148 	case MPOL_WEIGHTED_INTERLEAVE:
1149 		*nodes = pol->nodes;
1150 		break;
1151 	case MPOL_LOCAL:
1152 		/* return empty node mask for local allocation */
1153 		break;
1154 	default:
1155 		BUG();
1156 	}
1157 }
1158 
1159 static int lookup_node(struct mm_struct *mm, unsigned long addr)
1160 {
1161 	struct page *p = NULL;
1162 	int ret;
1163 
1164 	ret = get_user_pages_fast(addr & PAGE_MASK, 1, 0, &p);
1165 	if (ret > 0) {
1166 		ret = page_to_nid(p);
1167 		put_page(p);
1168 	}
1169 	return ret;
1170 }
1171 
1172 /* Retrieve NUMA policy */
1173 static long do_get_mempolicy(int *policy, nodemask_t *nmask,
1174 			     unsigned long addr, unsigned long flags)
1175 {
1176 	int err;
1177 	struct mm_struct *mm = current->mm;
1178 	struct vm_area_struct *vma = NULL;
1179 	struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL;
1180 
1181 	if (flags &
1182 		~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
1183 		return -EINVAL;
1184 
1185 	if (flags & MPOL_F_MEMS_ALLOWED) {
1186 		if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
1187 			return -EINVAL;
1188 		*policy = 0;	/* just so it's initialized */
1189 		task_lock(current);
1190 		*nmask  = cpuset_current_mems_allowed;
1191 		task_unlock(current);
1192 		return 0;
1193 	}
1194 
1195 	if (flags & MPOL_F_ADDR) {
1196 		pgoff_t ilx;		/* ignored here */
1197 		/*
1198 		 * Do NOT fall back to task policy if the
1199 		 * vma/shared policy at addr is NULL.  We
1200 		 * want to return MPOL_DEFAULT in this case.
1201 		 */
1202 		mmap_read_lock(mm);
1203 		vma = vma_lookup(mm, addr);
1204 		if (!vma) {
1205 			mmap_read_unlock(mm);
1206 			return -EFAULT;
1207 		}
1208 		pol = __get_vma_policy(vma, addr, &ilx);
1209 	} else if (addr)
1210 		return -EINVAL;
1211 
1212 	if (!pol)
1213 		pol = &default_policy;	/* indicates default behavior */
1214 
1215 	if (flags & MPOL_F_NODE) {
1216 		if (flags & MPOL_F_ADDR) {
1217 			/*
1218 			 * Take a refcount on the mpol, because we are about to
1219 			 * drop the mmap_lock, after which only "pol" remains
1220 			 * valid, "vma" is stale.
1221 			 */
1222 			pol_refcount = pol;
1223 			vma = NULL;
1224 			mpol_get(pol);
1225 			mmap_read_unlock(mm);
1226 			err = lookup_node(mm, addr);
1227 			if (err < 0)
1228 				goto out;
1229 			*policy = err;
1230 		} else if (pol == current->mempolicy &&
1231 				pol->mode == MPOL_INTERLEAVE) {
1232 			*policy = next_node_in(current->il_prev, pol->nodes);
1233 		} else if (pol == current->mempolicy &&
1234 				pol->mode == MPOL_WEIGHTED_INTERLEAVE) {
1235 			if (current->il_weight)
1236 				*policy = current->il_prev;
1237 			else
1238 				*policy = next_node_in(current->il_prev,
1239 						       pol->nodes);
1240 		} else {
1241 			err = -EINVAL;
1242 			goto out;
1243 		}
1244 	} else {
1245 		*policy = pol == &default_policy ? MPOL_DEFAULT :
1246 						pol->mode;
1247 		/*
1248 		 * Internal mempolicy flags must be masked off before exposing
1249 		 * the policy to userspace.
1250 		 */
1251 		*policy |= (pol->flags & MPOL_MODE_FLAGS);
1252 	}
1253 
1254 	err = 0;
1255 	if (nmask) {
1256 		if (mpol_store_user_nodemask(pol)) {
1257 			*nmask = pol->w.user_nodemask;
1258 		} else {
1259 			task_lock(current);
1260 			get_policy_nodemask(pol, nmask);
1261 			task_unlock(current);
1262 		}
1263 	}
1264 
1265  out:
1266 	mpol_cond_put(pol);
1267 	if (vma)
1268 		mmap_read_unlock(mm);
1269 	if (pol_refcount)
1270 		mpol_put(pol_refcount);
1271 	return err;
1272 }
1273 
1274 #ifdef CONFIG_NUMA_MIGRATION
1275 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
1276 				unsigned long flags)
1277 {
1278 	/*
1279 	 * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
1280 	 * Choosing not to migrate a shared folio is not counted as a failure.
1281 	 *
1282 	 * See folio_maybe_mapped_shared() on possible imprecision when we
1283 	 * cannot easily detect if a folio is shared.
1284 	 */
1285 	if ((flags & MPOL_MF_MOVE_ALL) || !folio_maybe_mapped_shared(folio)) {
1286 		if (folio_isolate_lru(folio)) {
1287 			list_add_tail(&folio->lru, foliolist);
1288 			node_stat_mod_folio(folio,
1289 				NR_ISOLATED_ANON + folio_is_file_lru(folio),
1290 				folio_nr_pages(folio));
1291 		} else {
1292 			/*
1293 			 * Non-movable folio may reach here.  And, there may be
1294 			 * temporary off LRU folios or non-LRU movable folios.
1295 			 * Treat them as unmovable folios since they can't be
1296 			 * isolated, so they can't be moved at the moment.
1297 			 */
1298 			return false;
1299 		}
1300 	}
1301 	return true;
1302 }
1303 
1304 /*
1305  * Migrate pages from one node to a target node.
1306  * Returns error or the number of pages not migrated.
1307  */
1308 static long migrate_to_node(struct mm_struct *mm, int source, int dest,
1309 			    int flags)
1310 {
1311 	nodemask_t nmask;
1312 	struct vm_area_struct *vma;
1313 	LIST_HEAD(pagelist);
1314 	long nr_failed;
1315 	long err = 0;
1316 	struct migration_target_control mtc = {
1317 		.nid = dest,
1318 		.gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
1319 		.reason = MR_SYSCALL,
1320 	};
1321 
1322 	nodes_clear(nmask);
1323 	node_set(source, nmask);
1324 
1325 	VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
1326 
1327 	mmap_read_lock(mm);
1328 	vma = find_vma(mm, 0);
1329 	if (unlikely(!vma)) {
1330 		mmap_read_unlock(mm);
1331 		return 0;
1332 	}
1333 
1334 	/*
1335 	 * This does not migrate the range, but isolates all pages that
1336 	 * need migration.  Between passing in the full user address
1337 	 * space range and MPOL_MF_DISCONTIG_OK, this call cannot fail,
1338 	 * but passes back the count of pages which could not be isolated.
1339 	 */
1340 	nr_failed = queue_pages_range(mm, vma->vm_start, mm->task_size, &nmask,
1341 				      flags | MPOL_MF_DISCONTIG_OK, &pagelist);
1342 	mmap_read_unlock(mm);
1343 
1344 	if (!list_empty(&pagelist)) {
1345 		err = migrate_pages(&pagelist, alloc_migration_target, NULL,
1346 			(unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
1347 		if (err)
1348 			putback_movable_pages(&pagelist);
1349 	}
1350 
1351 	if (err >= 0)
1352 		err += nr_failed;
1353 	return err;
1354 }
1355 
1356 /*
1357  * Move pages between the two nodesets so as to preserve the physical
1358  * layout as much as possible.
1359  *
1360  * Returns the number of page that could not be moved.
1361  */
1362 int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
1363 		     const nodemask_t *to, int flags)
1364 {
1365 	long nr_failed = 0;
1366 	long err = 0;
1367 	nodemask_t tmp;
1368 
1369 	lru_cache_disable();
1370 
1371 	/*
1372 	 * Find a 'source' bit set in 'tmp' whose corresponding 'dest'
1373 	 * bit in 'to' is not also set in 'tmp'.  Clear the found 'source'
1374 	 * bit in 'tmp', and return that <source, dest> pair for migration.
1375 	 * The pair of nodemasks 'to' and 'from' define the map.
1376 	 *
1377 	 * If no pair of bits is found that way, fallback to picking some
1378 	 * pair of 'source' and 'dest' bits that are not the same.  If the
1379 	 * 'source' and 'dest' bits are the same, this represents a node
1380 	 * that will be migrating to itself, so no pages need move.
1381 	 *
1382 	 * If no bits are left in 'tmp', or if all remaining bits left
1383 	 * in 'tmp' correspond to the same bit in 'to', return false
1384 	 * (nothing left to migrate).
1385 	 *
1386 	 * This lets us pick a pair of nodes to migrate between, such that
1387 	 * if possible the dest node is not already occupied by some other
1388 	 * source node, minimizing the risk of overloading the memory on a
1389 	 * node that would happen if we migrated incoming memory to a node
1390 	 * before migrating outgoing memory source that same node.
1391 	 *
1392 	 * A single scan of tmp is sufficient.  As we go, we remember the
1393 	 * most recent <s, d> pair that moved (s != d).  If we find a pair
1394 	 * that not only moved, but what's better, moved to an empty slot
1395 	 * (d is not set in tmp), then we break out then, with that pair.
1396 	 * Otherwise when we finish scanning from_tmp, we at least have the
1397 	 * most recent <s, d> pair that moved.  If we get all the way through
1398 	 * the scan of tmp without finding any node that moved, much less
1399 	 * moved to an empty node, then there is nothing left worth migrating.
1400 	 */
1401 
1402 	tmp = *from;
1403 	while (!nodes_empty(tmp)) {
1404 		int s, d;
1405 		int source = NUMA_NO_NODE;
1406 		int dest = 0;
1407 
1408 		for_each_node_mask(s, tmp) {
1409 
1410 			/*
1411 			 * do_migrate_pages() tries to maintain the relative
1412 			 * node relationship of the pages established between
1413 			 * threads and memory areas.
1414                          *
1415 			 * However if the number of source nodes is not equal to
1416 			 * the number of destination nodes we can not preserve
1417 			 * this node relative relationship.  In that case, skip
1418 			 * copying memory from a node that is in the destination
1419 			 * mask.
1420 			 *
1421 			 * Example: [2,3,4] -> [3,4,5] moves everything.
1422 			 *          [0-7] - > [3,4,5] moves only 0,1,2,6,7.
1423 			 */
1424 
1425 			if ((nodes_weight(*from) != nodes_weight(*to)) &&
1426 						(node_isset(s, *to)))
1427 				continue;
1428 
1429 			d = node_remap(s, *from, *to);
1430 			if (s == d)
1431 				continue;
1432 
1433 			source = s;	/* Node moved. Memorize */
1434 			dest = d;
1435 
1436 			/* dest not in remaining from nodes? */
1437 			if (!node_isset(dest, tmp))
1438 				break;
1439 		}
1440 		if (source == NUMA_NO_NODE)
1441 			break;
1442 
1443 		node_clear(source, tmp);
1444 		err = migrate_to_node(mm, source, dest, flags);
1445 		if (err > 0)
1446 			nr_failed += err;
1447 		if (err < 0)
1448 			break;
1449 	}
1450 
1451 	lru_cache_enable();
1452 	if (err < 0)
1453 		return err;
1454 	return (nr_failed < INT_MAX) ? nr_failed : INT_MAX;
1455 }
1456 
1457 /*
1458  * Allocate a new folio for page migration, according to NUMA mempolicy.
1459  */
1460 static struct folio *alloc_migration_target_by_mpol(struct folio *src,
1461 						    unsigned long private)
1462 {
1463 	struct migration_mpol *mmpol = (struct migration_mpol *)private;
1464 	struct mempolicy *pol = mmpol->pol;
1465 	pgoff_t ilx = mmpol->ilx;
1466 	unsigned int order;
1467 	int nid = numa_node_id();
1468 	gfp_t gfp;
1469 
1470 	order = folio_order(src);
1471 	ilx += src->index >> order;
1472 
1473 	if (folio_test_hugetlb(src)) {
1474 		nodemask_t *nodemask;
1475 		struct hstate *h;
1476 
1477 		h = folio_hstate(src);
1478 		gfp = htlb_alloc_mask(h);
1479 		nodemask = policy_nodemask(gfp, pol, ilx, &nid);
1480 		return alloc_hugetlb_folio_nodemask(h, nid, nodemask, gfp,
1481 				htlb_allow_alloc_fallback(MR_MEMPOLICY_MBIND));
1482 	}
1483 
1484 	if (folio_test_large(src))
1485 		gfp = GFP_TRANSHUGE;
1486 	else
1487 		gfp = GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL | __GFP_COMP;
1488 
1489 	return folio_alloc_mpol(gfp, order, pol, ilx, nid);
1490 }
1491 #else
1492 
1493 static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
1494 				unsigned long flags)
1495 {
1496 	return false;
1497 }
1498 
1499 int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
1500 		     const nodemask_t *to, int flags)
1501 {
1502 	return -ENOSYS;
1503 }
1504 
1505 static struct folio *alloc_migration_target_by_mpol(struct folio *src,
1506 						    unsigned long private)
1507 {
1508 	return NULL;
1509 }
1510 #endif
1511 
1512 static long do_mbind(unsigned long start, unsigned long len,
1513 		     unsigned short mode, unsigned short mode_flags,
1514 		     nodemask_t *nmask, unsigned long flags)
1515 {
1516 	struct mm_struct *mm = current->mm;
1517 	struct vm_area_struct *vma, *prev;
1518 	struct vma_iterator vmi;
1519 	struct migration_mpol mmpol;
1520 	struct mempolicy *new;
1521 	unsigned long end;
1522 	long err;
1523 	long nr_failed;
1524 	LIST_HEAD(pagelist);
1525 
1526 	if (flags & ~(unsigned long)MPOL_MF_VALID)
1527 		return -EINVAL;
1528 	if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
1529 		return -EPERM;
1530 
1531 	if (start & ~PAGE_MASK)
1532 		return -EINVAL;
1533 
1534 	if (mode == MPOL_DEFAULT)
1535 		flags &= ~MPOL_MF_STRICT;
1536 
1537 	len = PAGE_ALIGN(len);
1538 	end = start + len;
1539 
1540 	if (end < start)
1541 		return -EINVAL;
1542 	if (end == start)
1543 		return 0;
1544 
1545 	new = mpol_new(mode, mode_flags, nmask);
1546 	if (IS_ERR(new))
1547 		return PTR_ERR(new);
1548 
1549 	/*
1550 	 * If we are using the default policy then operation
1551 	 * on discontinuous address spaces is okay after all
1552 	 */
1553 	if (!new)
1554 		flags |= MPOL_MF_DISCONTIG_OK;
1555 
1556 	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
1557 		lru_cache_disable();
1558 	{
1559 		NODEMASK_SCRATCH(scratch);
1560 		if (scratch) {
1561 			mmap_write_lock(mm);
1562 			err = mpol_set_nodemask(new, nmask, scratch);
1563 			if (err)
1564 				mmap_write_unlock(mm);
1565 		} else
1566 			err = -ENOMEM;
1567 		NODEMASK_SCRATCH_FREE(scratch);
1568 	}
1569 	if (err)
1570 		goto mpol_out;
1571 
1572 	/*
1573 	 * Lock the VMAs before scanning for pages to migrate,
1574 	 * to ensure we don't miss a concurrently inserted page.
1575 	 */
1576 	nr_failed = queue_pages_range(mm, start, end, nmask,
1577 			flags | MPOL_MF_INVERT | MPOL_MF_WRLOCK, &pagelist);
1578 
1579 	if (nr_failed < 0) {
1580 		err = nr_failed;
1581 		nr_failed = 0;
1582 	} else {
1583 		vma_iter_init(&vmi, mm, start);
1584 		prev = vma_prev(&vmi);
1585 		for_each_vma_range(vmi, vma, end) {
1586 			err = mbind_range(&vmi, vma, &prev, start, end, new);
1587 			if (err)
1588 				break;
1589 		}
1590 	}
1591 
1592 	if (!err && !list_empty(&pagelist)) {
1593 		/* Convert MPOL_DEFAULT's NULL to task or default policy */
1594 		if (!new) {
1595 			new = get_task_policy(current);
1596 			mpol_get(new);
1597 		}
1598 		mmpol.pol = new;
1599 		mmpol.ilx = 0;
1600 
1601 		/*
1602 		 * In the interleaved case, attempt to allocate on exactly the
1603 		 * targeted nodes, for the first VMA to be migrated; for later
1604 		 * VMAs, the nodes will still be interleaved from the targeted
1605 		 * nodemask, but one by one may be selected differently.
1606 		 */
1607 		if (new->mode == MPOL_INTERLEAVE ||
1608 		    new->mode == MPOL_WEIGHTED_INTERLEAVE) {
1609 			struct folio *folio;
1610 			unsigned int order;
1611 			unsigned long addr = -EFAULT;
1612 
1613 			list_for_each_entry(folio, &pagelist, lru) {
1614 				if (!folio_test_ksm(folio))
1615 					break;
1616 			}
1617 			if (!list_entry_is_head(folio, &pagelist, lru)) {
1618 				vma_iter_init(&vmi, mm, start);
1619 				for_each_vma_range(vmi, vma, end) {
1620 					addr = page_address_in_vma(folio,
1621 						folio_page(folio, 0), vma);
1622 					if (addr != -EFAULT)
1623 						break;
1624 				}
1625 			}
1626 			if (addr != -EFAULT) {
1627 				order = folio_order(folio);
1628 				/* We already know the pol, but not the ilx */
1629 				mpol_cond_put(get_vma_policy(vma, addr, order,
1630 							     &mmpol.ilx));
1631 				/* Set base from which to increment by index */
1632 				mmpol.ilx -= folio->index >> order;
1633 			}
1634 		}
1635 	}
1636 
1637 	mmap_write_unlock(mm);
1638 
1639 	if (!err && !list_empty(&pagelist)) {
1640 		nr_failed |= migrate_pages(&pagelist,
1641 				alloc_migration_target_by_mpol, NULL,
1642 				(unsigned long)&mmpol, MIGRATE_SYNC,
1643 				MR_MEMPOLICY_MBIND, NULL);
1644 	}
1645 
1646 	if (nr_failed && (flags & MPOL_MF_STRICT))
1647 		err = -EIO;
1648 	if (!list_empty(&pagelist))
1649 		putback_movable_pages(&pagelist);
1650 mpol_out:
1651 	mpol_put(new);
1652 	if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
1653 		lru_cache_enable();
1654 	return err;
1655 }
1656 
1657 /*
1658  * User space interface with variable sized bitmaps for nodelists.
1659  */
1660 static int get_bitmap(unsigned long *mask, const unsigned long __user *nmask,
1661 		      unsigned long maxnode)
1662 {
1663 	unsigned long nlongs = BITS_TO_LONGS(maxnode);
1664 	int ret;
1665 
1666 	if (in_compat_syscall())
1667 		ret = compat_get_bitmap(mask,
1668 					(const compat_ulong_t __user *)nmask,
1669 					maxnode);
1670 	else
1671 		ret = copy_from_user(mask, nmask,
1672 				     nlongs * sizeof(unsigned long));
1673 
1674 	if (ret)
1675 		return -EFAULT;
1676 
1677 	if (maxnode % BITS_PER_LONG)
1678 		mask[nlongs - 1] &= (1UL << (maxnode % BITS_PER_LONG)) - 1;
1679 
1680 	return 0;
1681 }
1682 
1683 /* Copy a node mask from user space. */
1684 static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
1685 		     unsigned long maxnode)
1686 {
1687 	--maxnode;
1688 	nodes_clear(*nodes);
1689 	if (maxnode == 0 || !nmask)
1690 		return 0;
1691 	if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
1692 		return -EINVAL;
1693 
1694 	/*
1695 	 * When the user specified more nodes than supported just check
1696 	 * if the non supported part is all zero, one word at a time,
1697 	 * starting at the end.
1698 	 */
1699 	while (maxnode > MAX_NUMNODES) {
1700 		unsigned long bits = min_t(unsigned long, maxnode, BITS_PER_LONG);
1701 		unsigned long t;
1702 
1703 		if (get_bitmap(&t, &nmask[(maxnode - 1) / BITS_PER_LONG], bits))
1704 			return -EFAULT;
1705 
1706 		if (maxnode - bits >= MAX_NUMNODES) {
1707 			maxnode -= bits;
1708 		} else {
1709 			maxnode = MAX_NUMNODES;
1710 			t &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1);
1711 		}
1712 		if (t)
1713 			return -EINVAL;
1714 	}
1715 
1716 	return get_bitmap(nodes_addr(*nodes), nmask, maxnode);
1717 }
1718 
1719 /* Copy a kernel node mask to user space */
1720 static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
1721 			      nodemask_t *nodes)
1722 {
1723 	unsigned long copy = ALIGN(maxnode-1, 64) / 8;
1724 	unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
1725 	bool compat = in_compat_syscall();
1726 
1727 	if (compat)
1728 		nbytes = BITS_TO_COMPAT_LONGS(nr_node_ids) * sizeof(compat_long_t);
1729 
1730 	if (copy > nbytes) {
1731 		if (copy > PAGE_SIZE)
1732 			return -EINVAL;
1733 		if (clear_user((char __user *)mask + nbytes, copy - nbytes))
1734 			return -EFAULT;
1735 		copy = nbytes;
1736 		maxnode = nr_node_ids;
1737 	}
1738 
1739 	if (compat)
1740 		return compat_put_bitmap((compat_ulong_t __user *)mask,
1741 					 nodes_addr(*nodes), maxnode);
1742 
1743 	return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
1744 }
1745 
1746 /* Basic parameter sanity check used by both mbind() and set_mempolicy() */
1747 static inline int sanitize_mpol_flags(int *mode, unsigned short *flags)
1748 {
1749 	*flags = *mode & MPOL_MODE_FLAGS;
1750 	*mode &= ~MPOL_MODE_FLAGS;
1751 
1752 	if ((unsigned int)(*mode) >=  MPOL_MAX)
1753 		return -EINVAL;
1754 	if ((*flags & MPOL_F_STATIC_NODES) && (*flags & MPOL_F_RELATIVE_NODES))
1755 		return -EINVAL;
1756 	if (*flags & MPOL_F_NUMA_BALANCING) {
1757 		if (*mode == MPOL_BIND || *mode == MPOL_PREFERRED_MANY)
1758 			*flags |= (MPOL_F_MOF | MPOL_F_MORON);
1759 		else
1760 			return -EINVAL;
1761 	}
1762 	return 0;
1763 }
1764 
1765 static long kernel_mbind(unsigned long start, unsigned long len,
1766 			 unsigned long mode, const unsigned long __user *nmask,
1767 			 unsigned long maxnode, unsigned int flags)
1768 {
1769 	unsigned short mode_flags;
1770 	nodemask_t nodes;
1771 	int lmode = mode;
1772 	int err;
1773 
1774 	start = untagged_addr(start);
1775 	err = sanitize_mpol_flags(&lmode, &mode_flags);
1776 	if (err)
1777 		return err;
1778 
1779 	err = get_nodes(&nodes, nmask, maxnode);
1780 	if (err)
1781 		return err;
1782 
1783 	return do_mbind(start, len, lmode, mode_flags, &nodes, flags);
1784 }
1785 
1786 SYSCALL_DEFINE4(set_mempolicy_home_node, unsigned long, start, unsigned long, len,
1787 		unsigned long, home_node, unsigned long, flags)
1788 {
1789 	struct mm_struct *mm = current->mm;
1790 	struct vm_area_struct *vma, *prev;
1791 	struct mempolicy *new, *old;
1792 	unsigned long end;
1793 	int err = -ENOENT;
1794 	VMA_ITERATOR(vmi, mm, start);
1795 
1796 	start = untagged_addr(start);
1797 	if (start & ~PAGE_MASK)
1798 		return -EINVAL;
1799 	/*
1800 	 * flags is used for future extension if any.
1801 	 */
1802 	if (flags != 0)
1803 		return -EINVAL;
1804 
1805 	/*
1806 	 * Check home_node is online to avoid accessing uninitialized
1807 	 * NODE_DATA.
1808 	 */
1809 	if (home_node >= MAX_NUMNODES || !node_online(home_node))
1810 		return -EINVAL;
1811 
1812 	len = PAGE_ALIGN(len);
1813 	end = start + len;
1814 
1815 	if (end < start)
1816 		return -EINVAL;
1817 	if (end == start)
1818 		return 0;
1819 	mmap_write_lock(mm);
1820 	prev = vma_prev(&vmi);
1821 	for_each_vma_range(vmi, vma, end) {
1822 		/*
1823 		 * If any vma in the range got policy other than MPOL_BIND
1824 		 * or MPOL_PREFERRED_MANY we return error. We don't reset
1825 		 * the home node for vmas we already updated before.
1826 		 */
1827 		old = vma_policy(vma);
1828 		if (!old) {
1829 			prev = vma;
1830 			continue;
1831 		}
1832 		if (old->mode != MPOL_BIND && old->mode != MPOL_PREFERRED_MANY) {
1833 			err = -EOPNOTSUPP;
1834 			break;
1835 		}
1836 		new = mpol_dup(old);
1837 		if (IS_ERR(new)) {
1838 			err = PTR_ERR(new);
1839 			break;
1840 		}
1841 
1842 		vma_start_write(vma);
1843 		new->home_node = home_node;
1844 		err = mbind_range(&vmi, vma, &prev, start, end, new);
1845 		mpol_put(new);
1846 		if (err)
1847 			break;
1848 	}
1849 	mmap_write_unlock(mm);
1850 	return err;
1851 }
1852 
1853 SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
1854 		unsigned long, mode, const unsigned long __user *, nmask,
1855 		unsigned long, maxnode, unsigned int, flags)
1856 {
1857 	return kernel_mbind(start, len, mode, nmask, maxnode, flags);
1858 }
1859 
1860 /* Set the process memory policy */
1861 static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask,
1862 				 unsigned long maxnode)
1863 {
1864 	unsigned short mode_flags;
1865 	nodemask_t nodes;
1866 	int lmode = mode;
1867 	int err;
1868 
1869 	err = sanitize_mpol_flags(&lmode, &mode_flags);
1870 	if (err)
1871 		return err;
1872 
1873 	err = get_nodes(&nodes, nmask, maxnode);
1874 	if (err)
1875 		return err;
1876 
1877 	return do_set_mempolicy(lmode, mode_flags, &nodes);
1878 }
1879 
1880 SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
1881 		unsigned long, maxnode)
1882 {
1883 	return kernel_set_mempolicy(mode, nmask, maxnode);
1884 }
1885 
1886 static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
1887 				const unsigned long __user *old_nodes,
1888 				const unsigned long __user *new_nodes)
1889 {
1890 	struct mm_struct *mm = NULL;
1891 	struct task_struct *task;
1892 	nodemask_t task_nodes;
1893 	int err;
1894 	nodemask_t *old;
1895 	nodemask_t *new;
1896 	NODEMASK_SCRATCH(scratch);
1897 
1898 	if (!scratch)
1899 		return -ENOMEM;
1900 
1901 	old = &scratch->mask1;
1902 	new = &scratch->mask2;
1903 
1904 	err = get_nodes(old, old_nodes, maxnode);
1905 	if (err)
1906 		goto out;
1907 
1908 	err = get_nodes(new, new_nodes, maxnode);
1909 	if (err)
1910 		goto out;
1911 
1912 	/* Find the mm_struct */
1913 	rcu_read_lock();
1914 	task = pid ? find_task_by_vpid(pid) : current;
1915 	if (!task) {
1916 		rcu_read_unlock();
1917 		err = -ESRCH;
1918 		goto out;
1919 	}
1920 	get_task_struct(task);
1921 
1922 	err = -EINVAL;
1923 
1924 	/*
1925 	 * Check if this process has the right to modify the specified process.
1926 	 * Use the regular "ptrace_may_access()" checks.
1927 	 */
1928 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
1929 		rcu_read_unlock();
1930 		err = -EPERM;
1931 		goto out_put;
1932 	}
1933 	rcu_read_unlock();
1934 
1935 	task_nodes = cpuset_mems_allowed(task);
1936 	/* Is the user allowed to access the target nodes? */
1937 	if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
1938 		err = -EPERM;
1939 		goto out_put;
1940 	}
1941 
1942 	task_nodes = cpuset_mems_allowed(current);
1943 	if (!nodes_and(*new, *new, task_nodes))
1944 		goto out_put;
1945 
1946 	err = security_task_movememory(task);
1947 	if (err)
1948 		goto out_put;
1949 
1950 	mm = get_task_mm(task);
1951 	put_task_struct(task);
1952 
1953 	if (!mm) {
1954 		err = -EINVAL;
1955 		goto out;
1956 	}
1957 
1958 	err = do_migrate_pages(mm, old, new,
1959 		capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
1960 
1961 	mmput(mm);
1962 out:
1963 	NODEMASK_SCRATCH_FREE(scratch);
1964 
1965 	return err;
1966 
1967 out_put:
1968 	put_task_struct(task);
1969 	goto out;
1970 }
1971 
1972 SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
1973 		const unsigned long __user *, old_nodes,
1974 		const unsigned long __user *, new_nodes)
1975 {
1976 	return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes);
1977 }
1978 
1979 /* Retrieve NUMA policy */
1980 static int kernel_get_mempolicy(int __user *policy,
1981 				unsigned long __user *nmask,
1982 				unsigned long maxnode,
1983 				unsigned long addr,
1984 				unsigned long flags)
1985 {
1986 	int err;
1987 	int pval;
1988 	nodemask_t nodes;
1989 
1990 	if (nmask != NULL && maxnode < nr_node_ids)
1991 		return -EINVAL;
1992 
1993 	addr = untagged_addr(addr);
1994 
1995 	err = do_get_mempolicy(&pval, &nodes, addr, flags);
1996 
1997 	if (err)
1998 		return err;
1999 
2000 	if (policy && put_user(pval, policy))
2001 		return -EFAULT;
2002 
2003 	if (nmask)
2004 		err = copy_nodes_to_user(nmask, maxnode, &nodes);
2005 
2006 	return err;
2007 }
2008 
2009 SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
2010 		unsigned long __user *, nmask, unsigned long, maxnode,
2011 		unsigned long, addr, unsigned long, flags)
2012 {
2013 	return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags);
2014 }
2015 
2016 bool vma_migratable(struct vm_area_struct *vma)
2017 {
2018 	if (vma->vm_flags & (VM_IO | VM_PFNMAP))
2019 		return false;
2020 
2021 	/*
2022 	 * DAX device mappings require predictable access latency, so avoid
2023 	 * incurring periodic faults.
2024 	 */
2025 	if (vma_is_dax(vma))
2026 		return false;
2027 
2028 	if (vma_is_hugetlb(vma) &&
2029 		!hugepage_migration_supported(hstate_vma(vma)))
2030 		return false;
2031 
2032 	/*
2033 	 * Migration allocates pages in the highest zone. If we cannot
2034 	 * do so then migration (at least from node to node) is not
2035 	 * possible.
2036 	 */
2037 	if (vma->vm_file &&
2038 		gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping))
2039 			< policy_zone)
2040 		return false;
2041 	return true;
2042 }
2043 
2044 struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
2045 				   unsigned long addr, pgoff_t *ilx)
2046 {
2047 	*ilx = 0;
2048 	return (vma->vm_ops && vma->vm_ops->get_policy) ?
2049 		vma->vm_ops->get_policy(vma, addr, ilx) : vma->vm_policy;
2050 }
2051 
2052 /*
2053  * get_vma_policy(@vma, @addr, @order, @ilx)
2054  * @vma: virtual memory area whose policy is sought
2055  * @addr: address in @vma for shared policy lookup
2056  * @order: 0, or appropriate huge_page_order for interleaving
2057  * @ilx: interleave index (output), for use only when MPOL_INTERLEAVE or
2058  *       MPOL_WEIGHTED_INTERLEAVE
2059  *
2060  * Returns effective policy for a VMA at specified address.
2061  * Falls back to current->mempolicy or system default policy, as necessary.
2062  * Shared policies [those marked as MPOL_F_SHARED] require an extra reference
2063  * count--added by the get_policy() vm_op, as appropriate--to protect against
2064  * freeing by another task.  It is the caller's responsibility to free the
2065  * extra reference for shared policies.
2066  */
2067 struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
2068 				 unsigned long addr, int order, pgoff_t *ilx)
2069 {
2070 	struct mempolicy *pol;
2071 
2072 	pol = __get_vma_policy(vma, addr, ilx);
2073 	if (!pol)
2074 		pol = get_task_policy(current);
2075 	if (pol->mode == MPOL_INTERLEAVE ||
2076 	    pol->mode == MPOL_WEIGHTED_INTERLEAVE) {
2077 		*ilx += vma_start_pgoff(vma) >> order;
2078 		*ilx += linear_page_delta(vma, addr) >> order;
2079 	}
2080 	return pol;
2081 }
2082 
2083 bool vma_policy_mof(struct vm_area_struct *vma)
2084 {
2085 	struct mempolicy *pol;
2086 	pgoff_t ilx;
2087 	bool mof;
2088 
2089 	pol = __get_vma_policy(vma, vma->vm_start, &ilx);
2090 	if (!pol)
2091 		pol = get_task_policy(current);
2092 	mof = pol->flags & MPOL_F_MOF;
2093 	mpol_cond_put(pol);
2094 	return mof;
2095 }
2096 
2097 bool apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
2098 {
2099 	enum zone_type dynamic_policy_zone = policy_zone;
2100 
2101 	BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
2102 
2103 	/*
2104 	 * if policy->nodes has movable memory only,
2105 	 * we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
2106 	 *
2107 	 * policy->nodes is intersect with node_states[N_MEMORY].
2108 	 * so if the following test fails, it implies
2109 	 * policy->nodes has movable memory only.
2110 	 */
2111 	if (!nodes_intersects(policy->nodes, node_states[N_HIGH_MEMORY]))
2112 		dynamic_policy_zone = ZONE_MOVABLE;
2113 
2114 	return zone >= dynamic_policy_zone;
2115 }
2116 
2117 static unsigned int weighted_interleave_nodes(struct mempolicy *policy)
2118 {
2119 	unsigned int node;
2120 	unsigned int cpuset_mems_cookie;
2121 
2122 retry:
2123 	/* to prevent miscount use tsk->mems_allowed_seq to detect rebind */
2124 	cpuset_mems_cookie = read_mems_allowed_begin();
2125 	node = current->il_prev;
2126 	if (!current->il_weight || !node_isset(node, policy->nodes)) {
2127 		node = next_node_in(node, policy->nodes);
2128 		if (read_mems_allowed_retry(cpuset_mems_cookie))
2129 			goto retry;
2130 		if (node == MAX_NUMNODES)
2131 			return node;
2132 		current->il_prev = node;
2133 		current->il_weight = get_il_weight(node);
2134 	}
2135 	current->il_weight--;
2136 	return node;
2137 }
2138 
2139 /* Do dynamic interleaving for a process */
2140 static unsigned int interleave_nodes(struct mempolicy *policy)
2141 {
2142 	unsigned int nid;
2143 	unsigned int cpuset_mems_cookie;
2144 
2145 	/* to prevent miscount, use tsk->mems_allowed_seq to detect rebind */
2146 	do {
2147 		cpuset_mems_cookie = read_mems_allowed_begin();
2148 		nid = next_node_in(current->il_prev, policy->nodes);
2149 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
2150 
2151 	if (nid < MAX_NUMNODES)
2152 		current->il_prev = nid;
2153 	return nid;
2154 }
2155 
2156 /*
2157  * Depending on the memory policy provide a node from which to allocate the
2158  * next slab entry.
2159  */
2160 unsigned int mempolicy_slab_node(void)
2161 {
2162 	struct mempolicy *policy;
2163 	int node = numa_mem_id();
2164 
2165 	if (!in_task())
2166 		return node;
2167 
2168 	policy = current->mempolicy;
2169 	if (!policy)
2170 		return node;
2171 
2172 	switch (policy->mode) {
2173 	case MPOL_PREFERRED:
2174 		return first_node(policy->nodes);
2175 
2176 	case MPOL_INTERLEAVE:
2177 		return interleave_nodes(policy);
2178 
2179 	case MPOL_WEIGHTED_INTERLEAVE:
2180 		return weighted_interleave_nodes(policy);
2181 
2182 	case MPOL_BIND:
2183 	case MPOL_PREFERRED_MANY:
2184 	{
2185 		struct zoneref *z;
2186 		struct zone *zone;
2187 
2188 		/*
2189 		 * Follow bind policy behavior and start allocation at the
2190 		 * first node.
2191 		 */
2192 		struct zonelist *zonelist;
2193 		enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
2194 		zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
2195 		z = first_zones_zonelist(zonelist, highest_zoneidx,
2196 							&policy->nodes);
2197 		zone = zonelist_zone(z);
2198 		return zone ? zone_to_nid(zone) : node;
2199 	}
2200 	case MPOL_LOCAL:
2201 		return node;
2202 
2203 	default:
2204 		BUG();
2205 	}
2206 }
2207 
2208 static unsigned int weighted_interleave_nid(struct mempolicy *pol, pgoff_t ilx)
2209 {
2210 	struct weighted_interleave_state *state;
2211 	unsigned int target, nnodes = 0;
2212 	u8 *table = NULL;
2213 	unsigned int weight_total = 0;
2214 	u8 weight;
2215 	int nid = 0;
2216 
2217 	rcu_read_lock();
2218 
2219 	state = rcu_dereference(wi_state);
2220 	/* Uninitialized wi_state means we should assume all weights are 1 */
2221 	if (state)
2222 		table = state->iw_table;
2223 
2224 	/* calculate the total weight and the node count */
2225 	for_each_node_mask(nid, pol->nodes) {
2226 		weight_total += table ? table[nid] : 1;
2227 		nnodes++;
2228 	}
2229 
2230 	/* the mask is empty */
2231 	if (!weight_total) {
2232 		rcu_read_unlock();
2233 		return numa_node_id();
2234 	}
2235 
2236 	/* Calculate the node offset based on totals */
2237 	target = ilx % weight_total;
2238 	nid = first_node(pol->nodes);
2239 
2240 	/*
2241 	 * The target was calculated in a separate loop, and a concurrent
2242 	 * rebind can change the contents of pol->nodes as we calculate.
2243 	 * Access is safe, in the worst case we suddenly perceive an empty
2244 	 * nodemask and return numa_node_id() below - otherwise we may
2245 	 * simply cause a skew in allocations.
2246 	 *
2247 	 * Clamp this loop to a single pass (nnodes) to keep the walk
2248 	 * bounded by node count.
2249 	 */
2250 	while (target && nnodes-- && nid < MAX_NUMNODES) {
2251 		/* detect system default usage */
2252 		weight = table ? table[nid] : 1;
2253 		if (target < weight)
2254 			break;
2255 		target -= weight;
2256 		nid = next_node_in(nid, pol->nodes);
2257 	}
2258 	rcu_read_unlock();
2259 
2260 	/* the mask emptied under the walk */
2261 	if (nid >= MAX_NUMNODES)
2262 		return numa_node_id();
2263 	return nid;
2264 }
2265 
2266 /*
2267  * Do static interleaving for interleave index @ilx.  Returns the ilx'th
2268  * node in pol->nodes (starting from ilx=0), wrapping around if ilx
2269  * exceeds the number of present nodes.
2270  */
2271 static unsigned int interleave_nid(struct mempolicy *pol, pgoff_t ilx)
2272 {
2273 	unsigned int target, nnodes;
2274 	int i;
2275 	int nid;
2276 
2277 	nnodes = nodes_weight(pol->nodes);
2278 	if (!nnodes)
2279 		return numa_node_id();
2280 	target = ilx % nnodes;
2281 	nid = first_node(pol->nodes);
2282 
2283 	/* A concurrent cpuset rebind may cause us to see an empty nodemask */
2284 	for (i = 0; i < target && nid < MAX_NUMNODES; i++)
2285 		nid = next_node_in(nid, pol->nodes);
2286 
2287 	/* the mask emptied under the walk */
2288 	if (nid >= MAX_NUMNODES)
2289 		return numa_node_id();
2290 	return nid;
2291 }
2292 
2293 /*
2294  * Return a nodemask representing a mempolicy for filtering nodes for
2295  * page allocation, together with preferred node id (or the input node id).
2296  */
2297 static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,
2298 				   pgoff_t ilx, int *nid)
2299 {
2300 	nodemask_t *nodemask = NULL;
2301 
2302 	switch (pol->mode) {
2303 	case MPOL_PREFERRED:
2304 		/* Override input node id */
2305 		*nid = first_node(pol->nodes);
2306 		break;
2307 	case MPOL_PREFERRED_MANY:
2308 		nodemask = &pol->nodes;
2309 		if (pol->home_node != NUMA_NO_NODE)
2310 			*nid = pol->home_node;
2311 		break;
2312 	case MPOL_BIND:
2313 		/* Restrict to nodemask (but not on lower zones) */
2314 		if (apply_policy_zone(pol, gfp_zone(current_gfp_context(gfp))) &&
2315 		    cpuset_nodemask_valid_mems_allowed(&pol->nodes))
2316 			nodemask = &pol->nodes;
2317 		if (pol->home_node != NUMA_NO_NODE)
2318 			*nid = pol->home_node;
2319 		/*
2320 		 * __GFP_THISNODE shouldn't even be used with the bind policy
2321 		 * because we might easily break the expectation to stay on the
2322 		 * requested node and not break the policy.
2323 		 */
2324 		WARN_ON_ONCE(gfp & __GFP_THISNODE);
2325 		break;
2326 	case MPOL_INTERLEAVE:
2327 		/* Override input node id */
2328 		*nid = (ilx == NO_INTERLEAVE_INDEX) ?
2329 			interleave_nodes(pol) : interleave_nid(pol, ilx);
2330 		break;
2331 	case MPOL_WEIGHTED_INTERLEAVE:
2332 		*nid = (ilx == NO_INTERLEAVE_INDEX) ?
2333 			weighted_interleave_nodes(pol) :
2334 			weighted_interleave_nid(pol, ilx);
2335 		break;
2336 	}
2337 
2338 	return nodemask;
2339 }
2340 
2341 #ifdef CONFIG_HUGETLBFS
2342 /*
2343  * huge_node(@vma, @addr, @gfp_flags, @mpol)
2344  * @vma: virtual memory area whose policy is sought
2345  * @addr: address in @vma for shared policy lookup and interleave policy
2346  * @gfp_flags: for requested zone
2347  * @mpol: pointer to mempolicy pointer for reference counted mempolicy
2348  * @nodemask: pointer to nodemask pointer for 'bind' and 'prefer-many' policy
2349  *
2350  * Returns a nid suitable for a huge page allocation and a pointer
2351  * to the struct mempolicy for conditional unref after allocation.
2352  * If the effective policy is 'bind' or 'prefer-many', returns a pointer
2353  * to the mempolicy's @nodemask for filtering the zonelist.
2354  */
2355 int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags,
2356 		struct mempolicy **mpol, nodemask_t **nodemask)
2357 {
2358 	pgoff_t ilx;
2359 	int nid;
2360 
2361 	nid = numa_node_id();
2362 	*mpol = get_vma_policy(vma, addr, hstate_vma(vma)->order, &ilx);
2363 	*nodemask = policy_nodemask(gfp_flags, *mpol, ilx, &nid);
2364 	return nid;
2365 }
2366 
2367 /*
2368  * init_nodemask_of_mempolicy
2369  *
2370  * If the current task's mempolicy is "default" [NULL], return 'false'
2371  * to indicate default policy.  Otherwise, extract the policy nodemask
2372  * for 'bind' or 'interleave' policy into the argument nodemask, or
2373  * initialize the argument nodemask to contain the single node for
2374  * 'preferred' or 'local' policy and return 'true' to indicate presence
2375  * of non-default mempolicy.
2376  *
2377  * We don't bother with reference counting the mempolicy [mpol_get/put]
2378  * because the current task is examining it's own mempolicy and a task's
2379  * mempolicy is only ever changed by the task itself.
2380  *
2381  * N.B., it is the caller's responsibility to free a returned nodemask.
2382  */
2383 bool init_nodemask_of_mempolicy(nodemask_t *mask)
2384 {
2385 	struct mempolicy *mempolicy;
2386 
2387 	if (!(mask && current->mempolicy))
2388 		return false;
2389 
2390 	task_lock(current);
2391 	mempolicy = current->mempolicy;
2392 	switch (mempolicy->mode) {
2393 	case MPOL_PREFERRED:
2394 	case MPOL_PREFERRED_MANY:
2395 	case MPOL_BIND:
2396 	case MPOL_INTERLEAVE:
2397 	case MPOL_WEIGHTED_INTERLEAVE:
2398 		*mask = mempolicy->nodes;
2399 		break;
2400 
2401 	case MPOL_LOCAL:
2402 		init_nodemask_of_node(mask, numa_node_id());
2403 		break;
2404 
2405 	default:
2406 		BUG();
2407 	}
2408 	task_unlock(current);
2409 
2410 	return true;
2411 }
2412 #endif
2413 
2414 /*
2415  * mempolicy_in_oom_domain
2416  *
2417  * If tsk's mempolicy is "bind", check for intersection between mask and
2418  * the policy nodemask. Otherwise, return true for all other policies
2419  * including "interleave", as a tsk with "interleave" policy may have
2420  * memory allocated from all nodes in system.
2421  *
2422  * Takes task_lock(tsk) to prevent freeing of its mempolicy.
2423  */
2424 bool mempolicy_in_oom_domain(struct task_struct *tsk,
2425 					const nodemask_t *mask)
2426 {
2427 	struct mempolicy *mempolicy;
2428 	bool ret = true;
2429 
2430 	if (!mask)
2431 		return ret;
2432 
2433 	task_lock(tsk);
2434 	mempolicy = tsk->mempolicy;
2435 	if (mempolicy && mempolicy->mode == MPOL_BIND)
2436 		ret = nodes_intersects(mempolicy->nodes, *mask);
2437 	task_unlock(tsk);
2438 
2439 	return ret;
2440 }
2441 
2442 static struct page *alloc_pages_preferred_many(gfp_t gfp, unsigned int order,
2443 						int nid, nodemask_t *nodemask)
2444 {
2445 	struct page *page;
2446 	gfp_t preferred_gfp;
2447 
2448 	/*
2449 	 * This is a two pass approach. The first pass will only try the
2450 	 * preferred nodes but skip the direct reclaim and allow the
2451 	 * allocation to fail, while the second pass will try all the
2452 	 * nodes in system.
2453 	 */
2454 	preferred_gfp = gfp | __GFP_NOWARN;
2455 	preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2456 	page = __alloc_frozen_pages_noprof(preferred_gfp, order, nid, nodemask,
2457 					   ALLOC_DEFAULT);
2458 	if (!page)
2459 		page = __alloc_frozen_pages_noprof(gfp, order, nid, NULL,
2460 						   ALLOC_DEFAULT);
2461 
2462 	return page;
2463 }
2464 
2465 /**
2466  * alloc_pages_mpol - Allocate pages according to NUMA mempolicy.
2467  * @gfp: GFP flags.
2468  * @order: Order of the page allocation.
2469  * @pol: Pointer to the NUMA mempolicy.
2470  * @ilx: Index for interleave mempolicy (also distinguishes alloc_pages()).
2471  * @nid: Preferred node (usually numa_node_id() but @mpol may override it).
2472  *
2473  * Return: The page on success or NULL if allocation fails.
2474  */
2475 static struct page *alloc_pages_mpol(gfp_t gfp, unsigned int order,
2476 		struct mempolicy *pol, pgoff_t ilx, int nid)
2477 {
2478 	nodemask_t *nodemask;
2479 	struct page *page;
2480 
2481 	nodemask = policy_nodemask(gfp, pol, ilx, &nid);
2482 
2483 	if (pol->mode == MPOL_PREFERRED_MANY)
2484 		return alloc_pages_preferred_many(gfp, order, nid, nodemask);
2485 
2486 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
2487 	    /* filter "hugepage" allocation, unless from alloc_pages() */
2488 	    is_pmd_order(order) && ilx != NO_INTERLEAVE_INDEX) {
2489 		/*
2490 		 * For hugepage allocation and non-interleave policy which
2491 		 * allows the current node (or other explicitly preferred
2492 		 * node) we only try to allocate from the current/preferred
2493 		 * node and don't fall back to other nodes, as the cost of
2494 		 * remote accesses would likely offset THP benefits.
2495 		 *
2496 		 * If the policy is interleave or does not allow the current
2497 		 * node in its nodemask, we allocate the standard way.
2498 		 */
2499 		if (pol->mode != MPOL_INTERLEAVE &&
2500 		    pol->mode != MPOL_WEIGHTED_INTERLEAVE &&
2501 		    (!nodemask || node_isset(nid, *nodemask))) {
2502 			/*
2503 			 * First, try to allocate THP only on local node, but
2504 			 * don't reclaim unnecessarily, just compact.
2505 			 */
2506 			page = __alloc_frozen_pages_noprof(
2507 				gfp | __GFP_THISNODE | __GFP_NORETRY, order,
2508 				nid, NULL, ALLOC_DEFAULT);
2509 			if (page || !(gfp & __GFP_DIRECT_RECLAIM))
2510 				return page;
2511 			/*
2512 			 * If hugepage allocations are configured to always
2513 			 * synchronous compact or the vma has been madvised
2514 			 * to prefer hugepage backing, retry allowing remote
2515 			 * memory with both reclaim and compact as well.
2516 			 */
2517 		}
2518 	}
2519 
2520 	page = __alloc_frozen_pages_noprof(gfp, order, nid, nodemask, ALLOC_DEFAULT);
2521 
2522 	if (unlikely(pol->mode == MPOL_INTERLEAVE ||
2523 		     pol->mode == MPOL_WEIGHTED_INTERLEAVE) && page) {
2524 		/* skip NUMA_INTERLEAVE_HIT update if numa stats is disabled */
2525 		if (static_branch_likely(&vm_numa_stat_key) &&
2526 		    page_to_nid(page) == nid) {
2527 			preempt_disable();
2528 			__count_numa_event(page_zone(page), NUMA_INTERLEAVE_HIT);
2529 			preempt_enable();
2530 		}
2531 	}
2532 
2533 	return page;
2534 }
2535 
2536 struct folio *folio_alloc_mpol_noprof(gfp_t gfp, unsigned int order,
2537 		struct mempolicy *pol, pgoff_t ilx, int nid)
2538 {
2539 	struct page *page = alloc_pages_mpol(gfp | __GFP_COMP, order, pol,
2540 			ilx, nid);
2541 	if (!page)
2542 		return NULL;
2543 
2544 	set_page_refcounted(page);
2545 	return page_rmappable_folio(page);
2546 }
2547 
2548 /**
2549  * vma_alloc_folio - Allocate a folio for a VMA.
2550  * @gfp: GFP flags.
2551  * @order: Order of the folio.
2552  * @vma: Pointer to VMA.
2553  * @addr: Virtual address of the allocation.  Must be inside @vma.
2554  *
2555  * Allocate a folio for a specific address in @vma, using the appropriate
2556  * NUMA policy.  The caller must hold the mmap_lock of the mm_struct of the
2557  * VMA to prevent it from going away.  Should be used for all allocations
2558  * for folios that will be mapped into user space, excepting hugetlbfs, and
2559  * excepting where direct use of folio_alloc_mpol() is more appropriate.
2560  *
2561  * Return: The folio on success or NULL if allocation fails.
2562  */
2563 struct folio *vma_alloc_folio_noprof(gfp_t gfp, int order, struct vm_area_struct *vma,
2564 		unsigned long addr)
2565 {
2566 	struct mempolicy *pol;
2567 	pgoff_t ilx;
2568 	struct folio *folio;
2569 
2570 	if (vma->vm_flags & VM_DROPPABLE)
2571 		gfp |= __GFP_NOWARN;
2572 
2573 	pol = get_vma_policy(vma, addr, order, &ilx);
2574 	folio = folio_alloc_mpol_noprof(gfp, order, pol, ilx, numa_node_id());
2575 	mpol_cond_put(pol);
2576 	return folio;
2577 }
2578 EXPORT_SYMBOL(vma_alloc_folio_noprof);
2579 
2580 struct page *alloc_frozen_pages_noprof(gfp_t gfp, unsigned order)
2581 {
2582 	struct mempolicy *pol = &default_policy;
2583 
2584 	/*
2585 	 * No reference counting needed for current->mempolicy
2586 	 * nor system default_policy
2587 	 */
2588 	if (!in_interrupt() && !(gfp & __GFP_THISNODE))
2589 		pol = get_task_policy(current);
2590 
2591 	return alloc_pages_mpol(gfp, order, pol, NO_INTERLEAVE_INDEX,
2592 				       numa_node_id());
2593 }
2594 
2595 /**
2596  * alloc_pages - Allocate pages.
2597  * @gfp: GFP flags.
2598  * @order: Power of two of number of pages to allocate.
2599  *
2600  * Allocate 1 << @order contiguous pages.  The physical address of the
2601  * first page is naturally aligned (eg an order-3 allocation will be aligned
2602  * to a multiple of 8 * PAGE_SIZE bytes).  The NUMA policy of the current
2603  * process is honoured when in process context.
2604  *
2605  * Context: Can be called from any context, providing the appropriate GFP
2606  * flags are used.
2607  * Return: The page on success or NULL if allocation fails.
2608  */
2609 struct page *alloc_pages_noprof(gfp_t gfp, unsigned int order)
2610 {
2611 	struct page *page = alloc_frozen_pages_noprof(gfp, order);
2612 
2613 	if (page)
2614 		set_page_refcounted(page);
2615 	return page;
2616 }
2617 EXPORT_SYMBOL(alloc_pages_noprof);
2618 
2619 struct folio *folio_alloc_noprof(gfp_t gfp, unsigned int order)
2620 {
2621 	return page_rmappable_folio(alloc_pages_noprof(gfp | __GFP_COMP, order));
2622 }
2623 EXPORT_SYMBOL(folio_alloc_noprof);
2624 
2625 static unsigned long alloc_pages_bulk_interleave(gfp_t gfp,
2626 		struct mempolicy *pol, unsigned long nr_pages,
2627 		struct page **page_array)
2628 {
2629 	unsigned int cpuset_mems_cookie;
2630 	int nodes;
2631 	unsigned long nr_pages_per_node;
2632 	int delta;
2633 	int i;
2634 	unsigned long nr_allocated;
2635 	unsigned long total_allocated = 0;
2636 
2637 	/* count the nodes, retry if a rebind happened during the read */
2638 	do {
2639 		cpuset_mems_cookie = read_mems_allowed_begin();
2640 		nodes = nodes_weight(pol->nodes);
2641 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
2642 
2643 	/* if the nodemask has become invalid, we cannot do anything */
2644 	if (!nodes)
2645 		return 0;
2646 
2647 	nr_pages_per_node = nr_pages / nodes;
2648 	delta = nr_pages - nodes * nr_pages_per_node;
2649 
2650 	for (i = 0; i < nodes; i++) {
2651 		if (delta) {
2652 			nr_allocated = alloc_pages_bulk_noprof(gfp,
2653 					interleave_nodes(pol), NULL,
2654 					nr_pages_per_node + 1,
2655 					page_array);
2656 			delta--;
2657 		} else {
2658 			nr_allocated = alloc_pages_bulk_noprof(gfp,
2659 					interleave_nodes(pol), NULL,
2660 					nr_pages_per_node, page_array);
2661 		}
2662 
2663 		page_array += nr_allocated;
2664 		total_allocated += nr_allocated;
2665 	}
2666 
2667 	return total_allocated;
2668 }
2669 
2670 static unsigned long alloc_pages_bulk_weighted_interleave(gfp_t gfp,
2671 		struct mempolicy *pol, unsigned long nr_pages,
2672 		struct page **page_array)
2673 {
2674 	struct weighted_interleave_state *state;
2675 	struct task_struct *me = current;
2676 	unsigned int cpuset_mems_cookie;
2677 	unsigned long total_allocated = 0;
2678 	unsigned long nr_allocated = 0;
2679 	unsigned long rounds;
2680 	unsigned long node_pages, delta;
2681 	struct srcu_ctr __percpu *scp;
2682 	u8 *table, weight;
2683 	unsigned int weight_total = 0;
2684 	unsigned long rem_pages = nr_pages;
2685 	int nnodes, node;
2686 	int resume_node = MAX_NUMNODES - 1;
2687 	u8 resume_weight = 0;
2688 	int prev_node;
2689 	int i;
2690 
2691 	if (!nr_pages)
2692 		return 0;
2693 
2694 	/* count the nodes, retry if a rebind happened during the read */
2695 	do {
2696 		cpuset_mems_cookie = read_mems_allowed_begin();
2697 		nnodes = nodes_weight(pol->nodes);
2698 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
2699 
2700 	/* if the nodemask has become invalid, we cannot do anything */
2701 	if (!nnodes)
2702 		return 0;
2703 
2704 	/* Continue allocating from most recent node and adjust the nr_pages */
2705 	node = me->il_prev;
2706 	weight = me->il_weight;
2707 	if (weight && node_isset(node, pol->nodes)) {
2708 		node_pages = min(rem_pages, weight);
2709 		nr_allocated = __alloc_pages_bulk(gfp, node, NULL, node_pages,
2710 						  page_array);
2711 		page_array += nr_allocated;
2712 		total_allocated += nr_allocated;
2713 		/* if that's all the pages, no need to interleave */
2714 		if (rem_pages <= weight) {
2715 			me->il_weight -= rem_pages;
2716 			return total_allocated;
2717 		}
2718 		/* Otherwise we adjust remaining pages, continue from there */
2719 		rem_pages -= weight;
2720 	}
2721 	/* clear active weight in case of an allocation failure */
2722 	me->il_weight = 0;
2723 	prev_node = node;
2724 
2725 	/* The page allocator may sleep, pin the weight table with SRCU */
2726 	scp = srcu_read_lock_fast(&wi_srcu);
2727 	state = srcu_dereference(wi_state, &wi_srcu);
2728 	table = state ? state->iw_table : NULL;
2729 
2730 	/* calculate total, detect system default usage */
2731 	for_each_node_mask(node, pol->nodes)
2732 		weight_total += table ? table[node] : 1;
2733 
2734 	/* the mask emptied since it was counted */
2735 	if (!weight_total)
2736 		goto out;
2737 
2738 	/*
2739 	 * Calculate rounds/partial rounds to minimize __alloc_pages_bulk calls.
2740 	 * Track which node weighted interleave should resume from.
2741 	 *
2742 	 * if (rounds > 0) and (delta == 0), resume_node will always be
2743 	 * the node following prev_node and its weight.
2744 	 */
2745 	rounds = rem_pages / weight_total;
2746 	delta = rem_pages % weight_total;
2747 	resume_node = next_node_in(prev_node, pol->nodes);
2748 	if (resume_node >= MAX_NUMNODES)
2749 		goto out;
2750 	resume_weight = table ? table[resume_node] : 1;
2751 	for (i = 0; i < nnodes; i++) {
2752 		node = next_node_in(prev_node, pol->nodes);
2753 		if (node >= MAX_NUMNODES)
2754 			break;
2755 		weight = table ? table[node] : 1;
2756 		node_pages = weight * rounds;
2757 		/* If a delta exists, add this node's portion of the delta */
2758 		if (delta > weight) {
2759 			node_pages += weight;
2760 			delta -= weight;
2761 		} else if (delta) {
2762 			/* when delta is depleted, resume from that node */
2763 			node_pages += delta;
2764 			resume_node = node;
2765 			resume_weight = weight - delta;
2766 			delta = 0;
2767 		}
2768 		/* node_pages can be 0 if an allocation fails and rounds == 0 */
2769 		if (!node_pages)
2770 			break;
2771 		/* a rebind can invalidate the counts: never overrun page_array */
2772 		node_pages = min(node_pages, nr_pages - total_allocated);
2773 		nr_allocated = __alloc_pages_bulk(gfp, node, NULL, node_pages,
2774 						  page_array);
2775 		page_array += nr_allocated;
2776 		total_allocated += nr_allocated;
2777 		if (total_allocated == nr_pages)
2778 			break;
2779 		prev_node = node;
2780 	}
2781 	me->il_prev = resume_node;
2782 	me->il_weight = resume_weight;
2783 out:
2784 	srcu_read_unlock_fast(&wi_srcu, scp);
2785 	return total_allocated;
2786 }
2787 
2788 static unsigned long alloc_pages_bulk_preferred_many(gfp_t gfp, int nid,
2789 		struct mempolicy *pol, unsigned long nr_pages,
2790 		struct page **page_array)
2791 {
2792 	gfp_t preferred_gfp;
2793 	unsigned long nr_allocated = 0;
2794 
2795 	preferred_gfp = gfp | __GFP_NOWARN;
2796 	preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2797 
2798 	nr_allocated  = alloc_pages_bulk_noprof(preferred_gfp, nid, &pol->nodes,
2799 					   nr_pages, page_array);
2800 
2801 	if (nr_allocated < nr_pages)
2802 		nr_allocated += alloc_pages_bulk_noprof(gfp, numa_node_id(), NULL,
2803 				nr_pages - nr_allocated,
2804 				page_array + nr_allocated);
2805 	return nr_allocated;
2806 }
2807 
2808 /* alloc pages bulk and mempolicy should be considered at the
2809  * same time in some situation such as vmalloc.
2810  *
2811  * It can accelerate memory allocation especially interleaving
2812  * allocate memory.
2813  */
2814 unsigned long alloc_pages_bulk_mempolicy_noprof(gfp_t gfp,
2815 		unsigned long nr_pages, struct page **page_array)
2816 {
2817 	struct mempolicy *pol = &default_policy;
2818 	nodemask_t *nodemask;
2819 	int nid;
2820 
2821 	if (!in_interrupt() && !(gfp & __GFP_THISNODE))
2822 		pol = get_task_policy(current);
2823 
2824 	if (pol->mode == MPOL_INTERLEAVE)
2825 		return alloc_pages_bulk_interleave(gfp, pol,
2826 							 nr_pages, page_array);
2827 
2828 	if (pol->mode == MPOL_WEIGHTED_INTERLEAVE)
2829 		return alloc_pages_bulk_weighted_interleave(
2830 				  gfp, pol, nr_pages, page_array);
2831 
2832 	if (pol->mode == MPOL_PREFERRED_MANY)
2833 		return alloc_pages_bulk_preferred_many(gfp,
2834 				numa_node_id(), pol, nr_pages, page_array);
2835 
2836 	nid = numa_node_id();
2837 	nodemask = policy_nodemask(gfp, pol, NO_INTERLEAVE_INDEX, &nid);
2838 	return alloc_pages_bulk_noprof(gfp, nid, nodemask,
2839 				       nr_pages, page_array);
2840 }
2841 
2842 int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
2843 {
2844 	struct mempolicy *pol = mpol_dup(src->vm_policy);
2845 
2846 	if (IS_ERR(pol))
2847 		return PTR_ERR(pol);
2848 	dst->vm_policy = pol;
2849 	return 0;
2850 }
2851 
2852 /*
2853  * If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
2854  * rebinds the mempolicy its copying by calling mpol_rebind_policy()
2855  * with the mems_allowed returned by cpuset_mems_allowed().  This
2856  * keeps mempolicies cpuset relative after its cpuset moves.  See
2857  * further kernel/cpuset.c update_nodemask().
2858  *
2859  * current's mempolicy may be rebinded by the other task(the task that changes
2860  * cpuset's mems), so we needn't do rebind work for current task.
2861  */
2862 
2863 /* Slow path of a mempolicy duplicate */
2864 struct mempolicy *__mpol_dup(struct mempolicy *old)
2865 {
2866 	struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
2867 
2868 	if (!new)
2869 		return ERR_PTR(-ENOMEM);
2870 
2871 	/* task's mempolicy is protected by alloc_lock */
2872 	if (old == current->mempolicy) {
2873 		task_lock(current);
2874 		*new = *old;
2875 		task_unlock(current);
2876 	} else
2877 		*new = *old;
2878 
2879 	if (current_cpuset_is_being_rebound()) {
2880 		nodemask_t mems = cpuset_mems_allowed(current);
2881 		mpol_rebind_policy(new, &mems);
2882 	}
2883 	atomic_set(&new->refcnt, 1);
2884 	return new;
2885 }
2886 
2887 /* Slow path of a mempolicy comparison */
2888 bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
2889 {
2890 	if (!a || !b)
2891 		return false;
2892 	if (a->mode != b->mode)
2893 		return false;
2894 	if (a->flags != b->flags)
2895 		return false;
2896 	if (a->home_node != b->home_node)
2897 		return false;
2898 	if (mpol_store_user_nodemask(a))
2899 		if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
2900 			return false;
2901 
2902 	switch (a->mode) {
2903 	case MPOL_BIND:
2904 	case MPOL_INTERLEAVE:
2905 	case MPOL_PREFERRED:
2906 	case MPOL_PREFERRED_MANY:
2907 	case MPOL_WEIGHTED_INTERLEAVE:
2908 		return nodes_equal(a->nodes, b->nodes);
2909 	case MPOL_LOCAL:
2910 		return true;
2911 	default:
2912 		BUG();
2913 		return false;
2914 	}
2915 }
2916 
2917 /*
2918  * Shared memory backing store policy support.
2919  *
2920  * Remember policies even when nobody has shared memory mapped.
2921  * The policies are kept in Red-Black tree linked from the inode.
2922  * They are protected by the sp->lock rwlock, which should be held
2923  * for any accesses to the tree.
2924  */
2925 
2926 /*
2927  * lookup first element intersecting start-end.  Caller holds sp->lock for
2928  * reading or for writing
2929  */
2930 static struct sp_node *sp_lookup(struct shared_policy *sp,
2931 					pgoff_t start, pgoff_t end)
2932 {
2933 	struct rb_node *n = sp->root.rb_node;
2934 
2935 	while (n) {
2936 		struct sp_node *p = rb_entry(n, struct sp_node, nd);
2937 
2938 		if (start >= p->end)
2939 			n = n->rb_right;
2940 		else if (end <= p->start)
2941 			n = n->rb_left;
2942 		else
2943 			break;
2944 	}
2945 	if (!n)
2946 		return NULL;
2947 	for (;;) {
2948 		struct sp_node *w = NULL;
2949 		struct rb_node *prev = rb_prev(n);
2950 		if (!prev)
2951 			break;
2952 		w = rb_entry(prev, struct sp_node, nd);
2953 		if (w->end <= start)
2954 			break;
2955 		n = prev;
2956 	}
2957 	return rb_entry(n, struct sp_node, nd);
2958 }
2959 
2960 /*
2961  * Insert a new shared policy into the list.  Caller holds sp->lock for
2962  * writing.
2963  */
2964 static void sp_insert(struct shared_policy *sp, struct sp_node *new)
2965 {
2966 	struct rb_node **p = &sp->root.rb_node;
2967 	struct rb_node *parent = NULL;
2968 	struct sp_node *nd;
2969 
2970 	while (*p) {
2971 		parent = *p;
2972 		nd = rb_entry(parent, struct sp_node, nd);
2973 		if (new->start < nd->start)
2974 			p = &(*p)->rb_left;
2975 		else if (new->end > nd->end)
2976 			p = &(*p)->rb_right;
2977 		else
2978 			BUG();
2979 	}
2980 	rb_link_node(&new->nd, parent, p);
2981 	rb_insert_color(&new->nd, &sp->root);
2982 }
2983 
2984 /* Find shared policy intersecting idx */
2985 struct mempolicy *mpol_shared_policy_lookup(struct shared_policy *sp,
2986 						pgoff_t idx)
2987 {
2988 	struct mempolicy *pol = NULL;
2989 	struct sp_node *sn;
2990 
2991 	if (!sp->root.rb_node)
2992 		return NULL;
2993 	read_lock(&sp->lock);
2994 	sn = sp_lookup(sp, idx, idx+1);
2995 	if (sn) {
2996 		mpol_get(sn->policy);
2997 		pol = sn->policy;
2998 	}
2999 	read_unlock(&sp->lock);
3000 	return pol;
3001 }
3002 EXPORT_SYMBOL_FOR_MODULES(mpol_shared_policy_lookup, "kvm");
3003 
3004 static void sp_free(struct sp_node *n)
3005 {
3006 	mpol_put(n->policy);
3007 	kmem_cache_free(sn_cache, n);
3008 }
3009 
3010 /**
3011  * mpol_misplaced - check whether current folio node is valid in policy
3012  *
3013  * @folio: folio to be checked
3014  * @vmf: structure describing the fault
3015  * @addr: virtual address in @vma for shared policy lookup and interleave policy
3016  *
3017  * Lookup current policy node id for vma,addr and "compare to" folio's
3018  * node id.  Policy determination "mimics" alloc_page_vma().
3019  * Called from fault path where we know the vma and faulting address.
3020  *
3021  * Return: NUMA_NO_NODE if the page is in a node that is valid for this
3022  * policy, or a suitable node ID to allocate a replacement folio from.
3023  */
3024 int mpol_misplaced(struct folio *folio, struct vm_fault *vmf,
3025 		   unsigned long addr)
3026 {
3027 	struct mempolicy *pol;
3028 	pgoff_t ilx;
3029 	struct zoneref *z;
3030 	int curnid = folio_nid(folio);
3031 	struct vm_area_struct *vma = vmf->vma;
3032 	int thiscpu = raw_smp_processor_id();
3033 	int thisnid = numa_node_id();
3034 	int polnid = NUMA_NO_NODE;
3035 	int ret = NUMA_NO_NODE;
3036 
3037 	/*
3038 	 * Make sure ptl is held so that we don't preempt and we
3039 	 * have a stable smp processor id
3040 	 */
3041 	lockdep_assert_held(vmf->ptl);
3042 	pol = get_vma_policy(vma, addr, folio_order(folio), &ilx);
3043 	if (!(pol->flags & MPOL_F_MOF))
3044 		goto out;
3045 
3046 	switch (pol->mode) {
3047 	case MPOL_INTERLEAVE:
3048 		polnid = interleave_nid(pol, ilx);
3049 		break;
3050 
3051 	case MPOL_WEIGHTED_INTERLEAVE:
3052 		polnid = weighted_interleave_nid(pol, ilx);
3053 		break;
3054 
3055 	case MPOL_PREFERRED:
3056 		if (node_isset(curnid, pol->nodes))
3057 			goto out;
3058 		polnid = first_node(pol->nodes);
3059 		break;
3060 
3061 	case MPOL_LOCAL:
3062 		polnid = numa_node_id();
3063 		break;
3064 
3065 	case MPOL_BIND:
3066 	case MPOL_PREFERRED_MANY:
3067 		/*
3068 		 * Even though MPOL_PREFERRED_MANY can allocate pages outside
3069 		 * policy nodemask we don't allow numa migration to nodes
3070 		 * outside policy nodemask for now. This is done so that if we
3071 		 * want demotion to slow memory to happen, before allocating
3072 		 * from some DRAM node say 'x', we will end up using a
3073 		 * MPOL_PREFERRED_MANY mask excluding node 'x'. In such scenario
3074 		 * we should not promote to node 'x' from slow memory node.
3075 		 */
3076 		if (pol->flags & MPOL_F_MORON) {
3077 			/*
3078 			 * Optimize placement among multiple nodes
3079 			 * via NUMA balancing
3080 			 */
3081 			if (node_isset(thisnid, pol->nodes))
3082 				break;
3083 			goto out;
3084 		}
3085 
3086 		/*
3087 		 * use current page if in policy nodemask,
3088 		 * else select nearest allowed node, if any.
3089 		 * If no allowed nodes, use current [!misplaced].
3090 		 */
3091 		if (node_isset(curnid, pol->nodes))
3092 			goto out;
3093 		z = first_zones_zonelist(
3094 				node_zonelist(thisnid, GFP_HIGHUSER),
3095 				gfp_zone(GFP_HIGHUSER),
3096 				&pol->nodes);
3097 		polnid = zone_to_nid(zonelist_zone(z));
3098 		break;
3099 
3100 	default:
3101 		BUG();
3102 	}
3103 
3104 	/* Migrate the folio towards the node whose CPU is referencing it */
3105 	if (pol->flags & MPOL_F_MORON) {
3106 		polnid = thisnid;
3107 
3108 		if (!should_numa_migrate_memory(current, folio, curnid,
3109 						thiscpu))
3110 			goto out;
3111 	}
3112 
3113 	if (curnid != polnid)
3114 		ret = polnid;
3115 out:
3116 	mpol_cond_put(pol);
3117 
3118 	return ret;
3119 }
3120 
3121 /*
3122  * Drop the (possibly final) reference to task->mempolicy.  It needs to be
3123  * dropped after task->mempolicy is set to NULL so that any allocation done as
3124  * part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
3125  * policy.
3126  */
3127 void mpol_put_task_policy(struct task_struct *task)
3128 {
3129 	struct mempolicy *pol;
3130 
3131 	task_lock(task);
3132 	pol = task->mempolicy;
3133 	task->mempolicy = NULL;
3134 	task_unlock(task);
3135 	mpol_put(pol);
3136 }
3137 
3138 static void sp_delete(struct shared_policy *sp, struct sp_node *n)
3139 {
3140 	rb_erase(&n->nd, &sp->root);
3141 	sp_free(n);
3142 }
3143 
3144 static void sp_node_init(struct sp_node *node, unsigned long start,
3145 			unsigned long end, struct mempolicy *pol)
3146 {
3147 	node->start = start;
3148 	node->end = end;
3149 	node->policy = pol;
3150 }
3151 
3152 static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
3153 				struct mempolicy *pol)
3154 {
3155 	struct sp_node *n;
3156 	struct mempolicy *newpol;
3157 
3158 	n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
3159 	if (!n)
3160 		return NULL;
3161 
3162 	newpol = mpol_dup(pol);
3163 	if (IS_ERR(newpol)) {
3164 		kmem_cache_free(sn_cache, n);
3165 		return NULL;
3166 	}
3167 	newpol->flags |= MPOL_F_SHARED;
3168 	sp_node_init(n, start, end, newpol);
3169 
3170 	return n;
3171 }
3172 
3173 /* Replace a policy range. */
3174 static int shared_policy_replace(struct shared_policy *sp, pgoff_t start,
3175 				 pgoff_t end, struct sp_node *new)
3176 {
3177 	struct sp_node *n;
3178 	struct sp_node *n_new = NULL;
3179 	struct mempolicy *mpol_new = NULL;
3180 	int ret = 0;
3181 
3182 restart:
3183 	write_lock(&sp->lock);
3184 	n = sp_lookup(sp, start, end);
3185 	/* Take care of old policies in the same range. */
3186 	while (n && n->start < end) {
3187 		struct rb_node *next = rb_next(&n->nd);
3188 		if (n->start >= start) {
3189 			if (n->end <= end)
3190 				sp_delete(sp, n);
3191 			else
3192 				n->start = end;
3193 		} else {
3194 			/* Old policy spanning whole new range. */
3195 			if (n->end > end) {
3196 				if (!n_new)
3197 					goto alloc_new;
3198 
3199 				*mpol_new = *n->policy;
3200 				atomic_set(&mpol_new->refcnt, 1);
3201 				sp_node_init(n_new, end, n->end, mpol_new);
3202 				n->end = start;
3203 				sp_insert(sp, n_new);
3204 				n_new = NULL;
3205 				mpol_new = NULL;
3206 				break;
3207 			} else
3208 				n->end = start;
3209 		}
3210 		if (!next)
3211 			break;
3212 		n = rb_entry(next, struct sp_node, nd);
3213 	}
3214 	if (new)
3215 		sp_insert(sp, new);
3216 	write_unlock(&sp->lock);
3217 	ret = 0;
3218 
3219 err_out:
3220 	if (mpol_new)
3221 		mpol_put(mpol_new);
3222 	if (n_new)
3223 		kmem_cache_free(sn_cache, n_new);
3224 
3225 	return ret;
3226 
3227 alloc_new:
3228 	write_unlock(&sp->lock);
3229 	ret = -ENOMEM;
3230 	n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
3231 	if (!n_new)
3232 		goto err_out;
3233 	mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
3234 	if (!mpol_new)
3235 		goto err_out;
3236 	atomic_set(&mpol_new->refcnt, 1);
3237 	goto restart;
3238 }
3239 
3240 /**
3241  * mpol_shared_policy_init - initialize shared policy for inode
3242  * @sp: pointer to inode shared policy
3243  * @mpol:  struct mempolicy to install
3244  *
3245  * Install non-NULL @mpol in inode's shared policy rb-tree.
3246  * On entry, the current task has a reference on a non-NULL @mpol.
3247  * This must be released on exit.
3248  * This is called at get_inode() calls and we can use GFP_KERNEL.
3249  */
3250 void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
3251 {
3252 	int ret;
3253 
3254 	sp->root = RB_ROOT;		/* empty tree == default mempolicy */
3255 	rwlock_init(&sp->lock);
3256 
3257 	if (mpol) {
3258 		struct sp_node *sn;
3259 		struct mempolicy *npol;
3260 		NODEMASK_SCRATCH(scratch);
3261 
3262 		if (!scratch)
3263 			goto put_mpol;
3264 
3265 		/* contextualize the tmpfs mount point mempolicy to this file */
3266 		npol = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
3267 		if (IS_ERR(npol))
3268 			goto free_scratch; /* no valid nodemask intersection */
3269 
3270 		task_lock(current);
3271 		ret = mpol_set_nodemask(npol, &mpol->w.user_nodemask, scratch);
3272 		task_unlock(current);
3273 		if (ret)
3274 			goto put_npol;
3275 
3276 		/* alloc node covering entire file; adds ref to file's npol */
3277 		sn = sp_alloc(0, MAX_LFS_FILESIZE >> PAGE_SHIFT, npol);
3278 		if (sn)
3279 			sp_insert(sp, sn);
3280 put_npol:
3281 		mpol_put(npol);	/* drop initial ref on file's npol */
3282 free_scratch:
3283 		NODEMASK_SCRATCH_FREE(scratch);
3284 put_mpol:
3285 		mpol_put(mpol);	/* drop our incoming ref on sb mpol */
3286 	}
3287 }
3288 EXPORT_SYMBOL_FOR_MODULES(mpol_shared_policy_init, "kvm");
3289 
3290 int mpol_set_shared_policy(struct shared_policy *sp,
3291 			struct vm_area_struct *vma, struct mempolicy *pol)
3292 {
3293 	const pgoff_t pgoff = vma_start_pgoff(vma);
3294 	const pgoff_t pgoff_end = vma_end_pgoff(vma);
3295 	struct sp_node *new = NULL;
3296 	int err;
3297 
3298 	if (pol) {
3299 		new = sp_alloc(pgoff, pgoff_end, pol);
3300 		if (!new)
3301 			return -ENOMEM;
3302 	}
3303 	err = shared_policy_replace(sp, pgoff, pgoff_end, new);
3304 	if (err && new)
3305 		sp_free(new);
3306 	return err;
3307 }
3308 EXPORT_SYMBOL_FOR_MODULES(mpol_set_shared_policy, "kvm");
3309 
3310 /* Free a backing policy store on inode delete. */
3311 void mpol_free_shared_policy(struct shared_policy *sp)
3312 {
3313 	struct sp_node *n;
3314 	struct rb_node *next;
3315 
3316 	if (!sp->root.rb_node)
3317 		return;
3318 	write_lock(&sp->lock);
3319 	next = rb_first(&sp->root);
3320 	while (next) {
3321 		n = rb_entry(next, struct sp_node, nd);
3322 		next = rb_next(&n->nd);
3323 		sp_delete(sp, n);
3324 	}
3325 	write_unlock(&sp->lock);
3326 }
3327 EXPORT_SYMBOL_FOR_MODULES(mpol_free_shared_policy, "kvm");
3328 
3329 #ifdef CONFIG_NUMA_BALANCING
3330 static int __initdata numabalancing_override;
3331 
3332 static void __init check_numabalancing_enable(void)
3333 {
3334 	bool numabalancing_default = false;
3335 
3336 	if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
3337 		numabalancing_default = true;
3338 
3339 	/* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
3340 	if (numabalancing_override)
3341 		set_numabalancing_state(numabalancing_override == 1);
3342 
3343 	if (num_online_nodes() > 1 && !numabalancing_override) {
3344 		pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
3345 			numabalancing_default ? "Enabling" : "Disabling");
3346 		set_numabalancing_state(numabalancing_default);
3347 	}
3348 }
3349 
3350 static int __init setup_numabalancing(char *str)
3351 {
3352 	int ret = 0;
3353 	if (!str)
3354 		goto out;
3355 
3356 	if (!strcmp(str, "enable")) {
3357 		numabalancing_override = 1;
3358 		ret = 1;
3359 	} else if (!strcmp(str, "disable")) {
3360 		numabalancing_override = -1;
3361 		ret = 1;
3362 	}
3363 out:
3364 	if (!ret)
3365 		pr_warn("Unable to parse numa_balancing=\n");
3366 
3367 	return ret;
3368 }
3369 __setup("numa_balancing=", setup_numabalancing);
3370 #else
3371 static inline void __init check_numabalancing_enable(void)
3372 {
3373 }
3374 #endif /* CONFIG_NUMA_BALANCING */
3375 
3376 void __init numa_policy_init(void)
3377 {
3378 	nodemask_t interleave_nodes;
3379 	unsigned long largest = 0;
3380 	int nid, prefer = 0;
3381 
3382 	policy_cache = kmem_cache_create("numa_policy",
3383 					 sizeof(struct mempolicy),
3384 					 0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
3385 
3386 	sn_cache = kmem_cache_create("shared_policy_node",
3387 				     sizeof(struct sp_node),
3388 				     0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
3389 
3390 	for_each_node(nid) {
3391 		preferred_node_policy[nid] = (struct mempolicy) {
3392 			.refcnt = ATOMIC_INIT(1),
3393 			.mode = MPOL_PREFERRED,
3394 			.flags = MPOL_F_MOF | MPOL_F_MORON,
3395 			.nodes = nodemask_of_node(nid),
3396 		};
3397 	}
3398 
3399 	/*
3400 	 * Set interleaving policy for system init. Interleaving is only
3401 	 * enabled across suitably sized nodes (default is >= 16MB), or
3402 	 * fall back to the largest node if they're all smaller.
3403 	 */
3404 	nodes_clear(interleave_nodes);
3405 	for_each_node_state(nid, N_MEMORY) {
3406 		unsigned long total_pages = node_present_pages(nid);
3407 
3408 		/* Preserve the largest node */
3409 		if (largest < total_pages) {
3410 			largest = total_pages;
3411 			prefer = nid;
3412 		}
3413 
3414 		/* Interleave this node? */
3415 		if ((total_pages << PAGE_SHIFT) >= (16 << 20))
3416 			node_set(nid, interleave_nodes);
3417 	}
3418 
3419 	/* All too small, use the largest */
3420 	if (unlikely(nodes_empty(interleave_nodes)))
3421 		node_set(prefer, interleave_nodes);
3422 
3423 	if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
3424 		pr_err("%s: interleaving failed\n", __func__);
3425 
3426 	check_numabalancing_enable();
3427 }
3428 
3429 /* Reset policy of current process to default */
3430 void numa_default_policy(void)
3431 {
3432 	do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
3433 }
3434 
3435 /*
3436  * Parse and format mempolicy from/to strings
3437  */
3438 static const char * const policy_modes[] =
3439 {
3440 	[MPOL_DEFAULT]    = "default",
3441 	[MPOL_PREFERRED]  = "prefer",
3442 	[MPOL_BIND]       = "bind",
3443 	[MPOL_INTERLEAVE] = "interleave",
3444 	[MPOL_WEIGHTED_INTERLEAVE] = "weighted interleave",
3445 	[MPOL_LOCAL]      = "local",
3446 	[MPOL_PREFERRED_MANY]  = "prefer (many)",
3447 };
3448 
3449 #ifdef CONFIG_TMPFS
3450 /**
3451  * mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
3452  * @str:  string containing mempolicy to parse
3453  * @mpol:  pointer to struct mempolicy pointer, returned on success.
3454  *
3455  * Format of input:
3456  *	<mode>[=<flags>][:<nodelist>]
3457  *
3458  * Return: %0 on success, else %1
3459  */
3460 int mpol_parse_str(char *str, struct mempolicy **mpol)
3461 {
3462 	struct mempolicy *new = NULL;
3463 	unsigned short mode_flags;
3464 	nodemask_t nodes;
3465 	char *nodelist = strchr(str, ':');
3466 	char *flags = strchr(str, '=');
3467 	int err = 1, mode;
3468 
3469 	if (flags)
3470 		*flags++ = '\0';	/* terminate mode string */
3471 
3472 	if (nodelist) {
3473 		/* NUL-terminate mode or flags string */
3474 		*nodelist++ = '\0';
3475 		if (nodelist_parse(nodelist, nodes))
3476 			goto out;
3477 		if (!nodes_subset(nodes, node_states[N_MEMORY]))
3478 			goto out;
3479 	} else
3480 		nodes_clear(nodes);
3481 
3482 	mode = match_string(policy_modes, MPOL_MAX, str);
3483 	if (mode < 0)
3484 		goto out;
3485 
3486 	switch (mode) {
3487 	case MPOL_PREFERRED:
3488 		/*
3489 		 * Insist on a nodelist of one node only, although later
3490 		 * we use first_node(nodes) to grab a single node, so here
3491 		 * nodelist (or nodes) cannot be empty.
3492 		 */
3493 		if (nodelist) {
3494 			char *rest = nodelist;
3495 			while (isdigit(*rest))
3496 				rest++;
3497 			if (*rest)
3498 				goto out;
3499 			if (nodes_empty(nodes))
3500 				goto out;
3501 		}
3502 		break;
3503 	case MPOL_INTERLEAVE:
3504 	case MPOL_WEIGHTED_INTERLEAVE:
3505 		/*
3506 		 * Default to online nodes with memory if no nodelist
3507 		 */
3508 		if (!nodelist)
3509 			nodes = node_states[N_MEMORY];
3510 		break;
3511 	case MPOL_LOCAL:
3512 		/*
3513 		 * Don't allow a nodelist;  mpol_new() checks flags
3514 		 */
3515 		if (nodelist)
3516 			goto out;
3517 		break;
3518 	case MPOL_DEFAULT:
3519 		/*
3520 		 * Insist on a empty nodelist
3521 		 */
3522 		if (!nodelist)
3523 			err = 0;
3524 		goto out;
3525 	case MPOL_PREFERRED_MANY:
3526 	case MPOL_BIND:
3527 		/*
3528 		 * Insist on a nodelist
3529 		 */
3530 		if (!nodelist)
3531 			goto out;
3532 	}
3533 
3534 	mode_flags = 0;
3535 	if (flags) {
3536 		/*
3537 		 * Currently, we only support two mutually exclusive
3538 		 * mode flags.
3539 		 */
3540 		if (!strcmp(flags, "static"))
3541 			mode_flags |= MPOL_F_STATIC_NODES;
3542 		else if (!strcmp(flags, "relative"))
3543 			mode_flags |= MPOL_F_RELATIVE_NODES;
3544 		else
3545 			goto out;
3546 	}
3547 
3548 	new = mpol_new(mode, mode_flags, &nodes);
3549 	if (IS_ERR(new))
3550 		goto out;
3551 
3552 	/*
3553 	 * Save nodes for mpol_to_str() to show the tmpfs mount options
3554 	 * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
3555 	 */
3556 	if (mode != MPOL_PREFERRED) {
3557 		new->nodes = nodes;
3558 	} else if (nodelist) {
3559 		nodes_clear(new->nodes);
3560 		node_set(first_node(nodes), new->nodes);
3561 	} else {
3562 		new->mode = MPOL_LOCAL;
3563 	}
3564 
3565 	/*
3566 	 * Save nodes for contextualization: this will be used to "clone"
3567 	 * the mempolicy in a specific context [cpuset] at a later time.
3568 	 */
3569 	new->w.user_nodemask = nodes;
3570 
3571 	err = 0;
3572 
3573 out:
3574 	/* Restore string for error message */
3575 	if (nodelist)
3576 		*--nodelist = ':';
3577 	if (flags)
3578 		*--flags = '=';
3579 	if (!err)
3580 		*mpol = new;
3581 	return err;
3582 }
3583 #endif /* CONFIG_TMPFS */
3584 
3585 /**
3586  * mpol_to_str - format a mempolicy structure for printing
3587  * @buffer:  to contain formatted mempolicy string
3588  * @maxlen:  length of @buffer
3589  * @pol:  pointer to mempolicy to be formatted
3590  *
3591  * Convert @pol into a string.  If @buffer is too short, truncate the string.
3592  * Recommend a @maxlen of at least 51 for the longest mode, "weighted
3593  * interleave", plus the longest flag flags, "relative|balancing", and to
3594  * display at least a few node ids.
3595  */
3596 void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
3597 {
3598 	char *p = buffer;
3599 	nodemask_t nodes = NODE_MASK_NONE;
3600 	unsigned short mode = MPOL_DEFAULT;
3601 	unsigned short flags = 0;
3602 
3603 	if (pol &&
3604 	    pol != &default_policy &&
3605 	    !(pol >= &preferred_node_policy[0] &&
3606 	      pol <= &preferred_node_policy[ARRAY_SIZE(preferred_node_policy) - 1])) {
3607 		mode = pol->mode;
3608 		flags = pol->flags;
3609 	}
3610 
3611 	switch (mode) {
3612 	case MPOL_DEFAULT:
3613 	case MPOL_LOCAL:
3614 		break;
3615 	case MPOL_PREFERRED:
3616 	case MPOL_PREFERRED_MANY:
3617 	case MPOL_BIND:
3618 	case MPOL_INTERLEAVE:
3619 	case MPOL_WEIGHTED_INTERLEAVE:
3620 		nodes = pol->nodes;
3621 		break;
3622 	default:
3623 		WARN_ON_ONCE(1);
3624 		snprintf(p, maxlen, "unknown");
3625 		return;
3626 	}
3627 
3628 	p += snprintf(p, maxlen, "%s", policy_modes[mode]);
3629 
3630 	if (flags & MPOL_MODE_FLAGS) {
3631 		p += snprintf(p, buffer + maxlen - p, "=");
3632 
3633 		/*
3634 		 * Static and relative are mutually exclusive.
3635 		 */
3636 		if (flags & MPOL_F_STATIC_NODES)
3637 			p += snprintf(p, buffer + maxlen - p, "static");
3638 		else if (flags & MPOL_F_RELATIVE_NODES)
3639 			p += snprintf(p, buffer + maxlen - p, "relative");
3640 
3641 		if (flags & MPOL_F_NUMA_BALANCING) {
3642 			if (!is_power_of_2(flags & MPOL_MODE_FLAGS))
3643 				p += snprintf(p, buffer + maxlen - p, "|");
3644 			p += snprintf(p, buffer + maxlen - p, "balancing");
3645 		}
3646 	}
3647 
3648 	if (!nodes_empty(nodes))
3649 		p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
3650 			       nodemask_pr_args(&nodes));
3651 }
3652 
3653 #ifdef CONFIG_SYSFS
3654 struct iw_node_attr {
3655 	struct kobj_attribute kobj_attr;
3656 	int nid;
3657 };
3658 
3659 struct sysfs_wi_group {
3660 	struct kobject wi_kobj;
3661 	struct mutex kobj_lock;
3662 	struct iw_node_attr *nattrs[];
3663 };
3664 
3665 static struct sysfs_wi_group *wi_group;
3666 
3667 static ssize_t node_show(struct kobject *kobj, struct kobj_attribute *attr,
3668 			 char *buf)
3669 {
3670 	struct iw_node_attr *node_attr;
3671 	u8 weight;
3672 
3673 	node_attr = container_of(attr, struct iw_node_attr, kobj_attr);
3674 	weight = get_il_weight(node_attr->nid);
3675 	return sysfs_emit(buf, "%d\n", weight);
3676 }
3677 
3678 static ssize_t node_store(struct kobject *kobj, struct kobj_attribute *attr,
3679 			  const char *buf, size_t count)
3680 {
3681 	struct weighted_interleave_state *new_wi_state, *old_wi_state = NULL;
3682 	struct iw_node_attr *node_attr;
3683 	u8 weight = 0;
3684 	int i;
3685 
3686 	node_attr = container_of(attr, struct iw_node_attr, kobj_attr);
3687 	if (count == 0 || sysfs_streq(buf, "") ||
3688 	    kstrtou8(buf, 0, &weight) || weight == 0)
3689 		return -EINVAL;
3690 
3691 	new_wi_state = kzalloc_flex(*new_wi_state, iw_table, nr_node_ids);
3692 	if (!new_wi_state)
3693 		return -ENOMEM;
3694 
3695 	mutex_lock(&wi_state_lock);
3696 	old_wi_state = rcu_dereference_protected(wi_state,
3697 					lockdep_is_held(&wi_state_lock));
3698 	if (old_wi_state) {
3699 		memcpy(new_wi_state->iw_table, old_wi_state->iw_table,
3700 					nr_node_ids * sizeof(u8));
3701 	} else {
3702 		for (i = 0; i < nr_node_ids; i++)
3703 			new_wi_state->iw_table[i] = 1;
3704 	}
3705 	new_wi_state->iw_table[node_attr->nid] = weight;
3706 	new_wi_state->mode_auto = false;
3707 
3708 	rcu_assign_pointer(wi_state, new_wi_state);
3709 	mutex_unlock(&wi_state_lock);
3710 	wi_state_retire(old_wi_state);
3711 	return count;
3712 }
3713 
3714 static ssize_t weighted_interleave_auto_show(struct kobject *kobj,
3715 		struct kobj_attribute *attr, char *buf)
3716 {
3717 	struct weighted_interleave_state *state;
3718 	bool wi_auto = true;
3719 
3720 	rcu_read_lock();
3721 	state = rcu_dereference(wi_state);
3722 	if (state)
3723 		wi_auto = state->mode_auto;
3724 	rcu_read_unlock();
3725 
3726 	return sysfs_emit(buf, "%s\n", str_true_false(wi_auto));
3727 }
3728 
3729 static ssize_t weighted_interleave_auto_store(struct kobject *kobj,
3730 		struct kobj_attribute *attr, const char *buf, size_t count)
3731 {
3732 	struct weighted_interleave_state *new_wi_state, *old_wi_state = NULL;
3733 	unsigned int *bw;
3734 	bool input;
3735 	int i;
3736 
3737 	if (kstrtobool(buf, &input))
3738 		return -EINVAL;
3739 
3740 	new_wi_state = kzalloc_flex(*new_wi_state, iw_table, nr_node_ids);
3741 	if (!new_wi_state)
3742 		return -ENOMEM;
3743 	for (i = 0; i < nr_node_ids; i++)
3744 		new_wi_state->iw_table[i] = 1;
3745 
3746 	mutex_lock(&wi_state_lock);
3747 	old_wi_state = rcu_dereference_protected(wi_state,
3748 				lockdep_is_held(&wi_state_lock));
3749 
3750 	if (old_wi_state && input == old_wi_state->mode_auto) {
3751 		mutex_unlock(&wi_state_lock);
3752 		kfree(new_wi_state);
3753 		return count;
3754 	}
3755 
3756 	if (!input) {
3757 		if (old_wi_state)
3758 			memcpy(new_wi_state->iw_table, old_wi_state->iw_table,
3759 						       nr_node_ids * sizeof(u8));
3760 		goto update_wi_state;
3761 	}
3762 
3763 	bw = node_bw_table;
3764 	if (!bw) {
3765 		mutex_unlock(&wi_state_lock);
3766 		kfree(new_wi_state);
3767 		return -ENODEV;
3768 	}
3769 
3770 	new_wi_state->mode_auto = true;
3771 	reduce_interleave_weights(bw, new_wi_state->iw_table);
3772 
3773 update_wi_state:
3774 	rcu_assign_pointer(wi_state, new_wi_state);
3775 	mutex_unlock(&wi_state_lock);
3776 	wi_state_retire(old_wi_state);
3777 	return count;
3778 }
3779 
3780 static void sysfs_wi_node_delete(int nid)
3781 {
3782 	struct iw_node_attr *attr;
3783 
3784 	if (nid < 0 || nid >= nr_node_ids)
3785 		return;
3786 
3787 	mutex_lock(&wi_group->kobj_lock);
3788 	attr = wi_group->nattrs[nid];
3789 	if (!attr) {
3790 		mutex_unlock(&wi_group->kobj_lock);
3791 		return;
3792 	}
3793 
3794 	wi_group->nattrs[nid] = NULL;
3795 	mutex_unlock(&wi_group->kobj_lock);
3796 
3797 	sysfs_remove_file(&wi_group->wi_kobj, &attr->kobj_attr.attr);
3798 	kfree(attr->kobj_attr.attr.name);
3799 	kfree(attr);
3800 }
3801 
3802 static void sysfs_wi_node_delete_all(void)
3803 {
3804 	int nid;
3805 
3806 	for (nid = 0; nid < nr_node_ids; nid++)
3807 		sysfs_wi_node_delete(nid);
3808 }
3809 
3810 static void wi_state_free(void)
3811 {
3812 	struct weighted_interleave_state *old_wi_state;
3813 
3814 	mutex_lock(&wi_state_lock);
3815 	old_wi_state = rcu_dereference_protected(wi_state,
3816 			lockdep_is_held(&wi_state_lock));
3817 	rcu_assign_pointer(wi_state, NULL);
3818 	mutex_unlock(&wi_state_lock);
3819 
3820 	wi_state_retire(old_wi_state);
3821 }
3822 
3823 static struct kobj_attribute wi_auto_attr = {
3824 	.attr = { .name = "auto", .mode = 0664 },
3825 	.show = weighted_interleave_auto_show,
3826 	.store = weighted_interleave_auto_store,
3827 };
3828 
3829 static void wi_cleanup(void) {
3830 	sysfs_remove_file(&wi_group->wi_kobj, &wi_auto_attr.attr);
3831 	sysfs_wi_node_delete_all();
3832 	wi_state_free();
3833 }
3834 
3835 static void wi_kobj_release(struct kobject *wi_kobj)
3836 {
3837 	kfree(wi_group);
3838 }
3839 
3840 static const struct kobj_type wi_ktype = {
3841 	.sysfs_ops = &kobj_sysfs_ops,
3842 	.release = wi_kobj_release,
3843 };
3844 
3845 static int sysfs_wi_node_add(int nid)
3846 {
3847 	int ret;
3848 	char *name;
3849 	struct iw_node_attr *new_attr;
3850 
3851 	if (nid < 0 || nid >= nr_node_ids) {
3852 		pr_err("invalid node id: %d\n", nid);
3853 		return -EINVAL;
3854 	}
3855 
3856 	new_attr = kzalloc_obj(*new_attr);
3857 	if (!new_attr)
3858 		return -ENOMEM;
3859 
3860 	name = kasprintf(GFP_KERNEL, "node%d", nid);
3861 	if (!name) {
3862 		kfree(new_attr);
3863 		return -ENOMEM;
3864 	}
3865 
3866 	sysfs_attr_init(&new_attr->kobj_attr.attr);
3867 	new_attr->kobj_attr.attr.name = name;
3868 	new_attr->kobj_attr.attr.mode = 0644;
3869 	new_attr->kobj_attr.show = node_show;
3870 	new_attr->kobj_attr.store = node_store;
3871 	new_attr->nid = nid;
3872 
3873 	mutex_lock(&wi_group->kobj_lock);
3874 	if (wi_group->nattrs[nid]) {
3875 		mutex_unlock(&wi_group->kobj_lock);
3876 		ret = -EEXIST;
3877 		goto out;
3878 	}
3879 
3880 	ret = sysfs_create_file(&wi_group->wi_kobj, &new_attr->kobj_attr.attr);
3881 	if (ret) {
3882 		mutex_unlock(&wi_group->kobj_lock);
3883 		goto out;
3884 	}
3885 	wi_group->nattrs[nid] = new_attr;
3886 	mutex_unlock(&wi_group->kobj_lock);
3887 	return 0;
3888 
3889 out:
3890 	kfree(new_attr->kobj_attr.attr.name);
3891 	kfree(new_attr);
3892 	return ret;
3893 }
3894 
3895 static int wi_node_notifier(struct notifier_block *nb,
3896 			       unsigned long action, void *data)
3897 {
3898 	int err;
3899 	struct node_notify *nn = data;
3900 	int nid = nn->nid;
3901 
3902 	switch (action) {
3903 	case NODE_ADDED_FIRST_MEMORY:
3904 		err = sysfs_wi_node_add(nid);
3905 		if (err)
3906 			pr_err("failed to add sysfs for node%d during hotplug: %d\n",
3907 			       nid, err);
3908 		break;
3909 	case NODE_REMOVED_LAST_MEMORY:
3910 		sysfs_wi_node_delete(nid);
3911 		break;
3912 	}
3913 
3914 	return NOTIFY_OK;
3915 }
3916 
3917 static int __init add_weighted_interleave_group(struct kobject *mempolicy_kobj)
3918 {
3919 	int nid, err;
3920 
3921 	wi_group = kzalloc_flex(*wi_group, nattrs, nr_node_ids);
3922 	if (!wi_group)
3923 		return -ENOMEM;
3924 	mutex_init(&wi_group->kobj_lock);
3925 
3926 	err = kobject_init_and_add(&wi_group->wi_kobj, &wi_ktype, mempolicy_kobj,
3927 				   "weighted_interleave");
3928 	if (err)
3929 		goto err_put_kobj;
3930 
3931 	err = sysfs_create_file(&wi_group->wi_kobj, &wi_auto_attr.attr);
3932 	if (err)
3933 		goto err_put_kobj;
3934 
3935 	for_each_online_node(nid) {
3936 		if (!node_state(nid, N_MEMORY))
3937 			continue;
3938 
3939 		err = sysfs_wi_node_add(nid);
3940 		if (err) {
3941 			pr_err("failed to add sysfs for node%d during init: %d\n",
3942 			       nid, err);
3943 			goto err_cleanup_kobj;
3944 		}
3945 	}
3946 
3947 	hotplug_node_notifier(wi_node_notifier, DEFAULT_CALLBACK_PRI);
3948 	return 0;
3949 
3950 err_cleanup_kobj:
3951 	wi_cleanup();
3952 	kobject_del(&wi_group->wi_kobj);
3953 err_put_kobj:
3954 	kobject_put(&wi_group->wi_kobj);
3955 	return err;
3956 }
3957 
3958 static int __init mempolicy_sysfs_init(void)
3959 {
3960 	int err;
3961 	static struct kobject *mempolicy_kobj;
3962 
3963 	mempolicy_kobj = kobject_create_and_add("mempolicy", mm_kobj);
3964 	if (!mempolicy_kobj)
3965 		return -ENOMEM;
3966 
3967 	err = add_weighted_interleave_group(mempolicy_kobj);
3968 	if (err)
3969 		goto err_kobj;
3970 
3971 	return 0;
3972 
3973 err_kobj:
3974 	kobject_del(mempolicy_kobj);
3975 	kobject_put(mempolicy_kobj);
3976 	return err;
3977 }
3978 
3979 late_initcall(mempolicy_sysfs_init);
3980 #endif /* CONFIG_SYSFS */
3981