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