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