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