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