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