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