]> git.proxmox.com Git - mirror_ubuntu-disco-kernel.git/blob - mm/page_alloc.c
mm/hotplug: treat CMA pages as unmovable
[mirror_ubuntu-disco-kernel.git] / mm / page_alloc.c
1 /*
2 * linux/mm/page_alloc.c
3 *
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
6 *
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15 */
16
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/highmem.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/jiffies.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kasan.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/topology.h>
36 #include <linux/sysctl.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/memory_hotplug.h>
40 #include <linux/nodemask.h>
41 #include <linux/vmalloc.h>
42 #include <linux/vmstat.h>
43 #include <linux/mempolicy.h>
44 #include <linux/memremap.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_ext.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/compaction.h>
55 #include <trace/events/kmem.h>
56 #include <trace/events/oom.h>
57 #include <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/hugetlb.h>
61 #include <linux/sched/rt.h>
62 #include <linux/sched/mm.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
65 #include <linux/memcontrol.h>
66 #include <linux/ftrace.h>
67 #include <linux/lockdep.h>
68 #include <linux/nmi.h>
69 #include <linux/psi.h>
70
71 #include <asm/sections.h>
72 #include <asm/tlbflush.h>
73 #include <asm/div64.h>
74 #include "internal.h"
75
76 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
77 static DEFINE_MUTEX(pcp_batch_high_lock);
78 #define MIN_PERCPU_PAGELIST_FRACTION (8)
79
80 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
81 DEFINE_PER_CPU(int, numa_node);
82 EXPORT_PER_CPU_SYMBOL(numa_node);
83 #endif
84
85 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
86
87 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
88 /*
89 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
90 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
91 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
92 * defined in <linux/topology.h>.
93 */
94 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
95 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
96 int _node_numa_mem_[MAX_NUMNODES];
97 #endif
98
99 /* work_structs for global per-cpu drains */
100 struct pcpu_drain {
101 struct zone *zone;
102 struct work_struct work;
103 };
104 DEFINE_MUTEX(pcpu_drain_mutex);
105 DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
106
107 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
108 volatile unsigned long latent_entropy __latent_entropy;
109 EXPORT_SYMBOL(latent_entropy);
110 #endif
111
112 /*
113 * Array of node states.
114 */
115 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
116 [N_POSSIBLE] = NODE_MASK_ALL,
117 [N_ONLINE] = { { [0] = 1UL } },
118 #ifndef CONFIG_NUMA
119 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
120 #ifdef CONFIG_HIGHMEM
121 [N_HIGH_MEMORY] = { { [0] = 1UL } },
122 #endif
123 [N_MEMORY] = { { [0] = 1UL } },
124 [N_CPU] = { { [0] = 1UL } },
125 #endif /* NUMA */
126 };
127 EXPORT_SYMBOL(node_states);
128
129 atomic_long_t _totalram_pages __read_mostly;
130 EXPORT_SYMBOL(_totalram_pages);
131 unsigned long totalreserve_pages __read_mostly;
132 unsigned long totalcma_pages __read_mostly;
133
134 int percpu_pagelist_fraction;
135 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
136
137 /*
138 * A cached value of the page's pageblock's migratetype, used when the page is
139 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
140 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
141 * Also the migratetype set in the page does not necessarily match the pcplist
142 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
143 * other index - this ensures that it will be put on the correct CMA freelist.
144 */
145 static inline int get_pcppage_migratetype(struct page *page)
146 {
147 return page->index;
148 }
149
150 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
151 {
152 page->index = migratetype;
153 }
154
155 #ifdef CONFIG_PM_SLEEP
156 /*
157 * The following functions are used by the suspend/hibernate code to temporarily
158 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
159 * while devices are suspended. To avoid races with the suspend/hibernate code,
160 * they should always be called with system_transition_mutex held
161 * (gfp_allowed_mask also should only be modified with system_transition_mutex
162 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
163 * with that modification).
164 */
165
166 static gfp_t saved_gfp_mask;
167
168 void pm_restore_gfp_mask(void)
169 {
170 WARN_ON(!mutex_is_locked(&system_transition_mutex));
171 if (saved_gfp_mask) {
172 gfp_allowed_mask = saved_gfp_mask;
173 saved_gfp_mask = 0;
174 }
175 }
176
177 void pm_restrict_gfp_mask(void)
178 {
179 WARN_ON(!mutex_is_locked(&system_transition_mutex));
180 WARN_ON(saved_gfp_mask);
181 saved_gfp_mask = gfp_allowed_mask;
182 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
183 }
184
185 bool pm_suspended_storage(void)
186 {
187 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
188 return false;
189 return true;
190 }
191 #endif /* CONFIG_PM_SLEEP */
192
193 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
194 unsigned int pageblock_order __read_mostly;
195 #endif
196
197 static void __free_pages_ok(struct page *page, unsigned int order);
198
199 /*
200 * results with 256, 32 in the lowmem_reserve sysctl:
201 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
202 * 1G machine -> (16M dma, 784M normal, 224M high)
203 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
204 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
205 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
206 *
207 * TBD: should special case ZONE_DMA32 machines here - in those we normally
208 * don't need any ZONE_NORMAL reservation
209 */
210 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
211 #ifdef CONFIG_ZONE_DMA
212 [ZONE_DMA] = 256,
213 #endif
214 #ifdef CONFIG_ZONE_DMA32
215 [ZONE_DMA32] = 256,
216 #endif
217 [ZONE_NORMAL] = 32,
218 #ifdef CONFIG_HIGHMEM
219 [ZONE_HIGHMEM] = 0,
220 #endif
221 [ZONE_MOVABLE] = 0,
222 };
223
224 EXPORT_SYMBOL(totalram_pages);
225
226 static char * const zone_names[MAX_NR_ZONES] = {
227 #ifdef CONFIG_ZONE_DMA
228 "DMA",
229 #endif
230 #ifdef CONFIG_ZONE_DMA32
231 "DMA32",
232 #endif
233 "Normal",
234 #ifdef CONFIG_HIGHMEM
235 "HighMem",
236 #endif
237 "Movable",
238 #ifdef CONFIG_ZONE_DEVICE
239 "Device",
240 #endif
241 };
242
243 const char * const migratetype_names[MIGRATE_TYPES] = {
244 "Unmovable",
245 "Movable",
246 "Reclaimable",
247 "HighAtomic",
248 #ifdef CONFIG_CMA
249 "CMA",
250 #endif
251 #ifdef CONFIG_MEMORY_ISOLATION
252 "Isolate",
253 #endif
254 };
255
256 compound_page_dtor * const compound_page_dtors[] = {
257 NULL,
258 free_compound_page,
259 #ifdef CONFIG_HUGETLB_PAGE
260 free_huge_page,
261 #endif
262 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
263 free_transhuge_page,
264 #endif
265 };
266
267 int min_free_kbytes = 1024;
268 int user_min_free_kbytes = -1;
269 #ifdef CONFIG_DISCONTIGMEM
270 /*
271 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
272 * are not on separate NUMA nodes. Functionally this works but with
273 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
274 * quite small. By default, do not boost watermarks on discontigmem as in
275 * many cases very high-order allocations like THP are likely to be
276 * unsupported and the premature reclaim offsets the advantage of long-term
277 * fragmentation avoidance.
278 */
279 int watermark_boost_factor __read_mostly;
280 #else
281 int watermark_boost_factor __read_mostly = 15000;
282 #endif
283 int watermark_scale_factor = 10;
284
285 static unsigned long nr_kernel_pages __initdata;
286 static unsigned long nr_all_pages __initdata;
287 static unsigned long dma_reserve __initdata;
288
289 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
290 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
291 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
292 static unsigned long required_kernelcore __initdata;
293 static unsigned long required_kernelcore_percent __initdata;
294 static unsigned long required_movablecore __initdata;
295 static unsigned long required_movablecore_percent __initdata;
296 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
297 static bool mirrored_kernelcore __meminitdata;
298
299 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
300 int movable_zone;
301 EXPORT_SYMBOL(movable_zone);
302 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
303
304 #if MAX_NUMNODES > 1
305 int nr_node_ids __read_mostly = MAX_NUMNODES;
306 int nr_online_nodes __read_mostly = 1;
307 EXPORT_SYMBOL(nr_node_ids);
308 EXPORT_SYMBOL(nr_online_nodes);
309 #endif
310
311 int page_group_by_mobility_disabled __read_mostly;
312
313 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
314 /*
315 * During boot we initialize deferred pages on-demand, as needed, but once
316 * page_alloc_init_late() has finished, the deferred pages are all initialized,
317 * and we can permanently disable that path.
318 */
319 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
320
321 /*
322 * Calling kasan_free_pages() only after deferred memory initialization
323 * has completed. Poisoning pages during deferred memory init will greatly
324 * lengthen the process and cause problem in large memory systems as the
325 * deferred pages initialization is done with interrupt disabled.
326 *
327 * Assuming that there will be no reference to those newly initialized
328 * pages before they are ever allocated, this should have no effect on
329 * KASAN memory tracking as the poison will be properly inserted at page
330 * allocation time. The only corner case is when pages are allocated by
331 * on-demand allocation and then freed again before the deferred pages
332 * initialization is done, but this is not likely to happen.
333 */
334 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
335 {
336 if (!static_branch_unlikely(&deferred_pages))
337 kasan_free_pages(page, order);
338 }
339
340 /* Returns true if the struct page for the pfn is uninitialised */
341 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
342 {
343 int nid = early_pfn_to_nid(pfn);
344
345 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
346 return true;
347
348 return false;
349 }
350
351 /*
352 * Returns true when the remaining initialisation should be deferred until
353 * later in the boot cycle when it can be parallelised.
354 */
355 static bool __meminit
356 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
357 {
358 static unsigned long prev_end_pfn, nr_initialised;
359
360 /*
361 * prev_end_pfn static that contains the end of previous zone
362 * No need to protect because called very early in boot before smp_init.
363 */
364 if (prev_end_pfn != end_pfn) {
365 prev_end_pfn = end_pfn;
366 nr_initialised = 0;
367 }
368
369 /* Always populate low zones for address-constrained allocations */
370 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
371 return false;
372
373 /*
374 * We start only with one section of pages, more pages are added as
375 * needed until the rest of deferred pages are initialized.
376 */
377 nr_initialised++;
378 if ((nr_initialised > PAGES_PER_SECTION) &&
379 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
380 NODE_DATA(nid)->first_deferred_pfn = pfn;
381 return true;
382 }
383 return false;
384 }
385 #else
386 #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
387
388 static inline bool early_page_uninitialised(unsigned long pfn)
389 {
390 return false;
391 }
392
393 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
394 {
395 return false;
396 }
397 #endif
398
399 /* Return a pointer to the bitmap storing bits affecting a block of pages */
400 static inline unsigned long *get_pageblock_bitmap(struct page *page,
401 unsigned long pfn)
402 {
403 #ifdef CONFIG_SPARSEMEM
404 return __pfn_to_section(pfn)->pageblock_flags;
405 #else
406 return page_zone(page)->pageblock_flags;
407 #endif /* CONFIG_SPARSEMEM */
408 }
409
410 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
411 {
412 #ifdef CONFIG_SPARSEMEM
413 pfn &= (PAGES_PER_SECTION-1);
414 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
415 #else
416 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
417 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
418 #endif /* CONFIG_SPARSEMEM */
419 }
420
421 /**
422 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
423 * @page: The page within the block of interest
424 * @pfn: The target page frame number
425 * @end_bitidx: The last bit of interest to retrieve
426 * @mask: mask of bits that the caller is interested in
427 *
428 * Return: pageblock_bits flags
429 */
430 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
431 unsigned long pfn,
432 unsigned long end_bitidx,
433 unsigned long mask)
434 {
435 unsigned long *bitmap;
436 unsigned long bitidx, word_bitidx;
437 unsigned long word;
438
439 bitmap = get_pageblock_bitmap(page, pfn);
440 bitidx = pfn_to_bitidx(page, pfn);
441 word_bitidx = bitidx / BITS_PER_LONG;
442 bitidx &= (BITS_PER_LONG-1);
443
444 word = bitmap[word_bitidx];
445 bitidx += end_bitidx;
446 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
447 }
448
449 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
450 unsigned long end_bitidx,
451 unsigned long mask)
452 {
453 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
454 }
455
456 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
457 {
458 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
459 }
460
461 /**
462 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
463 * @page: The page within the block of interest
464 * @flags: The flags to set
465 * @pfn: The target page frame number
466 * @end_bitidx: The last bit of interest
467 * @mask: mask of bits that the caller is interested in
468 */
469 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
470 unsigned long pfn,
471 unsigned long end_bitidx,
472 unsigned long mask)
473 {
474 unsigned long *bitmap;
475 unsigned long bitidx, word_bitidx;
476 unsigned long old_word, word;
477
478 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
479 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
480
481 bitmap = get_pageblock_bitmap(page, pfn);
482 bitidx = pfn_to_bitidx(page, pfn);
483 word_bitidx = bitidx / BITS_PER_LONG;
484 bitidx &= (BITS_PER_LONG-1);
485
486 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
487
488 bitidx += end_bitidx;
489 mask <<= (BITS_PER_LONG - bitidx - 1);
490 flags <<= (BITS_PER_LONG - bitidx - 1);
491
492 word = READ_ONCE(bitmap[word_bitidx]);
493 for (;;) {
494 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
495 if (word == old_word)
496 break;
497 word = old_word;
498 }
499 }
500
501 void set_pageblock_migratetype(struct page *page, int migratetype)
502 {
503 if (unlikely(page_group_by_mobility_disabled &&
504 migratetype < MIGRATE_PCPTYPES))
505 migratetype = MIGRATE_UNMOVABLE;
506
507 set_pageblock_flags_group(page, (unsigned long)migratetype,
508 PB_migrate, PB_migrate_end);
509 }
510
511 #ifdef CONFIG_DEBUG_VM
512 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
513 {
514 int ret = 0;
515 unsigned seq;
516 unsigned long pfn = page_to_pfn(page);
517 unsigned long sp, start_pfn;
518
519 do {
520 seq = zone_span_seqbegin(zone);
521 start_pfn = zone->zone_start_pfn;
522 sp = zone->spanned_pages;
523 if (!zone_spans_pfn(zone, pfn))
524 ret = 1;
525 } while (zone_span_seqretry(zone, seq));
526
527 if (ret)
528 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
529 pfn, zone_to_nid(zone), zone->name,
530 start_pfn, start_pfn + sp);
531
532 return ret;
533 }
534
535 static int page_is_consistent(struct zone *zone, struct page *page)
536 {
537 if (!pfn_valid_within(page_to_pfn(page)))
538 return 0;
539 if (zone != page_zone(page))
540 return 0;
541
542 return 1;
543 }
544 /*
545 * Temporary debugging check for pages not lying within a given zone.
546 */
547 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
548 {
549 if (page_outside_zone_boundaries(zone, page))
550 return 1;
551 if (!page_is_consistent(zone, page))
552 return 1;
553
554 return 0;
555 }
556 #else
557 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
558 {
559 return 0;
560 }
561 #endif
562
563 static void bad_page(struct page *page, const char *reason,
564 unsigned long bad_flags)
565 {
566 static unsigned long resume;
567 static unsigned long nr_shown;
568 static unsigned long nr_unshown;
569
570 /*
571 * Allow a burst of 60 reports, then keep quiet for that minute;
572 * or allow a steady drip of one report per second.
573 */
574 if (nr_shown == 60) {
575 if (time_before(jiffies, resume)) {
576 nr_unshown++;
577 goto out;
578 }
579 if (nr_unshown) {
580 pr_alert(
581 "BUG: Bad page state: %lu messages suppressed\n",
582 nr_unshown);
583 nr_unshown = 0;
584 }
585 nr_shown = 0;
586 }
587 if (nr_shown++ == 0)
588 resume = jiffies + 60 * HZ;
589
590 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
591 current->comm, page_to_pfn(page));
592 __dump_page(page, reason);
593 bad_flags &= page->flags;
594 if (bad_flags)
595 pr_alert("bad because of flags: %#lx(%pGp)\n",
596 bad_flags, &bad_flags);
597 dump_page_owner(page);
598
599 print_modules();
600 dump_stack();
601 out:
602 /* Leave bad fields for debug, except PageBuddy could make trouble */
603 page_mapcount_reset(page); /* remove PageBuddy */
604 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
605 }
606
607 /*
608 * Higher-order pages are called "compound pages". They are structured thusly:
609 *
610 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
611 *
612 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
613 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
614 *
615 * The first tail page's ->compound_dtor holds the offset in array of compound
616 * page destructors. See compound_page_dtors.
617 *
618 * The first tail page's ->compound_order holds the order of allocation.
619 * This usage means that zero-order pages may not be compound.
620 */
621
622 void free_compound_page(struct page *page)
623 {
624 __free_pages_ok(page, compound_order(page));
625 }
626
627 void prep_compound_page(struct page *page, unsigned int order)
628 {
629 int i;
630 int nr_pages = 1 << order;
631
632 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
633 set_compound_order(page, order);
634 __SetPageHead(page);
635 for (i = 1; i < nr_pages; i++) {
636 struct page *p = page + i;
637 set_page_count(p, 0);
638 p->mapping = TAIL_MAPPING;
639 set_compound_head(p, page);
640 }
641 atomic_set(compound_mapcount_ptr(page), -1);
642 }
643
644 #ifdef CONFIG_DEBUG_PAGEALLOC
645 unsigned int _debug_guardpage_minorder;
646 bool _debug_pagealloc_enabled __read_mostly
647 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
648 EXPORT_SYMBOL(_debug_pagealloc_enabled);
649 bool _debug_guardpage_enabled __read_mostly;
650
651 static int __init early_debug_pagealloc(char *buf)
652 {
653 if (!buf)
654 return -EINVAL;
655 return kstrtobool(buf, &_debug_pagealloc_enabled);
656 }
657 early_param("debug_pagealloc", early_debug_pagealloc);
658
659 static bool need_debug_guardpage(void)
660 {
661 /* If we don't use debug_pagealloc, we don't need guard page */
662 if (!debug_pagealloc_enabled())
663 return false;
664
665 if (!debug_guardpage_minorder())
666 return false;
667
668 return true;
669 }
670
671 static void init_debug_guardpage(void)
672 {
673 if (!debug_pagealloc_enabled())
674 return;
675
676 if (!debug_guardpage_minorder())
677 return;
678
679 _debug_guardpage_enabled = true;
680 }
681
682 struct page_ext_operations debug_guardpage_ops = {
683 .need = need_debug_guardpage,
684 .init = init_debug_guardpage,
685 };
686
687 static int __init debug_guardpage_minorder_setup(char *buf)
688 {
689 unsigned long res;
690
691 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
692 pr_err("Bad debug_guardpage_minorder value\n");
693 return 0;
694 }
695 _debug_guardpage_minorder = res;
696 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
697 return 0;
698 }
699 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
700
701 static inline bool set_page_guard(struct zone *zone, struct page *page,
702 unsigned int order, int migratetype)
703 {
704 struct page_ext *page_ext;
705
706 if (!debug_guardpage_enabled())
707 return false;
708
709 if (order >= debug_guardpage_minorder())
710 return false;
711
712 page_ext = lookup_page_ext(page);
713 if (unlikely(!page_ext))
714 return false;
715
716 __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
717
718 INIT_LIST_HEAD(&page->lru);
719 set_page_private(page, order);
720 /* Guard pages are not available for any usage */
721 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
722
723 return true;
724 }
725
726 static inline void clear_page_guard(struct zone *zone, struct page *page,
727 unsigned int order, int migratetype)
728 {
729 struct page_ext *page_ext;
730
731 if (!debug_guardpage_enabled())
732 return;
733
734 page_ext = lookup_page_ext(page);
735 if (unlikely(!page_ext))
736 return;
737
738 __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
739
740 set_page_private(page, 0);
741 if (!is_migrate_isolate(migratetype))
742 __mod_zone_freepage_state(zone, (1 << order), migratetype);
743 }
744 #else
745 struct page_ext_operations debug_guardpage_ops;
746 static inline bool set_page_guard(struct zone *zone, struct page *page,
747 unsigned int order, int migratetype) { return false; }
748 static inline void clear_page_guard(struct zone *zone, struct page *page,
749 unsigned int order, int migratetype) {}
750 #endif
751
752 static inline void set_page_order(struct page *page, unsigned int order)
753 {
754 set_page_private(page, order);
755 __SetPageBuddy(page);
756 }
757
758 static inline void rmv_page_order(struct page *page)
759 {
760 __ClearPageBuddy(page);
761 set_page_private(page, 0);
762 }
763
764 /*
765 * This function checks whether a page is free && is the buddy
766 * we can coalesce a page and its buddy if
767 * (a) the buddy is not in a hole (check before calling!) &&
768 * (b) the buddy is in the buddy system &&
769 * (c) a page and its buddy have the same order &&
770 * (d) a page and its buddy are in the same zone.
771 *
772 * For recording whether a page is in the buddy system, we set PageBuddy.
773 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
774 *
775 * For recording page's order, we use page_private(page).
776 */
777 static inline int page_is_buddy(struct page *page, struct page *buddy,
778 unsigned int order)
779 {
780 if (page_is_guard(buddy) && page_order(buddy) == order) {
781 if (page_zone_id(page) != page_zone_id(buddy))
782 return 0;
783
784 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
785
786 return 1;
787 }
788
789 if (PageBuddy(buddy) && page_order(buddy) == order) {
790 /*
791 * zone check is done late to avoid uselessly
792 * calculating zone/node ids for pages that could
793 * never merge.
794 */
795 if (page_zone_id(page) != page_zone_id(buddy))
796 return 0;
797
798 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
799
800 return 1;
801 }
802 return 0;
803 }
804
805 /*
806 * Freeing function for a buddy system allocator.
807 *
808 * The concept of a buddy system is to maintain direct-mapped table
809 * (containing bit values) for memory blocks of various "orders".
810 * The bottom level table contains the map for the smallest allocatable
811 * units of memory (here, pages), and each level above it describes
812 * pairs of units from the levels below, hence, "buddies".
813 * At a high level, all that happens here is marking the table entry
814 * at the bottom level available, and propagating the changes upward
815 * as necessary, plus some accounting needed to play nicely with other
816 * parts of the VM system.
817 * At each level, we keep a list of pages, which are heads of continuous
818 * free pages of length of (1 << order) and marked with PageBuddy.
819 * Page's order is recorded in page_private(page) field.
820 * So when we are allocating or freeing one, we can derive the state of the
821 * other. That is, if we allocate a small block, and both were
822 * free, the remainder of the region must be split into blocks.
823 * If a block is freed, and its buddy is also free, then this
824 * triggers coalescing into a block of larger size.
825 *
826 * -- nyc
827 */
828
829 static inline void __free_one_page(struct page *page,
830 unsigned long pfn,
831 struct zone *zone, unsigned int order,
832 int migratetype)
833 {
834 unsigned long combined_pfn;
835 unsigned long uninitialized_var(buddy_pfn);
836 struct page *buddy;
837 unsigned int max_order;
838
839 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
840
841 VM_BUG_ON(!zone_is_initialized(zone));
842 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
843
844 VM_BUG_ON(migratetype == -1);
845 if (likely(!is_migrate_isolate(migratetype)))
846 __mod_zone_freepage_state(zone, 1 << order, migratetype);
847
848 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
849 VM_BUG_ON_PAGE(bad_range(zone, page), page);
850
851 continue_merging:
852 while (order < max_order - 1) {
853 buddy_pfn = __find_buddy_pfn(pfn, order);
854 buddy = page + (buddy_pfn - pfn);
855
856 if (!pfn_valid_within(buddy_pfn))
857 goto done_merging;
858 if (!page_is_buddy(page, buddy, order))
859 goto done_merging;
860 /*
861 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
862 * merge with it and move up one order.
863 */
864 if (page_is_guard(buddy)) {
865 clear_page_guard(zone, buddy, order, migratetype);
866 } else {
867 list_del(&buddy->lru);
868 zone->free_area[order].nr_free--;
869 rmv_page_order(buddy);
870 }
871 combined_pfn = buddy_pfn & pfn;
872 page = page + (combined_pfn - pfn);
873 pfn = combined_pfn;
874 order++;
875 }
876 if (max_order < MAX_ORDER) {
877 /* If we are here, it means order is >= pageblock_order.
878 * We want to prevent merge between freepages on isolate
879 * pageblock and normal pageblock. Without this, pageblock
880 * isolation could cause incorrect freepage or CMA accounting.
881 *
882 * We don't want to hit this code for the more frequent
883 * low-order merging.
884 */
885 if (unlikely(has_isolate_pageblock(zone))) {
886 int buddy_mt;
887
888 buddy_pfn = __find_buddy_pfn(pfn, order);
889 buddy = page + (buddy_pfn - pfn);
890 buddy_mt = get_pageblock_migratetype(buddy);
891
892 if (migratetype != buddy_mt
893 && (is_migrate_isolate(migratetype) ||
894 is_migrate_isolate(buddy_mt)))
895 goto done_merging;
896 }
897 max_order++;
898 goto continue_merging;
899 }
900
901 done_merging:
902 set_page_order(page, order);
903
904 /*
905 * If this is not the largest possible page, check if the buddy
906 * of the next-highest order is free. If it is, it's possible
907 * that pages are being freed that will coalesce soon. In case,
908 * that is happening, add the free page to the tail of the list
909 * so it's less likely to be used soon and more likely to be merged
910 * as a higher order page
911 */
912 if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)) {
913 struct page *higher_page, *higher_buddy;
914 combined_pfn = buddy_pfn & pfn;
915 higher_page = page + (combined_pfn - pfn);
916 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
917 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
918 if (pfn_valid_within(buddy_pfn) &&
919 page_is_buddy(higher_page, higher_buddy, order + 1)) {
920 list_add_tail(&page->lru,
921 &zone->free_area[order].free_list[migratetype]);
922 goto out;
923 }
924 }
925
926 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
927 out:
928 zone->free_area[order].nr_free++;
929 }
930
931 /*
932 * A bad page could be due to a number of fields. Instead of multiple branches,
933 * try and check multiple fields with one check. The caller must do a detailed
934 * check if necessary.
935 */
936 static inline bool page_expected_state(struct page *page,
937 unsigned long check_flags)
938 {
939 if (unlikely(atomic_read(&page->_mapcount) != -1))
940 return false;
941
942 if (unlikely((unsigned long)page->mapping |
943 page_ref_count(page) |
944 #ifdef CONFIG_MEMCG
945 (unsigned long)page->mem_cgroup |
946 #endif
947 (page->flags & check_flags)))
948 return false;
949
950 return true;
951 }
952
953 static void free_pages_check_bad(struct page *page)
954 {
955 const char *bad_reason;
956 unsigned long bad_flags;
957
958 bad_reason = NULL;
959 bad_flags = 0;
960
961 if (unlikely(atomic_read(&page->_mapcount) != -1))
962 bad_reason = "nonzero mapcount";
963 if (unlikely(page->mapping != NULL))
964 bad_reason = "non-NULL mapping";
965 if (unlikely(page_ref_count(page) != 0))
966 bad_reason = "nonzero _refcount";
967 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
968 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
969 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
970 }
971 #ifdef CONFIG_MEMCG
972 if (unlikely(page->mem_cgroup))
973 bad_reason = "page still charged to cgroup";
974 #endif
975 bad_page(page, bad_reason, bad_flags);
976 }
977
978 static inline int free_pages_check(struct page *page)
979 {
980 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
981 return 0;
982
983 /* Something has gone sideways, find it */
984 free_pages_check_bad(page);
985 return 1;
986 }
987
988 static int free_tail_pages_check(struct page *head_page, struct page *page)
989 {
990 int ret = 1;
991
992 /*
993 * We rely page->lru.next never has bit 0 set, unless the page
994 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
995 */
996 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
997
998 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
999 ret = 0;
1000 goto out;
1001 }
1002 switch (page - head_page) {
1003 case 1:
1004 /* the first tail page: ->mapping may be compound_mapcount() */
1005 if (unlikely(compound_mapcount(page))) {
1006 bad_page(page, "nonzero compound_mapcount", 0);
1007 goto out;
1008 }
1009 break;
1010 case 2:
1011 /*
1012 * the second tail page: ->mapping is
1013 * deferred_list.next -- ignore value.
1014 */
1015 break;
1016 default:
1017 if (page->mapping != TAIL_MAPPING) {
1018 bad_page(page, "corrupted mapping in tail page", 0);
1019 goto out;
1020 }
1021 break;
1022 }
1023 if (unlikely(!PageTail(page))) {
1024 bad_page(page, "PageTail not set", 0);
1025 goto out;
1026 }
1027 if (unlikely(compound_head(page) != head_page)) {
1028 bad_page(page, "compound_head not consistent", 0);
1029 goto out;
1030 }
1031 ret = 0;
1032 out:
1033 page->mapping = NULL;
1034 clear_compound_head(page);
1035 return ret;
1036 }
1037
1038 static __always_inline bool free_pages_prepare(struct page *page,
1039 unsigned int order, bool check_free)
1040 {
1041 int bad = 0;
1042
1043 VM_BUG_ON_PAGE(PageTail(page), page);
1044
1045 trace_mm_page_free(page, order);
1046
1047 /*
1048 * Check tail pages before head page information is cleared to
1049 * avoid checking PageCompound for order-0 pages.
1050 */
1051 if (unlikely(order)) {
1052 bool compound = PageCompound(page);
1053 int i;
1054
1055 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1056
1057 if (compound)
1058 ClearPageDoubleMap(page);
1059 for (i = 1; i < (1 << order); i++) {
1060 if (compound)
1061 bad += free_tail_pages_check(page, page + i);
1062 if (unlikely(free_pages_check(page + i))) {
1063 bad++;
1064 continue;
1065 }
1066 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1067 }
1068 }
1069 if (PageMappingFlags(page))
1070 page->mapping = NULL;
1071 if (memcg_kmem_enabled() && PageKmemcg(page))
1072 memcg_kmem_uncharge(page, order);
1073 if (check_free)
1074 bad += free_pages_check(page);
1075 if (bad)
1076 return false;
1077
1078 page_cpupid_reset_last(page);
1079 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1080 reset_page_owner(page, order);
1081
1082 if (!PageHighMem(page)) {
1083 debug_check_no_locks_freed(page_address(page),
1084 PAGE_SIZE << order);
1085 debug_check_no_obj_freed(page_address(page),
1086 PAGE_SIZE << order);
1087 }
1088 arch_free_page(page, order);
1089 kernel_poison_pages(page, 1 << order, 0);
1090 kernel_map_pages(page, 1 << order, 0);
1091 kasan_free_nondeferred_pages(page, order);
1092
1093 return true;
1094 }
1095
1096 #ifdef CONFIG_DEBUG_VM
1097 static inline bool free_pcp_prepare(struct page *page)
1098 {
1099 return free_pages_prepare(page, 0, true);
1100 }
1101
1102 static inline bool bulkfree_pcp_prepare(struct page *page)
1103 {
1104 return false;
1105 }
1106 #else
1107 static bool free_pcp_prepare(struct page *page)
1108 {
1109 return free_pages_prepare(page, 0, false);
1110 }
1111
1112 static bool bulkfree_pcp_prepare(struct page *page)
1113 {
1114 return free_pages_check(page);
1115 }
1116 #endif /* CONFIG_DEBUG_VM */
1117
1118 static inline void prefetch_buddy(struct page *page)
1119 {
1120 unsigned long pfn = page_to_pfn(page);
1121 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1122 struct page *buddy = page + (buddy_pfn - pfn);
1123
1124 prefetch(buddy);
1125 }
1126
1127 /*
1128 * Frees a number of pages from the PCP lists
1129 * Assumes all pages on list are in same zone, and of same order.
1130 * count is the number of pages to free.
1131 *
1132 * If the zone was previously in an "all pages pinned" state then look to
1133 * see if this freeing clears that state.
1134 *
1135 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1136 * pinned" detection logic.
1137 */
1138 static void free_pcppages_bulk(struct zone *zone, int count,
1139 struct per_cpu_pages *pcp)
1140 {
1141 int migratetype = 0;
1142 int batch_free = 0;
1143 int prefetch_nr = 0;
1144 bool isolated_pageblocks;
1145 struct page *page, *tmp;
1146 LIST_HEAD(head);
1147
1148 while (count) {
1149 struct list_head *list;
1150
1151 /*
1152 * Remove pages from lists in a round-robin fashion. A
1153 * batch_free count is maintained that is incremented when an
1154 * empty list is encountered. This is so more pages are freed
1155 * off fuller lists instead of spinning excessively around empty
1156 * lists
1157 */
1158 do {
1159 batch_free++;
1160 if (++migratetype == MIGRATE_PCPTYPES)
1161 migratetype = 0;
1162 list = &pcp->lists[migratetype];
1163 } while (list_empty(list));
1164
1165 /* This is the only non-empty list. Free them all. */
1166 if (batch_free == MIGRATE_PCPTYPES)
1167 batch_free = count;
1168
1169 do {
1170 page = list_last_entry(list, struct page, lru);
1171 /* must delete to avoid corrupting pcp list */
1172 list_del(&page->lru);
1173 pcp->count--;
1174
1175 if (bulkfree_pcp_prepare(page))
1176 continue;
1177
1178 list_add_tail(&page->lru, &head);
1179
1180 /*
1181 * We are going to put the page back to the global
1182 * pool, prefetch its buddy to speed up later access
1183 * under zone->lock. It is believed the overhead of
1184 * an additional test and calculating buddy_pfn here
1185 * can be offset by reduced memory latency later. To
1186 * avoid excessive prefetching due to large count, only
1187 * prefetch buddy for the first pcp->batch nr of pages.
1188 */
1189 if (prefetch_nr++ < pcp->batch)
1190 prefetch_buddy(page);
1191 } while (--count && --batch_free && !list_empty(list));
1192 }
1193
1194 spin_lock(&zone->lock);
1195 isolated_pageblocks = has_isolate_pageblock(zone);
1196
1197 /*
1198 * Use safe version since after __free_one_page(),
1199 * page->lru.next will not point to original list.
1200 */
1201 list_for_each_entry_safe(page, tmp, &head, lru) {
1202 int mt = get_pcppage_migratetype(page);
1203 /* MIGRATE_ISOLATE page should not go to pcplists */
1204 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1205 /* Pageblock could have been isolated meanwhile */
1206 if (unlikely(isolated_pageblocks))
1207 mt = get_pageblock_migratetype(page);
1208
1209 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
1210 trace_mm_page_pcpu_drain(page, 0, mt);
1211 }
1212 spin_unlock(&zone->lock);
1213 }
1214
1215 static void free_one_page(struct zone *zone,
1216 struct page *page, unsigned long pfn,
1217 unsigned int order,
1218 int migratetype)
1219 {
1220 spin_lock(&zone->lock);
1221 if (unlikely(has_isolate_pageblock(zone) ||
1222 is_migrate_isolate(migratetype))) {
1223 migratetype = get_pfnblock_migratetype(page, pfn);
1224 }
1225 __free_one_page(page, pfn, zone, order, migratetype);
1226 spin_unlock(&zone->lock);
1227 }
1228
1229 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1230 unsigned long zone, int nid)
1231 {
1232 mm_zero_struct_page(page);
1233 set_page_links(page, zone, nid, pfn);
1234 init_page_count(page);
1235 page_mapcount_reset(page);
1236 page_cpupid_reset_last(page);
1237 page_kasan_tag_reset(page);
1238
1239 INIT_LIST_HEAD(&page->lru);
1240 #ifdef WANT_PAGE_VIRTUAL
1241 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1242 if (!is_highmem_idx(zone))
1243 set_page_address(page, __va(pfn << PAGE_SHIFT));
1244 #endif
1245 }
1246
1247 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1248 static void __meminit init_reserved_page(unsigned long pfn)
1249 {
1250 pg_data_t *pgdat;
1251 int nid, zid;
1252
1253 if (!early_page_uninitialised(pfn))
1254 return;
1255
1256 nid = early_pfn_to_nid(pfn);
1257 pgdat = NODE_DATA(nid);
1258
1259 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1260 struct zone *zone = &pgdat->node_zones[zid];
1261
1262 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1263 break;
1264 }
1265 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1266 }
1267 #else
1268 static inline void init_reserved_page(unsigned long pfn)
1269 {
1270 }
1271 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1272
1273 /*
1274 * Initialised pages do not have PageReserved set. This function is
1275 * called for each range allocated by the bootmem allocator and
1276 * marks the pages PageReserved. The remaining valid pages are later
1277 * sent to the buddy page allocator.
1278 */
1279 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1280 {
1281 unsigned long start_pfn = PFN_DOWN(start);
1282 unsigned long end_pfn = PFN_UP(end);
1283
1284 for (; start_pfn < end_pfn; start_pfn++) {
1285 if (pfn_valid(start_pfn)) {
1286 struct page *page = pfn_to_page(start_pfn);
1287
1288 init_reserved_page(start_pfn);
1289
1290 /* Avoid false-positive PageTail() */
1291 INIT_LIST_HEAD(&page->lru);
1292
1293 /*
1294 * no need for atomic set_bit because the struct
1295 * page is not visible yet so nobody should
1296 * access it yet.
1297 */
1298 __SetPageReserved(page);
1299 }
1300 }
1301 }
1302
1303 static void __free_pages_ok(struct page *page, unsigned int order)
1304 {
1305 unsigned long flags;
1306 int migratetype;
1307 unsigned long pfn = page_to_pfn(page);
1308
1309 if (!free_pages_prepare(page, order, true))
1310 return;
1311
1312 migratetype = get_pfnblock_migratetype(page, pfn);
1313 local_irq_save(flags);
1314 __count_vm_events(PGFREE, 1 << order);
1315 free_one_page(page_zone(page), page, pfn, order, migratetype);
1316 local_irq_restore(flags);
1317 }
1318
1319 static void __init __free_pages_boot_core(struct page *page, unsigned int order)
1320 {
1321 unsigned int nr_pages = 1 << order;
1322 struct page *p = page;
1323 unsigned int loop;
1324
1325 prefetchw(p);
1326 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1327 prefetchw(p + 1);
1328 __ClearPageReserved(p);
1329 set_page_count(p, 0);
1330 }
1331 __ClearPageReserved(p);
1332 set_page_count(p, 0);
1333
1334 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1335 set_page_refcounted(page);
1336 __free_pages(page, order);
1337 }
1338
1339 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1340 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1341
1342 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1343
1344 int __meminit early_pfn_to_nid(unsigned long pfn)
1345 {
1346 static DEFINE_SPINLOCK(early_pfn_lock);
1347 int nid;
1348
1349 spin_lock(&early_pfn_lock);
1350 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1351 if (nid < 0)
1352 nid = first_online_node;
1353 spin_unlock(&early_pfn_lock);
1354
1355 return nid;
1356 }
1357 #endif
1358
1359 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1360 static inline bool __meminit __maybe_unused
1361 meminit_pfn_in_nid(unsigned long pfn, int node,
1362 struct mminit_pfnnid_cache *state)
1363 {
1364 int nid;
1365
1366 nid = __early_pfn_to_nid(pfn, state);
1367 if (nid >= 0 && nid != node)
1368 return false;
1369 return true;
1370 }
1371
1372 /* Only safe to use early in boot when initialisation is single-threaded */
1373 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1374 {
1375 return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1376 }
1377
1378 #else
1379
1380 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1381 {
1382 return true;
1383 }
1384 static inline bool __meminit __maybe_unused
1385 meminit_pfn_in_nid(unsigned long pfn, int node,
1386 struct mminit_pfnnid_cache *state)
1387 {
1388 return true;
1389 }
1390 #endif
1391
1392
1393 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1394 unsigned int order)
1395 {
1396 if (early_page_uninitialised(pfn))
1397 return;
1398 return __free_pages_boot_core(page, order);
1399 }
1400
1401 /*
1402 * Check that the whole (or subset of) a pageblock given by the interval of
1403 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1404 * with the migration of free compaction scanner. The scanners then need to
1405 * use only pfn_valid_within() check for arches that allow holes within
1406 * pageblocks.
1407 *
1408 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1409 *
1410 * It's possible on some configurations to have a setup like node0 node1 node0
1411 * i.e. it's possible that all pages within a zones range of pages do not
1412 * belong to a single zone. We assume that a border between node0 and node1
1413 * can occur within a single pageblock, but not a node0 node1 node0
1414 * interleaving within a single pageblock. It is therefore sufficient to check
1415 * the first and last page of a pageblock and avoid checking each individual
1416 * page in a pageblock.
1417 */
1418 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1419 unsigned long end_pfn, struct zone *zone)
1420 {
1421 struct page *start_page;
1422 struct page *end_page;
1423
1424 /* end_pfn is one past the range we are checking */
1425 end_pfn--;
1426
1427 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1428 return NULL;
1429
1430 start_page = pfn_to_online_page(start_pfn);
1431 if (!start_page)
1432 return NULL;
1433
1434 if (page_zone(start_page) != zone)
1435 return NULL;
1436
1437 end_page = pfn_to_page(end_pfn);
1438
1439 /* This gives a shorter code than deriving page_zone(end_page) */
1440 if (page_zone_id(start_page) != page_zone_id(end_page))
1441 return NULL;
1442
1443 return start_page;
1444 }
1445
1446 void set_zone_contiguous(struct zone *zone)
1447 {
1448 unsigned long block_start_pfn = zone->zone_start_pfn;
1449 unsigned long block_end_pfn;
1450
1451 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1452 for (; block_start_pfn < zone_end_pfn(zone);
1453 block_start_pfn = block_end_pfn,
1454 block_end_pfn += pageblock_nr_pages) {
1455
1456 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1457
1458 if (!__pageblock_pfn_to_page(block_start_pfn,
1459 block_end_pfn, zone))
1460 return;
1461 }
1462
1463 /* We confirm that there is no hole */
1464 zone->contiguous = true;
1465 }
1466
1467 void clear_zone_contiguous(struct zone *zone)
1468 {
1469 zone->contiguous = false;
1470 }
1471
1472 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1473 static void __init deferred_free_range(unsigned long pfn,
1474 unsigned long nr_pages)
1475 {
1476 struct page *page;
1477 unsigned long i;
1478
1479 if (!nr_pages)
1480 return;
1481
1482 page = pfn_to_page(pfn);
1483
1484 /* Free a large naturally-aligned chunk if possible */
1485 if (nr_pages == pageblock_nr_pages &&
1486 (pfn & (pageblock_nr_pages - 1)) == 0) {
1487 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1488 __free_pages_boot_core(page, pageblock_order);
1489 return;
1490 }
1491
1492 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1493 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1494 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1495 __free_pages_boot_core(page, 0);
1496 }
1497 }
1498
1499 /* Completion tracking for deferred_init_memmap() threads */
1500 static atomic_t pgdat_init_n_undone __initdata;
1501 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1502
1503 static inline void __init pgdat_init_report_one_done(void)
1504 {
1505 if (atomic_dec_and_test(&pgdat_init_n_undone))
1506 complete(&pgdat_init_all_done_comp);
1507 }
1508
1509 /*
1510 * Returns true if page needs to be initialized or freed to buddy allocator.
1511 *
1512 * First we check if pfn is valid on architectures where it is possible to have
1513 * holes within pageblock_nr_pages. On systems where it is not possible, this
1514 * function is optimized out.
1515 *
1516 * Then, we check if a current large page is valid by only checking the validity
1517 * of the head pfn.
1518 *
1519 * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
1520 * within a node: a pfn is between start and end of a node, but does not belong
1521 * to this memory node.
1522 */
1523 static inline bool __init
1524 deferred_pfn_valid(int nid, unsigned long pfn,
1525 struct mminit_pfnnid_cache *nid_init_state)
1526 {
1527 if (!pfn_valid_within(pfn))
1528 return false;
1529 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1530 return false;
1531 if (!meminit_pfn_in_nid(pfn, nid, nid_init_state))
1532 return false;
1533 return true;
1534 }
1535
1536 /*
1537 * Free pages to buddy allocator. Try to free aligned pages in
1538 * pageblock_nr_pages sizes.
1539 */
1540 static void __init deferred_free_pages(int nid, int zid, unsigned long pfn,
1541 unsigned long end_pfn)
1542 {
1543 struct mminit_pfnnid_cache nid_init_state = { };
1544 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1545 unsigned long nr_free = 0;
1546
1547 for (; pfn < end_pfn; pfn++) {
1548 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1549 deferred_free_range(pfn - nr_free, nr_free);
1550 nr_free = 0;
1551 } else if (!(pfn & nr_pgmask)) {
1552 deferred_free_range(pfn - nr_free, nr_free);
1553 nr_free = 1;
1554 touch_nmi_watchdog();
1555 } else {
1556 nr_free++;
1557 }
1558 }
1559 /* Free the last block of pages to allocator */
1560 deferred_free_range(pfn - nr_free, nr_free);
1561 }
1562
1563 /*
1564 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1565 * by performing it only once every pageblock_nr_pages.
1566 * Return number of pages initialized.
1567 */
1568 static unsigned long __init deferred_init_pages(int nid, int zid,
1569 unsigned long pfn,
1570 unsigned long end_pfn)
1571 {
1572 struct mminit_pfnnid_cache nid_init_state = { };
1573 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1574 unsigned long nr_pages = 0;
1575 struct page *page = NULL;
1576
1577 for (; pfn < end_pfn; pfn++) {
1578 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1579 page = NULL;
1580 continue;
1581 } else if (!page || !(pfn & nr_pgmask)) {
1582 page = pfn_to_page(pfn);
1583 touch_nmi_watchdog();
1584 } else {
1585 page++;
1586 }
1587 __init_single_page(page, pfn, zid, nid);
1588 nr_pages++;
1589 }
1590 return (nr_pages);
1591 }
1592
1593 /* Initialise remaining memory on a node */
1594 static int __init deferred_init_memmap(void *data)
1595 {
1596 pg_data_t *pgdat = data;
1597 int nid = pgdat->node_id;
1598 unsigned long start = jiffies;
1599 unsigned long nr_pages = 0;
1600 unsigned long spfn, epfn, first_init_pfn, flags;
1601 phys_addr_t spa, epa;
1602 int zid;
1603 struct zone *zone;
1604 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1605 u64 i;
1606
1607 /* Bind memory initialisation thread to a local node if possible */
1608 if (!cpumask_empty(cpumask))
1609 set_cpus_allowed_ptr(current, cpumask);
1610
1611 pgdat_resize_lock(pgdat, &flags);
1612 first_init_pfn = pgdat->first_deferred_pfn;
1613 if (first_init_pfn == ULONG_MAX) {
1614 pgdat_resize_unlock(pgdat, &flags);
1615 pgdat_init_report_one_done();
1616 return 0;
1617 }
1618
1619 /* Sanity check boundaries */
1620 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1621 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1622 pgdat->first_deferred_pfn = ULONG_MAX;
1623
1624 /* Only the highest zone is deferred so find it */
1625 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1626 zone = pgdat->node_zones + zid;
1627 if (first_init_pfn < zone_end_pfn(zone))
1628 break;
1629 }
1630 first_init_pfn = max(zone->zone_start_pfn, first_init_pfn);
1631
1632 /*
1633 * Initialize and free pages. We do it in two loops: first we initialize
1634 * struct page, than free to buddy allocator, because while we are
1635 * freeing pages we can access pages that are ahead (computing buddy
1636 * page in __free_one_page()).
1637 */
1638 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1639 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1640 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1641 nr_pages += deferred_init_pages(nid, zid, spfn, epfn);
1642 }
1643 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1644 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1645 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1646 deferred_free_pages(nid, zid, spfn, epfn);
1647 }
1648 pgdat_resize_unlock(pgdat, &flags);
1649
1650 /* Sanity check that the next zone really is unpopulated */
1651 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1652
1653 pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1654 jiffies_to_msecs(jiffies - start));
1655
1656 pgdat_init_report_one_done();
1657 return 0;
1658 }
1659
1660 /*
1661 * If this zone has deferred pages, try to grow it by initializing enough
1662 * deferred pages to satisfy the allocation specified by order, rounded up to
1663 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1664 * of SECTION_SIZE bytes by initializing struct pages in increments of
1665 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1666 *
1667 * Return true when zone was grown, otherwise return false. We return true even
1668 * when we grow less than requested, to let the caller decide if there are
1669 * enough pages to satisfy the allocation.
1670 *
1671 * Note: We use noinline because this function is needed only during boot, and
1672 * it is called from a __ref function _deferred_grow_zone. This way we are
1673 * making sure that it is not inlined into permanent text section.
1674 */
1675 static noinline bool __init
1676 deferred_grow_zone(struct zone *zone, unsigned int order)
1677 {
1678 int zid = zone_idx(zone);
1679 int nid = zone_to_nid(zone);
1680 pg_data_t *pgdat = NODE_DATA(nid);
1681 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1682 unsigned long nr_pages = 0;
1683 unsigned long first_init_pfn, spfn, epfn, t, flags;
1684 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1685 phys_addr_t spa, epa;
1686 u64 i;
1687
1688 /* Only the last zone may have deferred pages */
1689 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1690 return false;
1691
1692 pgdat_resize_lock(pgdat, &flags);
1693
1694 /*
1695 * If deferred pages have been initialized while we were waiting for
1696 * the lock, return true, as the zone was grown. The caller will retry
1697 * this zone. We won't return to this function since the caller also
1698 * has this static branch.
1699 */
1700 if (!static_branch_unlikely(&deferred_pages)) {
1701 pgdat_resize_unlock(pgdat, &flags);
1702 return true;
1703 }
1704
1705 /*
1706 * If someone grew this zone while we were waiting for spinlock, return
1707 * true, as there might be enough pages already.
1708 */
1709 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1710 pgdat_resize_unlock(pgdat, &flags);
1711 return true;
1712 }
1713
1714 first_init_pfn = max(zone->zone_start_pfn, first_deferred_pfn);
1715
1716 if (first_init_pfn >= pgdat_end_pfn(pgdat)) {
1717 pgdat_resize_unlock(pgdat, &flags);
1718 return false;
1719 }
1720
1721 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1722 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1723 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1724
1725 while (spfn < epfn && nr_pages < nr_pages_needed) {
1726 t = ALIGN(spfn + PAGES_PER_SECTION, PAGES_PER_SECTION);
1727 first_deferred_pfn = min(t, epfn);
1728 nr_pages += deferred_init_pages(nid, zid, spfn,
1729 first_deferred_pfn);
1730 spfn = first_deferred_pfn;
1731 }
1732
1733 if (nr_pages >= nr_pages_needed)
1734 break;
1735 }
1736
1737 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1738 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1739 epfn = min_t(unsigned long, first_deferred_pfn, PFN_DOWN(epa));
1740 deferred_free_pages(nid, zid, spfn, epfn);
1741
1742 if (first_deferred_pfn == epfn)
1743 break;
1744 }
1745 pgdat->first_deferred_pfn = first_deferred_pfn;
1746 pgdat_resize_unlock(pgdat, &flags);
1747
1748 return nr_pages > 0;
1749 }
1750
1751 /*
1752 * deferred_grow_zone() is __init, but it is called from
1753 * get_page_from_freelist() during early boot until deferred_pages permanently
1754 * disables this call. This is why we have refdata wrapper to avoid warning,
1755 * and to ensure that the function body gets unloaded.
1756 */
1757 static bool __ref
1758 _deferred_grow_zone(struct zone *zone, unsigned int order)
1759 {
1760 return deferred_grow_zone(zone, order);
1761 }
1762
1763 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1764
1765 void __init page_alloc_init_late(void)
1766 {
1767 struct zone *zone;
1768
1769 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1770 int nid;
1771
1772 /* There will be num_node_state(N_MEMORY) threads */
1773 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1774 for_each_node_state(nid, N_MEMORY) {
1775 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1776 }
1777
1778 /* Block until all are initialised */
1779 wait_for_completion(&pgdat_init_all_done_comp);
1780
1781 /*
1782 * We initialized the rest of the deferred pages. Permanently disable
1783 * on-demand struct page initialization.
1784 */
1785 static_branch_disable(&deferred_pages);
1786
1787 /* Reinit limits that are based on free pages after the kernel is up */
1788 files_maxfiles_init();
1789 #endif
1790 #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
1791 /* Discard memblock private memory */
1792 memblock_discard();
1793 #endif
1794
1795 for_each_populated_zone(zone)
1796 set_zone_contiguous(zone);
1797 }
1798
1799 #ifdef CONFIG_CMA
1800 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1801 void __init init_cma_reserved_pageblock(struct page *page)
1802 {
1803 unsigned i = pageblock_nr_pages;
1804 struct page *p = page;
1805
1806 do {
1807 __ClearPageReserved(p);
1808 set_page_count(p, 0);
1809 } while (++p, --i);
1810
1811 set_pageblock_migratetype(page, MIGRATE_CMA);
1812
1813 if (pageblock_order >= MAX_ORDER) {
1814 i = pageblock_nr_pages;
1815 p = page;
1816 do {
1817 set_page_refcounted(p);
1818 __free_pages(p, MAX_ORDER - 1);
1819 p += MAX_ORDER_NR_PAGES;
1820 } while (i -= MAX_ORDER_NR_PAGES);
1821 } else {
1822 set_page_refcounted(page);
1823 __free_pages(page, pageblock_order);
1824 }
1825
1826 adjust_managed_page_count(page, pageblock_nr_pages);
1827 }
1828 #endif
1829
1830 /*
1831 * The order of subdivision here is critical for the IO subsystem.
1832 * Please do not alter this order without good reasons and regression
1833 * testing. Specifically, as large blocks of memory are subdivided,
1834 * the order in which smaller blocks are delivered depends on the order
1835 * they're subdivided in this function. This is the primary factor
1836 * influencing the order in which pages are delivered to the IO
1837 * subsystem according to empirical testing, and this is also justified
1838 * by considering the behavior of a buddy system containing a single
1839 * large block of memory acted on by a series of small allocations.
1840 * This behavior is a critical factor in sglist merging's success.
1841 *
1842 * -- nyc
1843 */
1844 static inline void expand(struct zone *zone, struct page *page,
1845 int low, int high, struct free_area *area,
1846 int migratetype)
1847 {
1848 unsigned long size = 1 << high;
1849
1850 while (high > low) {
1851 area--;
1852 high--;
1853 size >>= 1;
1854 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1855
1856 /*
1857 * Mark as guard pages (or page), that will allow to
1858 * merge back to allocator when buddy will be freed.
1859 * Corresponding page table entries will not be touched,
1860 * pages will stay not present in virtual address space
1861 */
1862 if (set_page_guard(zone, &page[size], high, migratetype))
1863 continue;
1864
1865 list_add(&page[size].lru, &area->free_list[migratetype]);
1866 area->nr_free++;
1867 set_page_order(&page[size], high);
1868 }
1869 }
1870
1871 static void check_new_page_bad(struct page *page)
1872 {
1873 const char *bad_reason = NULL;
1874 unsigned long bad_flags = 0;
1875
1876 if (unlikely(atomic_read(&page->_mapcount) != -1))
1877 bad_reason = "nonzero mapcount";
1878 if (unlikely(page->mapping != NULL))
1879 bad_reason = "non-NULL mapping";
1880 if (unlikely(page_ref_count(page) != 0))
1881 bad_reason = "nonzero _count";
1882 if (unlikely(page->flags & __PG_HWPOISON)) {
1883 bad_reason = "HWPoisoned (hardware-corrupted)";
1884 bad_flags = __PG_HWPOISON;
1885 /* Don't complain about hwpoisoned pages */
1886 page_mapcount_reset(page); /* remove PageBuddy */
1887 return;
1888 }
1889 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1890 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1891 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1892 }
1893 #ifdef CONFIG_MEMCG
1894 if (unlikely(page->mem_cgroup))
1895 bad_reason = "page still charged to cgroup";
1896 #endif
1897 bad_page(page, bad_reason, bad_flags);
1898 }
1899
1900 /*
1901 * This page is about to be returned from the page allocator
1902 */
1903 static inline int check_new_page(struct page *page)
1904 {
1905 if (likely(page_expected_state(page,
1906 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1907 return 0;
1908
1909 check_new_page_bad(page);
1910 return 1;
1911 }
1912
1913 static inline bool free_pages_prezeroed(void)
1914 {
1915 return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
1916 page_poisoning_enabled();
1917 }
1918
1919 #ifdef CONFIG_DEBUG_VM
1920 static bool check_pcp_refill(struct page *page)
1921 {
1922 return false;
1923 }
1924
1925 static bool check_new_pcp(struct page *page)
1926 {
1927 return check_new_page(page);
1928 }
1929 #else
1930 static bool check_pcp_refill(struct page *page)
1931 {
1932 return check_new_page(page);
1933 }
1934 static bool check_new_pcp(struct page *page)
1935 {
1936 return false;
1937 }
1938 #endif /* CONFIG_DEBUG_VM */
1939
1940 static bool check_new_pages(struct page *page, unsigned int order)
1941 {
1942 int i;
1943 for (i = 0; i < (1 << order); i++) {
1944 struct page *p = page + i;
1945
1946 if (unlikely(check_new_page(p)))
1947 return true;
1948 }
1949
1950 return false;
1951 }
1952
1953 inline void post_alloc_hook(struct page *page, unsigned int order,
1954 gfp_t gfp_flags)
1955 {
1956 set_page_private(page, 0);
1957 set_page_refcounted(page);
1958
1959 arch_alloc_page(page, order);
1960 kernel_map_pages(page, 1 << order, 1);
1961 kasan_alloc_pages(page, order);
1962 kernel_poison_pages(page, 1 << order, 1);
1963 set_page_owner(page, order, gfp_flags);
1964 }
1965
1966 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1967 unsigned int alloc_flags)
1968 {
1969 int i;
1970
1971 post_alloc_hook(page, order, gfp_flags);
1972
1973 if (!free_pages_prezeroed() && (gfp_flags & __GFP_ZERO))
1974 for (i = 0; i < (1 << order); i++)
1975 clear_highpage(page + i);
1976
1977 if (order && (gfp_flags & __GFP_COMP))
1978 prep_compound_page(page, order);
1979
1980 /*
1981 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1982 * allocate the page. The expectation is that the caller is taking
1983 * steps that will free more memory. The caller should avoid the page
1984 * being used for !PFMEMALLOC purposes.
1985 */
1986 if (alloc_flags & ALLOC_NO_WATERMARKS)
1987 set_page_pfmemalloc(page);
1988 else
1989 clear_page_pfmemalloc(page);
1990 }
1991
1992 /*
1993 * Go through the free lists for the given migratetype and remove
1994 * the smallest available page from the freelists
1995 */
1996 static __always_inline
1997 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1998 int migratetype)
1999 {
2000 unsigned int current_order;
2001 struct free_area *area;
2002 struct page *page;
2003
2004 /* Find a page of the appropriate size in the preferred list */
2005 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2006 area = &(zone->free_area[current_order]);
2007 page = list_first_entry_or_null(&area->free_list[migratetype],
2008 struct page, lru);
2009 if (!page)
2010 continue;
2011 list_del(&page->lru);
2012 rmv_page_order(page);
2013 area->nr_free--;
2014 expand(zone, page, order, current_order, area, migratetype);
2015 set_pcppage_migratetype(page, migratetype);
2016 return page;
2017 }
2018
2019 return NULL;
2020 }
2021
2022
2023 /*
2024 * This array describes the order lists are fallen back to when
2025 * the free lists for the desirable migrate type are depleted
2026 */
2027 static int fallbacks[MIGRATE_TYPES][4] = {
2028 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2029 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2030 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2031 #ifdef CONFIG_CMA
2032 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2033 #endif
2034 #ifdef CONFIG_MEMORY_ISOLATION
2035 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2036 #endif
2037 };
2038
2039 #ifdef CONFIG_CMA
2040 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2041 unsigned int order)
2042 {
2043 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2044 }
2045 #else
2046 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2047 unsigned int order) { return NULL; }
2048 #endif
2049
2050 /*
2051 * Move the free pages in a range to the free lists of the requested type.
2052 * Note that start_page and end_pages are not aligned on a pageblock
2053 * boundary. If alignment is required, use move_freepages_block()
2054 */
2055 static int move_freepages(struct zone *zone,
2056 struct page *start_page, struct page *end_page,
2057 int migratetype, int *num_movable)
2058 {
2059 struct page *page;
2060 unsigned int order;
2061 int pages_moved = 0;
2062
2063 #ifndef CONFIG_HOLES_IN_ZONE
2064 /*
2065 * page_zone is not safe to call in this context when
2066 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
2067 * anyway as we check zone boundaries in move_freepages_block().
2068 * Remove at a later date when no bug reports exist related to
2069 * grouping pages by mobility
2070 */
2071 VM_BUG_ON(pfn_valid(page_to_pfn(start_page)) &&
2072 pfn_valid(page_to_pfn(end_page)) &&
2073 page_zone(start_page) != page_zone(end_page));
2074 #endif
2075 for (page = start_page; page <= end_page;) {
2076 if (!pfn_valid_within(page_to_pfn(page))) {
2077 page++;
2078 continue;
2079 }
2080
2081 /* Make sure we are not inadvertently changing nodes */
2082 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2083
2084 if (!PageBuddy(page)) {
2085 /*
2086 * We assume that pages that could be isolated for
2087 * migration are movable. But we don't actually try
2088 * isolating, as that would be expensive.
2089 */
2090 if (num_movable &&
2091 (PageLRU(page) || __PageMovable(page)))
2092 (*num_movable)++;
2093
2094 page++;
2095 continue;
2096 }
2097
2098 order = page_order(page);
2099 list_move(&page->lru,
2100 &zone->free_area[order].free_list[migratetype]);
2101 page += 1 << order;
2102 pages_moved += 1 << order;
2103 }
2104
2105 return pages_moved;
2106 }
2107
2108 int move_freepages_block(struct zone *zone, struct page *page,
2109 int migratetype, int *num_movable)
2110 {
2111 unsigned long start_pfn, end_pfn;
2112 struct page *start_page, *end_page;
2113
2114 if (num_movable)
2115 *num_movable = 0;
2116
2117 start_pfn = page_to_pfn(page);
2118 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2119 start_page = pfn_to_page(start_pfn);
2120 end_page = start_page + pageblock_nr_pages - 1;
2121 end_pfn = start_pfn + pageblock_nr_pages - 1;
2122
2123 /* Do not cross zone boundaries */
2124 if (!zone_spans_pfn(zone, start_pfn))
2125 start_page = page;
2126 if (!zone_spans_pfn(zone, end_pfn))
2127 return 0;
2128
2129 return move_freepages(zone, start_page, end_page, migratetype,
2130 num_movable);
2131 }
2132
2133 static void change_pageblock_range(struct page *pageblock_page,
2134 int start_order, int migratetype)
2135 {
2136 int nr_pageblocks = 1 << (start_order - pageblock_order);
2137
2138 while (nr_pageblocks--) {
2139 set_pageblock_migratetype(pageblock_page, migratetype);
2140 pageblock_page += pageblock_nr_pages;
2141 }
2142 }
2143
2144 /*
2145 * When we are falling back to another migratetype during allocation, try to
2146 * steal extra free pages from the same pageblocks to satisfy further
2147 * allocations, instead of polluting multiple pageblocks.
2148 *
2149 * If we are stealing a relatively large buddy page, it is likely there will
2150 * be more free pages in the pageblock, so try to steal them all. For
2151 * reclaimable and unmovable allocations, we steal regardless of page size,
2152 * as fragmentation caused by those allocations polluting movable pageblocks
2153 * is worse than movable allocations stealing from unmovable and reclaimable
2154 * pageblocks.
2155 */
2156 static bool can_steal_fallback(unsigned int order, int start_mt)
2157 {
2158 /*
2159 * Leaving this order check is intended, although there is
2160 * relaxed order check in next check. The reason is that
2161 * we can actually steal whole pageblock if this condition met,
2162 * but, below check doesn't guarantee it and that is just heuristic
2163 * so could be changed anytime.
2164 */
2165 if (order >= pageblock_order)
2166 return true;
2167
2168 if (order >= pageblock_order / 2 ||
2169 start_mt == MIGRATE_RECLAIMABLE ||
2170 start_mt == MIGRATE_UNMOVABLE ||
2171 page_group_by_mobility_disabled)
2172 return true;
2173
2174 return false;
2175 }
2176
2177 static inline void boost_watermark(struct zone *zone)
2178 {
2179 unsigned long max_boost;
2180
2181 if (!watermark_boost_factor)
2182 return;
2183
2184 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2185 watermark_boost_factor, 10000);
2186
2187 /*
2188 * high watermark may be uninitialised if fragmentation occurs
2189 * very early in boot so do not boost. We do not fall
2190 * through and boost by pageblock_nr_pages as failing
2191 * allocations that early means that reclaim is not going
2192 * to help and it may even be impossible to reclaim the
2193 * boosted watermark resulting in a hang.
2194 */
2195 if (!max_boost)
2196 return;
2197
2198 max_boost = max(pageblock_nr_pages, max_boost);
2199
2200 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2201 max_boost);
2202 }
2203
2204 /*
2205 * This function implements actual steal behaviour. If order is large enough,
2206 * we can steal whole pageblock. If not, we first move freepages in this
2207 * pageblock to our migratetype and determine how many already-allocated pages
2208 * are there in the pageblock with a compatible migratetype. If at least half
2209 * of pages are free or compatible, we can change migratetype of the pageblock
2210 * itself, so pages freed in the future will be put on the correct free list.
2211 */
2212 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2213 unsigned int alloc_flags, int start_type, bool whole_block)
2214 {
2215 unsigned int current_order = page_order(page);
2216 struct free_area *area;
2217 int free_pages, movable_pages, alike_pages;
2218 int old_block_type;
2219
2220 old_block_type = get_pageblock_migratetype(page);
2221
2222 /*
2223 * This can happen due to races and we want to prevent broken
2224 * highatomic accounting.
2225 */
2226 if (is_migrate_highatomic(old_block_type))
2227 goto single_page;
2228
2229 /* Take ownership for orders >= pageblock_order */
2230 if (current_order >= pageblock_order) {
2231 change_pageblock_range(page, current_order, start_type);
2232 goto single_page;
2233 }
2234
2235 /*
2236 * Boost watermarks to increase reclaim pressure to reduce the
2237 * likelihood of future fallbacks. Wake kswapd now as the node
2238 * may be balanced overall and kswapd will not wake naturally.
2239 */
2240 boost_watermark(zone);
2241 if (alloc_flags & ALLOC_KSWAPD)
2242 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2243
2244 /* We are not allowed to try stealing from the whole block */
2245 if (!whole_block)
2246 goto single_page;
2247
2248 free_pages = move_freepages_block(zone, page, start_type,
2249 &movable_pages);
2250 /*
2251 * Determine how many pages are compatible with our allocation.
2252 * For movable allocation, it's the number of movable pages which
2253 * we just obtained. For other types it's a bit more tricky.
2254 */
2255 if (start_type == MIGRATE_MOVABLE) {
2256 alike_pages = movable_pages;
2257 } else {
2258 /*
2259 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2260 * to MOVABLE pageblock, consider all non-movable pages as
2261 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2262 * vice versa, be conservative since we can't distinguish the
2263 * exact migratetype of non-movable pages.
2264 */
2265 if (old_block_type == MIGRATE_MOVABLE)
2266 alike_pages = pageblock_nr_pages
2267 - (free_pages + movable_pages);
2268 else
2269 alike_pages = 0;
2270 }
2271
2272 /* moving whole block can fail due to zone boundary conditions */
2273 if (!free_pages)
2274 goto single_page;
2275
2276 /*
2277 * If a sufficient number of pages in the block are either free or of
2278 * comparable migratability as our allocation, claim the whole block.
2279 */
2280 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2281 page_group_by_mobility_disabled)
2282 set_pageblock_migratetype(page, start_type);
2283
2284 return;
2285
2286 single_page:
2287 area = &zone->free_area[current_order];
2288 list_move(&page->lru, &area->free_list[start_type]);
2289 }
2290
2291 /*
2292 * Check whether there is a suitable fallback freepage with requested order.
2293 * If only_stealable is true, this function returns fallback_mt only if
2294 * we can steal other freepages all together. This would help to reduce
2295 * fragmentation due to mixed migratetype pages in one pageblock.
2296 */
2297 int find_suitable_fallback(struct free_area *area, unsigned int order,
2298 int migratetype, bool only_stealable, bool *can_steal)
2299 {
2300 int i;
2301 int fallback_mt;
2302
2303 if (area->nr_free == 0)
2304 return -1;
2305
2306 *can_steal = false;
2307 for (i = 0;; i++) {
2308 fallback_mt = fallbacks[migratetype][i];
2309 if (fallback_mt == MIGRATE_TYPES)
2310 break;
2311
2312 if (list_empty(&area->free_list[fallback_mt]))
2313 continue;
2314
2315 if (can_steal_fallback(order, migratetype))
2316 *can_steal = true;
2317
2318 if (!only_stealable)
2319 return fallback_mt;
2320
2321 if (*can_steal)
2322 return fallback_mt;
2323 }
2324
2325 return -1;
2326 }
2327
2328 /*
2329 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2330 * there are no empty page blocks that contain a page with a suitable order
2331 */
2332 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2333 unsigned int alloc_order)
2334 {
2335 int mt;
2336 unsigned long max_managed, flags;
2337
2338 /*
2339 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2340 * Check is race-prone but harmless.
2341 */
2342 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2343 if (zone->nr_reserved_highatomic >= max_managed)
2344 return;
2345
2346 spin_lock_irqsave(&zone->lock, flags);
2347
2348 /* Recheck the nr_reserved_highatomic limit under the lock */
2349 if (zone->nr_reserved_highatomic >= max_managed)
2350 goto out_unlock;
2351
2352 /* Yoink! */
2353 mt = get_pageblock_migratetype(page);
2354 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2355 && !is_migrate_cma(mt)) {
2356 zone->nr_reserved_highatomic += pageblock_nr_pages;
2357 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2358 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2359 }
2360
2361 out_unlock:
2362 spin_unlock_irqrestore(&zone->lock, flags);
2363 }
2364
2365 /*
2366 * Used when an allocation is about to fail under memory pressure. This
2367 * potentially hurts the reliability of high-order allocations when under
2368 * intense memory pressure but failed atomic allocations should be easier
2369 * to recover from than an OOM.
2370 *
2371 * If @force is true, try to unreserve a pageblock even though highatomic
2372 * pageblock is exhausted.
2373 */
2374 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2375 bool force)
2376 {
2377 struct zonelist *zonelist = ac->zonelist;
2378 unsigned long flags;
2379 struct zoneref *z;
2380 struct zone *zone;
2381 struct page *page;
2382 int order;
2383 bool ret;
2384
2385 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2386 ac->nodemask) {
2387 /*
2388 * Preserve at least one pageblock unless memory pressure
2389 * is really high.
2390 */
2391 if (!force && zone->nr_reserved_highatomic <=
2392 pageblock_nr_pages)
2393 continue;
2394
2395 spin_lock_irqsave(&zone->lock, flags);
2396 for (order = 0; order < MAX_ORDER; order++) {
2397 struct free_area *area = &(zone->free_area[order]);
2398
2399 page = list_first_entry_or_null(
2400 &area->free_list[MIGRATE_HIGHATOMIC],
2401 struct page, lru);
2402 if (!page)
2403 continue;
2404
2405 /*
2406 * In page freeing path, migratetype change is racy so
2407 * we can counter several free pages in a pageblock
2408 * in this loop althoug we changed the pageblock type
2409 * from highatomic to ac->migratetype. So we should
2410 * adjust the count once.
2411 */
2412 if (is_migrate_highatomic_page(page)) {
2413 /*
2414 * It should never happen but changes to
2415 * locking could inadvertently allow a per-cpu
2416 * drain to add pages to MIGRATE_HIGHATOMIC
2417 * while unreserving so be safe and watch for
2418 * underflows.
2419 */
2420 zone->nr_reserved_highatomic -= min(
2421 pageblock_nr_pages,
2422 zone->nr_reserved_highatomic);
2423 }
2424
2425 /*
2426 * Convert to ac->migratetype and avoid the normal
2427 * pageblock stealing heuristics. Minimally, the caller
2428 * is doing the work and needs the pages. More
2429 * importantly, if the block was always converted to
2430 * MIGRATE_UNMOVABLE or another type then the number
2431 * of pageblocks that cannot be completely freed
2432 * may increase.
2433 */
2434 set_pageblock_migratetype(page, ac->migratetype);
2435 ret = move_freepages_block(zone, page, ac->migratetype,
2436 NULL);
2437 if (ret) {
2438 spin_unlock_irqrestore(&zone->lock, flags);
2439 return ret;
2440 }
2441 }
2442 spin_unlock_irqrestore(&zone->lock, flags);
2443 }
2444
2445 return false;
2446 }
2447
2448 /*
2449 * Try finding a free buddy page on the fallback list and put it on the free
2450 * list of requested migratetype, possibly along with other pages from the same
2451 * block, depending on fragmentation avoidance heuristics. Returns true if
2452 * fallback was found so that __rmqueue_smallest() can grab it.
2453 *
2454 * The use of signed ints for order and current_order is a deliberate
2455 * deviation from the rest of this file, to make the for loop
2456 * condition simpler.
2457 */
2458 static __always_inline bool
2459 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2460 unsigned int alloc_flags)
2461 {
2462 struct free_area *area;
2463 int current_order;
2464 int min_order = order;
2465 struct page *page;
2466 int fallback_mt;
2467 bool can_steal;
2468
2469 /*
2470 * Do not steal pages from freelists belonging to other pageblocks
2471 * i.e. orders < pageblock_order. If there are no local zones free,
2472 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2473 */
2474 if (alloc_flags & ALLOC_NOFRAGMENT)
2475 min_order = pageblock_order;
2476
2477 /*
2478 * Find the largest available free page in the other list. This roughly
2479 * approximates finding the pageblock with the most free pages, which
2480 * would be too costly to do exactly.
2481 */
2482 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2483 --current_order) {
2484 area = &(zone->free_area[current_order]);
2485 fallback_mt = find_suitable_fallback(area, current_order,
2486 start_migratetype, false, &can_steal);
2487 if (fallback_mt == -1)
2488 continue;
2489
2490 /*
2491 * We cannot steal all free pages from the pageblock and the
2492 * requested migratetype is movable. In that case it's better to
2493 * steal and split the smallest available page instead of the
2494 * largest available page, because even if the next movable
2495 * allocation falls back into a different pageblock than this
2496 * one, it won't cause permanent fragmentation.
2497 */
2498 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2499 && current_order > order)
2500 goto find_smallest;
2501
2502 goto do_steal;
2503 }
2504
2505 return false;
2506
2507 find_smallest:
2508 for (current_order = order; current_order < MAX_ORDER;
2509 current_order++) {
2510 area = &(zone->free_area[current_order]);
2511 fallback_mt = find_suitable_fallback(area, current_order,
2512 start_migratetype, false, &can_steal);
2513 if (fallback_mt != -1)
2514 break;
2515 }
2516
2517 /*
2518 * This should not happen - we already found a suitable fallback
2519 * when looking for the largest page.
2520 */
2521 VM_BUG_ON(current_order == MAX_ORDER);
2522
2523 do_steal:
2524 page = list_first_entry(&area->free_list[fallback_mt],
2525 struct page, lru);
2526
2527 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2528 can_steal);
2529
2530 trace_mm_page_alloc_extfrag(page, order, current_order,
2531 start_migratetype, fallback_mt);
2532
2533 return true;
2534
2535 }
2536
2537 /*
2538 * Do the hard work of removing an element from the buddy allocator.
2539 * Call me with the zone->lock already held.
2540 */
2541 static __always_inline struct page *
2542 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2543 unsigned int alloc_flags)
2544 {
2545 struct page *page;
2546
2547 retry:
2548 page = __rmqueue_smallest(zone, order, migratetype);
2549 if (unlikely(!page)) {
2550 if (migratetype == MIGRATE_MOVABLE)
2551 page = __rmqueue_cma_fallback(zone, order);
2552
2553 if (!page && __rmqueue_fallback(zone, order, migratetype,
2554 alloc_flags))
2555 goto retry;
2556 }
2557
2558 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2559 return page;
2560 }
2561
2562 /*
2563 * Obtain a specified number of elements from the buddy allocator, all under
2564 * a single hold of the lock, for efficiency. Add them to the supplied list.
2565 * Returns the number of new pages which were placed at *list.
2566 */
2567 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2568 unsigned long count, struct list_head *list,
2569 int migratetype, unsigned int alloc_flags)
2570 {
2571 int i, alloced = 0;
2572
2573 spin_lock(&zone->lock);
2574 for (i = 0; i < count; ++i) {
2575 struct page *page = __rmqueue(zone, order, migratetype,
2576 alloc_flags);
2577 if (unlikely(page == NULL))
2578 break;
2579
2580 if (unlikely(check_pcp_refill(page)))
2581 continue;
2582
2583 /*
2584 * Split buddy pages returned by expand() are received here in
2585 * physical page order. The page is added to the tail of
2586 * caller's list. From the callers perspective, the linked list
2587 * is ordered by page number under some conditions. This is
2588 * useful for IO devices that can forward direction from the
2589 * head, thus also in the physical page order. This is useful
2590 * for IO devices that can merge IO requests if the physical
2591 * pages are ordered properly.
2592 */
2593 list_add_tail(&page->lru, list);
2594 alloced++;
2595 if (is_migrate_cma(get_pcppage_migratetype(page)))
2596 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2597 -(1 << order));
2598 }
2599
2600 /*
2601 * i pages were removed from the buddy list even if some leak due
2602 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2603 * on i. Do not confuse with 'alloced' which is the number of
2604 * pages added to the pcp list.
2605 */
2606 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2607 spin_unlock(&zone->lock);
2608 return alloced;
2609 }
2610
2611 #ifdef CONFIG_NUMA
2612 /*
2613 * Called from the vmstat counter updater to drain pagesets of this
2614 * currently executing processor on remote nodes after they have
2615 * expired.
2616 *
2617 * Note that this function must be called with the thread pinned to
2618 * a single processor.
2619 */
2620 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2621 {
2622 unsigned long flags;
2623 int to_drain, batch;
2624
2625 local_irq_save(flags);
2626 batch = READ_ONCE(pcp->batch);
2627 to_drain = min(pcp->count, batch);
2628 if (to_drain > 0)
2629 free_pcppages_bulk(zone, to_drain, pcp);
2630 local_irq_restore(flags);
2631 }
2632 #endif
2633
2634 /*
2635 * Drain pcplists of the indicated processor and zone.
2636 *
2637 * The processor must either be the current processor and the
2638 * thread pinned to the current processor or a processor that
2639 * is not online.
2640 */
2641 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2642 {
2643 unsigned long flags;
2644 struct per_cpu_pageset *pset;
2645 struct per_cpu_pages *pcp;
2646
2647 local_irq_save(flags);
2648 pset = per_cpu_ptr(zone->pageset, cpu);
2649
2650 pcp = &pset->pcp;
2651 if (pcp->count)
2652 free_pcppages_bulk(zone, pcp->count, pcp);
2653 local_irq_restore(flags);
2654 }
2655
2656 /*
2657 * Drain pcplists of all zones on the indicated processor.
2658 *
2659 * The processor must either be the current processor and the
2660 * thread pinned to the current processor or a processor that
2661 * is not online.
2662 */
2663 static void drain_pages(unsigned int cpu)
2664 {
2665 struct zone *zone;
2666
2667 for_each_populated_zone(zone) {
2668 drain_pages_zone(cpu, zone);
2669 }
2670 }
2671
2672 /*
2673 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2674 *
2675 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2676 * the single zone's pages.
2677 */
2678 void drain_local_pages(struct zone *zone)
2679 {
2680 int cpu = smp_processor_id();
2681
2682 if (zone)
2683 drain_pages_zone(cpu, zone);
2684 else
2685 drain_pages(cpu);
2686 }
2687
2688 static void drain_local_pages_wq(struct work_struct *work)
2689 {
2690 struct pcpu_drain *drain;
2691
2692 drain = container_of(work, struct pcpu_drain, work);
2693
2694 /*
2695 * drain_all_pages doesn't use proper cpu hotplug protection so
2696 * we can race with cpu offline when the WQ can move this from
2697 * a cpu pinned worker to an unbound one. We can operate on a different
2698 * cpu which is allright but we also have to make sure to not move to
2699 * a different one.
2700 */
2701 preempt_disable();
2702 drain_local_pages(drain->zone);
2703 preempt_enable();
2704 }
2705
2706 /*
2707 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2708 *
2709 * When zone parameter is non-NULL, spill just the single zone's pages.
2710 *
2711 * Note that this can be extremely slow as the draining happens in a workqueue.
2712 */
2713 void drain_all_pages(struct zone *zone)
2714 {
2715 int cpu;
2716
2717 /*
2718 * Allocate in the BSS so we wont require allocation in
2719 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2720 */
2721 static cpumask_t cpus_with_pcps;
2722
2723 /*
2724 * Make sure nobody triggers this path before mm_percpu_wq is fully
2725 * initialized.
2726 */
2727 if (WARN_ON_ONCE(!mm_percpu_wq))
2728 return;
2729
2730 /*
2731 * Do not drain if one is already in progress unless it's specific to
2732 * a zone. Such callers are primarily CMA and memory hotplug and need
2733 * the drain to be complete when the call returns.
2734 */
2735 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2736 if (!zone)
2737 return;
2738 mutex_lock(&pcpu_drain_mutex);
2739 }
2740
2741 /*
2742 * We don't care about racing with CPU hotplug event
2743 * as offline notification will cause the notified
2744 * cpu to drain that CPU pcps and on_each_cpu_mask
2745 * disables preemption as part of its processing
2746 */
2747 for_each_online_cpu(cpu) {
2748 struct per_cpu_pageset *pcp;
2749 struct zone *z;
2750 bool has_pcps = false;
2751
2752 if (zone) {
2753 pcp = per_cpu_ptr(zone->pageset, cpu);
2754 if (pcp->pcp.count)
2755 has_pcps = true;
2756 } else {
2757 for_each_populated_zone(z) {
2758 pcp = per_cpu_ptr(z->pageset, cpu);
2759 if (pcp->pcp.count) {
2760 has_pcps = true;
2761 break;
2762 }
2763 }
2764 }
2765
2766 if (has_pcps)
2767 cpumask_set_cpu(cpu, &cpus_with_pcps);
2768 else
2769 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2770 }
2771
2772 for_each_cpu(cpu, &cpus_with_pcps) {
2773 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
2774
2775 drain->zone = zone;
2776 INIT_WORK(&drain->work, drain_local_pages_wq);
2777 queue_work_on(cpu, mm_percpu_wq, &drain->work);
2778 }
2779 for_each_cpu(cpu, &cpus_with_pcps)
2780 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
2781
2782 mutex_unlock(&pcpu_drain_mutex);
2783 }
2784
2785 #ifdef CONFIG_HIBERNATION
2786
2787 /*
2788 * Touch the watchdog for every WD_PAGE_COUNT pages.
2789 */
2790 #define WD_PAGE_COUNT (128*1024)
2791
2792 void mark_free_pages(struct zone *zone)
2793 {
2794 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2795 unsigned long flags;
2796 unsigned int order, t;
2797 struct page *page;
2798
2799 if (zone_is_empty(zone))
2800 return;
2801
2802 spin_lock_irqsave(&zone->lock, flags);
2803
2804 max_zone_pfn = zone_end_pfn(zone);
2805 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2806 if (pfn_valid(pfn)) {
2807 page = pfn_to_page(pfn);
2808
2809 if (!--page_count) {
2810 touch_nmi_watchdog();
2811 page_count = WD_PAGE_COUNT;
2812 }
2813
2814 if (page_zone(page) != zone)
2815 continue;
2816
2817 if (!swsusp_page_is_forbidden(page))
2818 swsusp_unset_page_free(page);
2819 }
2820
2821 for_each_migratetype_order(order, t) {
2822 list_for_each_entry(page,
2823 &zone->free_area[order].free_list[t], lru) {
2824 unsigned long i;
2825
2826 pfn = page_to_pfn(page);
2827 for (i = 0; i < (1UL << order); i++) {
2828 if (!--page_count) {
2829 touch_nmi_watchdog();
2830 page_count = WD_PAGE_COUNT;
2831 }
2832 swsusp_set_page_free(pfn_to_page(pfn + i));
2833 }
2834 }
2835 }
2836 spin_unlock_irqrestore(&zone->lock, flags);
2837 }
2838 #endif /* CONFIG_PM */
2839
2840 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
2841 {
2842 int migratetype;
2843
2844 if (!free_pcp_prepare(page))
2845 return false;
2846
2847 migratetype = get_pfnblock_migratetype(page, pfn);
2848 set_pcppage_migratetype(page, migratetype);
2849 return true;
2850 }
2851
2852 static void free_unref_page_commit(struct page *page, unsigned long pfn)
2853 {
2854 struct zone *zone = page_zone(page);
2855 struct per_cpu_pages *pcp;
2856 int migratetype;
2857
2858 migratetype = get_pcppage_migratetype(page);
2859 __count_vm_event(PGFREE);
2860
2861 /*
2862 * We only track unmovable, reclaimable and movable on pcp lists.
2863 * Free ISOLATE pages back to the allocator because they are being
2864 * offlined but treat HIGHATOMIC as movable pages so we can get those
2865 * areas back if necessary. Otherwise, we may have to free
2866 * excessively into the page allocator
2867 */
2868 if (migratetype >= MIGRATE_PCPTYPES) {
2869 if (unlikely(is_migrate_isolate(migratetype))) {
2870 free_one_page(zone, page, pfn, 0, migratetype);
2871 return;
2872 }
2873 migratetype = MIGRATE_MOVABLE;
2874 }
2875
2876 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2877 list_add(&page->lru, &pcp->lists[migratetype]);
2878 pcp->count++;
2879 if (pcp->count >= pcp->high) {
2880 unsigned long batch = READ_ONCE(pcp->batch);
2881 free_pcppages_bulk(zone, batch, pcp);
2882 }
2883 }
2884
2885 /*
2886 * Free a 0-order page
2887 */
2888 void free_unref_page(struct page *page)
2889 {
2890 unsigned long flags;
2891 unsigned long pfn = page_to_pfn(page);
2892
2893 if (!free_unref_page_prepare(page, pfn))
2894 return;
2895
2896 local_irq_save(flags);
2897 free_unref_page_commit(page, pfn);
2898 local_irq_restore(flags);
2899 }
2900
2901 /*
2902 * Free a list of 0-order pages
2903 */
2904 void free_unref_page_list(struct list_head *list)
2905 {
2906 struct page *page, *next;
2907 unsigned long flags, pfn;
2908 int batch_count = 0;
2909
2910 /* Prepare pages for freeing */
2911 list_for_each_entry_safe(page, next, list, lru) {
2912 pfn = page_to_pfn(page);
2913 if (!free_unref_page_prepare(page, pfn))
2914 list_del(&page->lru);
2915 set_page_private(page, pfn);
2916 }
2917
2918 local_irq_save(flags);
2919 list_for_each_entry_safe(page, next, list, lru) {
2920 unsigned long pfn = page_private(page);
2921
2922 set_page_private(page, 0);
2923 trace_mm_page_free_batched(page);
2924 free_unref_page_commit(page, pfn);
2925
2926 /*
2927 * Guard against excessive IRQ disabled times when we get
2928 * a large list of pages to free.
2929 */
2930 if (++batch_count == SWAP_CLUSTER_MAX) {
2931 local_irq_restore(flags);
2932 batch_count = 0;
2933 local_irq_save(flags);
2934 }
2935 }
2936 local_irq_restore(flags);
2937 }
2938
2939 /*
2940 * split_page takes a non-compound higher-order page, and splits it into
2941 * n (1<<order) sub-pages: page[0..n]
2942 * Each sub-page must be freed individually.
2943 *
2944 * Note: this is probably too low level an operation for use in drivers.
2945 * Please consult with lkml before using this in your driver.
2946 */
2947 void split_page(struct page *page, unsigned int order)
2948 {
2949 int i;
2950
2951 VM_BUG_ON_PAGE(PageCompound(page), page);
2952 VM_BUG_ON_PAGE(!page_count(page), page);
2953
2954 for (i = 1; i < (1 << order); i++)
2955 set_page_refcounted(page + i);
2956 split_page_owner(page, order);
2957 }
2958 EXPORT_SYMBOL_GPL(split_page);
2959
2960 int __isolate_free_page(struct page *page, unsigned int order)
2961 {
2962 unsigned long watermark;
2963 struct zone *zone;
2964 int mt;
2965
2966 BUG_ON(!PageBuddy(page));
2967
2968 zone = page_zone(page);
2969 mt = get_pageblock_migratetype(page);
2970
2971 if (!is_migrate_isolate(mt)) {
2972 /*
2973 * Obey watermarks as if the page was being allocated. We can
2974 * emulate a high-order watermark check with a raised order-0
2975 * watermark, because we already know our high-order page
2976 * exists.
2977 */
2978 watermark = min_wmark_pages(zone) + (1UL << order);
2979 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
2980 return 0;
2981
2982 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2983 }
2984
2985 /* Remove page from free list */
2986 list_del(&page->lru);
2987 zone->free_area[order].nr_free--;
2988 rmv_page_order(page);
2989
2990 /*
2991 * Set the pageblock if the isolated page is at least half of a
2992 * pageblock
2993 */
2994 if (order >= pageblock_order - 1) {
2995 struct page *endpage = page + (1 << order) - 1;
2996 for (; page < endpage; page += pageblock_nr_pages) {
2997 int mt = get_pageblock_migratetype(page);
2998 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
2999 && !is_migrate_highatomic(mt))
3000 set_pageblock_migratetype(page,
3001 MIGRATE_MOVABLE);
3002 }
3003 }
3004
3005
3006 return 1UL << order;
3007 }
3008
3009 /*
3010 * Update NUMA hit/miss statistics
3011 *
3012 * Must be called with interrupts disabled.
3013 */
3014 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3015 {
3016 #ifdef CONFIG_NUMA
3017 enum numa_stat_item local_stat = NUMA_LOCAL;
3018
3019 /* skip numa counters update if numa stats is disabled */
3020 if (!static_branch_likely(&vm_numa_stat_key))
3021 return;
3022
3023 if (zone_to_nid(z) != numa_node_id())
3024 local_stat = NUMA_OTHER;
3025
3026 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3027 __inc_numa_state(z, NUMA_HIT);
3028 else {
3029 __inc_numa_state(z, NUMA_MISS);
3030 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3031 }
3032 __inc_numa_state(z, local_stat);
3033 #endif
3034 }
3035
3036 /* Remove page from the per-cpu list, caller must protect the list */
3037 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3038 unsigned int alloc_flags,
3039 struct per_cpu_pages *pcp,
3040 struct list_head *list)
3041 {
3042 struct page *page;
3043
3044 do {
3045 if (list_empty(list)) {
3046 pcp->count += rmqueue_bulk(zone, 0,
3047 pcp->batch, list,
3048 migratetype, alloc_flags);
3049 if (unlikely(list_empty(list)))
3050 return NULL;
3051 }
3052
3053 page = list_first_entry(list, struct page, lru);
3054 list_del(&page->lru);
3055 pcp->count--;
3056 } while (check_new_pcp(page));
3057
3058 return page;
3059 }
3060
3061 /* Lock and remove page from the per-cpu list */
3062 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3063 struct zone *zone, unsigned int order,
3064 gfp_t gfp_flags, int migratetype,
3065 unsigned int alloc_flags)
3066 {
3067 struct per_cpu_pages *pcp;
3068 struct list_head *list;
3069 struct page *page;
3070 unsigned long flags;
3071
3072 local_irq_save(flags);
3073 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3074 list = &pcp->lists[migratetype];
3075 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list);
3076 if (page) {
3077 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3078 zone_statistics(preferred_zone, zone);
3079 }
3080 local_irq_restore(flags);
3081 return page;
3082 }
3083
3084 /*
3085 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3086 */
3087 static inline
3088 struct page *rmqueue(struct zone *preferred_zone,
3089 struct zone *zone, unsigned int order,
3090 gfp_t gfp_flags, unsigned int alloc_flags,
3091 int migratetype)
3092 {
3093 unsigned long flags;
3094 struct page *page;
3095
3096 if (likely(order == 0)) {
3097 page = rmqueue_pcplist(preferred_zone, zone, order,
3098 gfp_flags, migratetype, alloc_flags);
3099 goto out;
3100 }
3101
3102 /*
3103 * We most definitely don't want callers attempting to
3104 * allocate greater than order-1 page units with __GFP_NOFAIL.
3105 */
3106 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3107 spin_lock_irqsave(&zone->lock, flags);
3108
3109 do {
3110 page = NULL;
3111 if (alloc_flags & ALLOC_HARDER) {
3112 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3113 if (page)
3114 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3115 }
3116 if (!page)
3117 page = __rmqueue(zone, order, migratetype, alloc_flags);
3118 } while (page && check_new_pages(page, order));
3119 spin_unlock(&zone->lock);
3120 if (!page)
3121 goto failed;
3122 __mod_zone_freepage_state(zone, -(1 << order),
3123 get_pcppage_migratetype(page));
3124
3125 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3126 zone_statistics(preferred_zone, zone);
3127 local_irq_restore(flags);
3128
3129 out:
3130 /* Separate test+clear to avoid unnecessary atomics */
3131 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3132 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3133 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3134 }
3135
3136 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3137 return page;
3138
3139 failed:
3140 local_irq_restore(flags);
3141 return NULL;
3142 }
3143
3144 #ifdef CONFIG_FAIL_PAGE_ALLOC
3145
3146 static struct {
3147 struct fault_attr attr;
3148
3149 bool ignore_gfp_highmem;
3150 bool ignore_gfp_reclaim;
3151 u32 min_order;
3152 } fail_page_alloc = {
3153 .attr = FAULT_ATTR_INITIALIZER,
3154 .ignore_gfp_reclaim = true,
3155 .ignore_gfp_highmem = true,
3156 .min_order = 1,
3157 };
3158
3159 static int __init setup_fail_page_alloc(char *str)
3160 {
3161 return setup_fault_attr(&fail_page_alloc.attr, str);
3162 }
3163 __setup("fail_page_alloc=", setup_fail_page_alloc);
3164
3165 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3166 {
3167 if (order < fail_page_alloc.min_order)
3168 return false;
3169 if (gfp_mask & __GFP_NOFAIL)
3170 return false;
3171 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3172 return false;
3173 if (fail_page_alloc.ignore_gfp_reclaim &&
3174 (gfp_mask & __GFP_DIRECT_RECLAIM))
3175 return false;
3176
3177 return should_fail(&fail_page_alloc.attr, 1 << order);
3178 }
3179
3180 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3181
3182 static int __init fail_page_alloc_debugfs(void)
3183 {
3184 umode_t mode = S_IFREG | 0600;
3185 struct dentry *dir;
3186
3187 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3188 &fail_page_alloc.attr);
3189 if (IS_ERR(dir))
3190 return PTR_ERR(dir);
3191
3192 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
3193 &fail_page_alloc.ignore_gfp_reclaim))
3194 goto fail;
3195 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3196 &fail_page_alloc.ignore_gfp_highmem))
3197 goto fail;
3198 if (!debugfs_create_u32("min-order", mode, dir,
3199 &fail_page_alloc.min_order))
3200 goto fail;
3201
3202 return 0;
3203 fail:
3204 debugfs_remove_recursive(dir);
3205
3206 return -ENOMEM;
3207 }
3208
3209 late_initcall(fail_page_alloc_debugfs);
3210
3211 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3212
3213 #else /* CONFIG_FAIL_PAGE_ALLOC */
3214
3215 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3216 {
3217 return false;
3218 }
3219
3220 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3221
3222 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3223 {
3224 return __should_fail_alloc_page(gfp_mask, order);
3225 }
3226 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3227
3228 /*
3229 * Return true if free base pages are above 'mark'. For high-order checks it
3230 * will return true of the order-0 watermark is reached and there is at least
3231 * one free page of a suitable size. Checking now avoids taking the zone lock
3232 * to check in the allocation paths if no pages are free.
3233 */
3234 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3235 int classzone_idx, unsigned int alloc_flags,
3236 long free_pages)
3237 {
3238 long min = mark;
3239 int o;
3240 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3241
3242 /* free_pages may go negative - that's OK */
3243 free_pages -= (1 << order) - 1;
3244
3245 if (alloc_flags & ALLOC_HIGH)
3246 min -= min / 2;
3247
3248 /*
3249 * If the caller does not have rights to ALLOC_HARDER then subtract
3250 * the high-atomic reserves. This will over-estimate the size of the
3251 * atomic reserve but it avoids a search.
3252 */
3253 if (likely(!alloc_harder)) {
3254 free_pages -= z->nr_reserved_highatomic;
3255 } else {
3256 /*
3257 * OOM victims can try even harder than normal ALLOC_HARDER
3258 * users on the grounds that it's definitely going to be in
3259 * the exit path shortly and free memory. Any allocation it
3260 * makes during the free path will be small and short-lived.
3261 */
3262 if (alloc_flags & ALLOC_OOM)
3263 min -= min / 2;
3264 else
3265 min -= min / 4;
3266 }
3267
3268
3269 #ifdef CONFIG_CMA
3270 /* If allocation can't use CMA areas don't use free CMA pages */
3271 if (!(alloc_flags & ALLOC_CMA))
3272 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3273 #endif
3274
3275 /*
3276 * Check watermarks for an order-0 allocation request. If these
3277 * are not met, then a high-order request also cannot go ahead
3278 * even if a suitable page happened to be free.
3279 */
3280 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3281 return false;
3282
3283 /* If this is an order-0 request then the watermark is fine */
3284 if (!order)
3285 return true;
3286
3287 /* For a high-order request, check at least one suitable page is free */
3288 for (o = order; o < MAX_ORDER; o++) {
3289 struct free_area *area = &z->free_area[o];
3290 int mt;
3291
3292 if (!area->nr_free)
3293 continue;
3294
3295 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3296 if (!list_empty(&area->free_list[mt]))
3297 return true;
3298 }
3299
3300 #ifdef CONFIG_CMA
3301 if ((alloc_flags & ALLOC_CMA) &&
3302 !list_empty(&area->free_list[MIGRATE_CMA])) {
3303 return true;
3304 }
3305 #endif
3306 if (alloc_harder &&
3307 !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3308 return true;
3309 }
3310 return false;
3311 }
3312
3313 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3314 int classzone_idx, unsigned int alloc_flags)
3315 {
3316 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3317 zone_page_state(z, NR_FREE_PAGES));
3318 }
3319
3320 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3321 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3322 {
3323 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3324 long cma_pages = 0;
3325
3326 #ifdef CONFIG_CMA
3327 /* If allocation can't use CMA areas don't use free CMA pages */
3328 if (!(alloc_flags & ALLOC_CMA))
3329 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3330 #endif
3331
3332 /*
3333 * Fast check for order-0 only. If this fails then the reserves
3334 * need to be calculated. There is a corner case where the check
3335 * passes but only the high-order atomic reserve are free. If
3336 * the caller is !atomic then it'll uselessly search the free
3337 * list. That corner case is then slower but it is harmless.
3338 */
3339 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3340 return true;
3341
3342 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3343 free_pages);
3344 }
3345
3346 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3347 unsigned long mark, int classzone_idx)
3348 {
3349 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3350
3351 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3352 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3353
3354 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3355 free_pages);
3356 }
3357
3358 #ifdef CONFIG_NUMA
3359 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3360 {
3361 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3362 RECLAIM_DISTANCE;
3363 }
3364 #else /* CONFIG_NUMA */
3365 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3366 {
3367 return true;
3368 }
3369 #endif /* CONFIG_NUMA */
3370
3371 /*
3372 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3373 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3374 * premature use of a lower zone may cause lowmem pressure problems that
3375 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3376 * probably too small. It only makes sense to spread allocations to avoid
3377 * fragmentation between the Normal and DMA32 zones.
3378 */
3379 static inline unsigned int
3380 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3381 {
3382 unsigned int alloc_flags = 0;
3383
3384 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3385 alloc_flags |= ALLOC_KSWAPD;
3386
3387 #ifdef CONFIG_ZONE_DMA32
3388 if (zone_idx(zone) != ZONE_NORMAL)
3389 goto out;
3390
3391 /*
3392 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3393 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3394 * on UMA that if Normal is populated then so is DMA32.
3395 */
3396 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3397 if (nr_online_nodes > 1 && !populated_zone(--zone))
3398 goto out;
3399
3400 out:
3401 #endif /* CONFIG_ZONE_DMA32 */
3402 return alloc_flags;
3403 }
3404
3405 /*
3406 * get_page_from_freelist goes through the zonelist trying to allocate
3407 * a page.
3408 */
3409 static struct page *
3410 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3411 const struct alloc_context *ac)
3412 {
3413 struct zoneref *z;
3414 struct zone *zone;
3415 struct pglist_data *last_pgdat_dirty_limit = NULL;
3416 bool no_fallback;
3417
3418 retry:
3419 /*
3420 * Scan zonelist, looking for a zone with enough free.
3421 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3422 */
3423 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3424 z = ac->preferred_zoneref;
3425 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3426 ac->nodemask) {
3427 struct page *page;
3428 unsigned long mark;
3429
3430 if (cpusets_enabled() &&
3431 (alloc_flags & ALLOC_CPUSET) &&
3432 !__cpuset_zone_allowed(zone, gfp_mask))
3433 continue;
3434 /*
3435 * When allocating a page cache page for writing, we
3436 * want to get it from a node that is within its dirty
3437 * limit, such that no single node holds more than its
3438 * proportional share of globally allowed dirty pages.
3439 * The dirty limits take into account the node's
3440 * lowmem reserves and high watermark so that kswapd
3441 * should be able to balance it without having to
3442 * write pages from its LRU list.
3443 *
3444 * XXX: For now, allow allocations to potentially
3445 * exceed the per-node dirty limit in the slowpath
3446 * (spread_dirty_pages unset) before going into reclaim,
3447 * which is important when on a NUMA setup the allowed
3448 * nodes are together not big enough to reach the
3449 * global limit. The proper fix for these situations
3450 * will require awareness of nodes in the
3451 * dirty-throttling and the flusher threads.
3452 */
3453 if (ac->spread_dirty_pages) {
3454 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3455 continue;
3456
3457 if (!node_dirty_ok(zone->zone_pgdat)) {
3458 last_pgdat_dirty_limit = zone->zone_pgdat;
3459 continue;
3460 }
3461 }
3462
3463 if (no_fallback && nr_online_nodes > 1 &&
3464 zone != ac->preferred_zoneref->zone) {
3465 int local_nid;
3466
3467 /*
3468 * If moving to a remote node, retry but allow
3469 * fragmenting fallbacks. Locality is more important
3470 * than fragmentation avoidance.
3471 */
3472 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3473 if (zone_to_nid(zone) != local_nid) {
3474 alloc_flags &= ~ALLOC_NOFRAGMENT;
3475 goto retry;
3476 }
3477 }
3478
3479 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3480 if (!zone_watermark_fast(zone, order, mark,
3481 ac_classzone_idx(ac), alloc_flags)) {
3482 int ret;
3483
3484 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3485 /*
3486 * Watermark failed for this zone, but see if we can
3487 * grow this zone if it contains deferred pages.
3488 */
3489 if (static_branch_unlikely(&deferred_pages)) {
3490 if (_deferred_grow_zone(zone, order))
3491 goto try_this_zone;
3492 }
3493 #endif
3494 /* Checked here to keep the fast path fast */
3495 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3496 if (alloc_flags & ALLOC_NO_WATERMARKS)
3497 goto try_this_zone;
3498
3499 if (node_reclaim_mode == 0 ||
3500 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3501 continue;
3502
3503 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3504 switch (ret) {
3505 case NODE_RECLAIM_NOSCAN:
3506 /* did not scan */
3507 continue;
3508 case NODE_RECLAIM_FULL:
3509 /* scanned but unreclaimable */
3510 continue;
3511 default:
3512 /* did we reclaim enough */
3513 if (zone_watermark_ok(zone, order, mark,
3514 ac_classzone_idx(ac), alloc_flags))
3515 goto try_this_zone;
3516
3517 continue;
3518 }
3519 }
3520
3521 try_this_zone:
3522 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3523 gfp_mask, alloc_flags, ac->migratetype);
3524 if (page) {
3525 prep_new_page(page, order, gfp_mask, alloc_flags);
3526
3527 /*
3528 * If this is a high-order atomic allocation then check
3529 * if the pageblock should be reserved for the future
3530 */
3531 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3532 reserve_highatomic_pageblock(page, zone, order);
3533
3534 return page;
3535 } else {
3536 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3537 /* Try again if zone has deferred pages */
3538 if (static_branch_unlikely(&deferred_pages)) {
3539 if (_deferred_grow_zone(zone, order))
3540 goto try_this_zone;
3541 }
3542 #endif
3543 }
3544 }
3545
3546 /*
3547 * It's possible on a UMA machine to get through all zones that are
3548 * fragmented. If avoiding fragmentation, reset and try again.
3549 */
3550 if (no_fallback) {
3551 alloc_flags &= ~ALLOC_NOFRAGMENT;
3552 goto retry;
3553 }
3554
3555 return NULL;
3556 }
3557
3558 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3559 {
3560 unsigned int filter = SHOW_MEM_FILTER_NODES;
3561 static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
3562
3563 if (!__ratelimit(&show_mem_rs))
3564 return;
3565
3566 /*
3567 * This documents exceptions given to allocations in certain
3568 * contexts that are allowed to allocate outside current's set
3569 * of allowed nodes.
3570 */
3571 if (!(gfp_mask & __GFP_NOMEMALLOC))
3572 if (tsk_is_oom_victim(current) ||
3573 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3574 filter &= ~SHOW_MEM_FILTER_NODES;
3575 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3576 filter &= ~SHOW_MEM_FILTER_NODES;
3577
3578 show_mem(filter, nodemask);
3579 }
3580
3581 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3582 {
3583 struct va_format vaf;
3584 va_list args;
3585 static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
3586 DEFAULT_RATELIMIT_BURST);
3587
3588 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3589 return;
3590
3591 va_start(args, fmt);
3592 vaf.fmt = fmt;
3593 vaf.va = &args;
3594 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3595 current->comm, &vaf, gfp_mask, &gfp_mask,
3596 nodemask_pr_args(nodemask));
3597 va_end(args);
3598
3599 cpuset_print_current_mems_allowed();
3600 pr_cont("\n");
3601 dump_stack();
3602 warn_alloc_show_mem(gfp_mask, nodemask);
3603 }
3604
3605 static inline struct page *
3606 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3607 unsigned int alloc_flags,
3608 const struct alloc_context *ac)
3609 {
3610 struct page *page;
3611
3612 page = get_page_from_freelist(gfp_mask, order,
3613 alloc_flags|ALLOC_CPUSET, ac);
3614 /*
3615 * fallback to ignore cpuset restriction if our nodes
3616 * are depleted
3617 */
3618 if (!page)
3619 page = get_page_from_freelist(gfp_mask, order,
3620 alloc_flags, ac);
3621
3622 return page;
3623 }
3624
3625 static inline struct page *
3626 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3627 const struct alloc_context *ac, unsigned long *did_some_progress)
3628 {
3629 struct oom_control oc = {
3630 .zonelist = ac->zonelist,
3631 .nodemask = ac->nodemask,
3632 .memcg = NULL,
3633 .gfp_mask = gfp_mask,
3634 .order = order,
3635 };
3636 struct page *page;
3637
3638 *did_some_progress = 0;
3639
3640 /*
3641 * Acquire the oom lock. If that fails, somebody else is
3642 * making progress for us.
3643 */
3644 if (!mutex_trylock(&oom_lock)) {
3645 *did_some_progress = 1;
3646 schedule_timeout_uninterruptible(1);
3647 return NULL;
3648 }
3649
3650 /*
3651 * Go through the zonelist yet one more time, keep very high watermark
3652 * here, this is only to catch a parallel oom killing, we must fail if
3653 * we're still under heavy pressure. But make sure that this reclaim
3654 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3655 * allocation which will never fail due to oom_lock already held.
3656 */
3657 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3658 ~__GFP_DIRECT_RECLAIM, order,
3659 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3660 if (page)
3661 goto out;
3662
3663 /* Coredumps can quickly deplete all memory reserves */
3664 if (current->flags & PF_DUMPCORE)
3665 goto out;
3666 /* The OOM killer will not help higher order allocs */
3667 if (order > PAGE_ALLOC_COSTLY_ORDER)
3668 goto out;
3669 /*
3670 * We have already exhausted all our reclaim opportunities without any
3671 * success so it is time to admit defeat. We will skip the OOM killer
3672 * because it is very likely that the caller has a more reasonable
3673 * fallback than shooting a random task.
3674 */
3675 if (gfp_mask & __GFP_RETRY_MAYFAIL)
3676 goto out;
3677 /* The OOM killer does not needlessly kill tasks for lowmem */
3678 if (ac->high_zoneidx < ZONE_NORMAL)
3679 goto out;
3680 if (pm_suspended_storage())
3681 goto out;
3682 /*
3683 * XXX: GFP_NOFS allocations should rather fail than rely on
3684 * other request to make a forward progress.
3685 * We are in an unfortunate situation where out_of_memory cannot
3686 * do much for this context but let's try it to at least get
3687 * access to memory reserved if the current task is killed (see
3688 * out_of_memory). Once filesystems are ready to handle allocation
3689 * failures more gracefully we should just bail out here.
3690 */
3691
3692 /* The OOM killer may not free memory on a specific node */
3693 if (gfp_mask & __GFP_THISNODE)
3694 goto out;
3695
3696 /* Exhausted what can be done so it's blame time */
3697 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3698 *did_some_progress = 1;
3699
3700 /*
3701 * Help non-failing allocations by giving them access to memory
3702 * reserves
3703 */
3704 if (gfp_mask & __GFP_NOFAIL)
3705 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3706 ALLOC_NO_WATERMARKS, ac);
3707 }
3708 out:
3709 mutex_unlock(&oom_lock);
3710 return page;
3711 }
3712
3713 /*
3714 * Maximum number of compaction retries wit a progress before OOM
3715 * killer is consider as the only way to move forward.
3716 */
3717 #define MAX_COMPACT_RETRIES 16
3718
3719 #ifdef CONFIG_COMPACTION
3720 /* Try memory compaction for high-order allocations before reclaim */
3721 static struct page *
3722 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3723 unsigned int alloc_flags, const struct alloc_context *ac,
3724 enum compact_priority prio, enum compact_result *compact_result)
3725 {
3726 struct page *page;
3727 unsigned long pflags;
3728 unsigned int noreclaim_flag;
3729
3730 if (!order)
3731 return NULL;
3732
3733 psi_memstall_enter(&pflags);
3734 noreclaim_flag = memalloc_noreclaim_save();
3735
3736 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3737 prio);
3738
3739 memalloc_noreclaim_restore(noreclaim_flag);
3740 psi_memstall_leave(&pflags);
3741
3742 if (*compact_result <= COMPACT_INACTIVE)
3743 return NULL;
3744
3745 /*
3746 * At least in one zone compaction wasn't deferred or skipped, so let's
3747 * count a compaction stall
3748 */
3749 count_vm_event(COMPACTSTALL);
3750
3751 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3752
3753 if (page) {
3754 struct zone *zone = page_zone(page);
3755
3756 zone->compact_blockskip_flush = false;
3757 compaction_defer_reset(zone, order, true);
3758 count_vm_event(COMPACTSUCCESS);
3759 return page;
3760 }
3761
3762 /*
3763 * It's bad if compaction run occurs and fails. The most likely reason
3764 * is that pages exist, but not enough to satisfy watermarks.
3765 */
3766 count_vm_event(COMPACTFAIL);
3767
3768 cond_resched();
3769
3770 return NULL;
3771 }
3772
3773 static inline bool
3774 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
3775 enum compact_result compact_result,
3776 enum compact_priority *compact_priority,
3777 int *compaction_retries)
3778 {
3779 int max_retries = MAX_COMPACT_RETRIES;
3780 int min_priority;
3781 bool ret = false;
3782 int retries = *compaction_retries;
3783 enum compact_priority priority = *compact_priority;
3784
3785 if (!order)
3786 return false;
3787
3788 if (compaction_made_progress(compact_result))
3789 (*compaction_retries)++;
3790
3791 /*
3792 * compaction considers all the zone as desperately out of memory
3793 * so it doesn't really make much sense to retry except when the
3794 * failure could be caused by insufficient priority
3795 */
3796 if (compaction_failed(compact_result))
3797 goto check_priority;
3798
3799 /*
3800 * make sure the compaction wasn't deferred or didn't bail out early
3801 * due to locks contention before we declare that we should give up.
3802 * But do not retry if the given zonelist is not suitable for
3803 * compaction.
3804 */
3805 if (compaction_withdrawn(compact_result)) {
3806 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
3807 goto out;
3808 }
3809
3810 /*
3811 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
3812 * costly ones because they are de facto nofail and invoke OOM
3813 * killer to move on while costly can fail and users are ready
3814 * to cope with that. 1/4 retries is rather arbitrary but we
3815 * would need much more detailed feedback from compaction to
3816 * make a better decision.
3817 */
3818 if (order > PAGE_ALLOC_COSTLY_ORDER)
3819 max_retries /= 4;
3820 if (*compaction_retries <= max_retries) {
3821 ret = true;
3822 goto out;
3823 }
3824
3825 /*
3826 * Make sure there are attempts at the highest priority if we exhausted
3827 * all retries or failed at the lower priorities.
3828 */
3829 check_priority:
3830 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
3831 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
3832
3833 if (*compact_priority > min_priority) {
3834 (*compact_priority)--;
3835 *compaction_retries = 0;
3836 ret = true;
3837 }
3838 out:
3839 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
3840 return ret;
3841 }
3842 #else
3843 static inline struct page *
3844 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3845 unsigned int alloc_flags, const struct alloc_context *ac,
3846 enum compact_priority prio, enum compact_result *compact_result)
3847 {
3848 *compact_result = COMPACT_SKIPPED;
3849 return NULL;
3850 }
3851
3852 static inline bool
3853 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
3854 enum compact_result compact_result,
3855 enum compact_priority *compact_priority,
3856 int *compaction_retries)
3857 {
3858 struct zone *zone;
3859 struct zoneref *z;
3860
3861 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
3862 return false;
3863
3864 /*
3865 * There are setups with compaction disabled which would prefer to loop
3866 * inside the allocator rather than hit the oom killer prematurely.
3867 * Let's give them a good hope and keep retrying while the order-0
3868 * watermarks are OK.
3869 */
3870 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3871 ac->nodemask) {
3872 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
3873 ac_classzone_idx(ac), alloc_flags))
3874 return true;
3875 }
3876 return false;
3877 }
3878 #endif /* CONFIG_COMPACTION */
3879
3880 #ifdef CONFIG_LOCKDEP
3881 static struct lockdep_map __fs_reclaim_map =
3882 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
3883
3884 static bool __need_fs_reclaim(gfp_t gfp_mask)
3885 {
3886 gfp_mask = current_gfp_context(gfp_mask);
3887
3888 /* no reclaim without waiting on it */
3889 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
3890 return false;
3891
3892 /* this guy won't enter reclaim */
3893 if (current->flags & PF_MEMALLOC)
3894 return false;
3895
3896 /* We're only interested __GFP_FS allocations for now */
3897 if (!(gfp_mask & __GFP_FS))
3898 return false;
3899
3900 if (gfp_mask & __GFP_NOLOCKDEP)
3901 return false;
3902
3903 return true;
3904 }
3905
3906 void __fs_reclaim_acquire(void)
3907 {
3908 lock_map_acquire(&__fs_reclaim_map);
3909 }
3910
3911 void __fs_reclaim_release(void)
3912 {
3913 lock_map_release(&__fs_reclaim_map);
3914 }
3915
3916 void fs_reclaim_acquire(gfp_t gfp_mask)
3917 {
3918 if (__need_fs_reclaim(gfp_mask))
3919 __fs_reclaim_acquire();
3920 }
3921 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
3922
3923 void fs_reclaim_release(gfp_t gfp_mask)
3924 {
3925 if (__need_fs_reclaim(gfp_mask))
3926 __fs_reclaim_release();
3927 }
3928 EXPORT_SYMBOL_GPL(fs_reclaim_release);
3929 #endif
3930
3931 /* Perform direct synchronous page reclaim */
3932 static int
3933 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
3934 const struct alloc_context *ac)
3935 {
3936 struct reclaim_state reclaim_state;
3937 int progress;
3938 unsigned int noreclaim_flag;
3939 unsigned long pflags;
3940
3941 cond_resched();
3942
3943 /* We now go into synchronous reclaim */
3944 cpuset_memory_pressure_bump();
3945 psi_memstall_enter(&pflags);
3946 fs_reclaim_acquire(gfp_mask);
3947 noreclaim_flag = memalloc_noreclaim_save();
3948 reclaim_state.reclaimed_slab = 0;
3949 current->reclaim_state = &reclaim_state;
3950
3951 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
3952 ac->nodemask);
3953
3954 current->reclaim_state = NULL;
3955 memalloc_noreclaim_restore(noreclaim_flag);
3956 fs_reclaim_release(gfp_mask);
3957 psi_memstall_leave(&pflags);
3958
3959 cond_resched();
3960
3961 return progress;
3962 }
3963
3964 /* The really slow allocator path where we enter direct reclaim */
3965 static inline struct page *
3966 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
3967 unsigned int alloc_flags, const struct alloc_context *ac,
3968 unsigned long *did_some_progress)
3969 {
3970 struct page *page = NULL;
3971 bool drained = false;
3972
3973 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
3974 if (unlikely(!(*did_some_progress)))
3975 return NULL;
3976
3977 retry:
3978 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3979
3980 /*
3981 * If an allocation failed after direct reclaim, it could be because
3982 * pages are pinned on the per-cpu lists or in high alloc reserves.
3983 * Shrink them them and try again
3984 */
3985 if (!page && !drained) {
3986 unreserve_highatomic_pageblock(ac, false);
3987 drain_all_pages(NULL);
3988 drained = true;
3989 goto retry;
3990 }
3991
3992 return page;
3993 }
3994
3995 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
3996 const struct alloc_context *ac)
3997 {
3998 struct zoneref *z;
3999 struct zone *zone;
4000 pg_data_t *last_pgdat = NULL;
4001 enum zone_type high_zoneidx = ac->high_zoneidx;
4002
4003 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, high_zoneidx,
4004 ac->nodemask) {
4005 if (last_pgdat != zone->zone_pgdat)
4006 wakeup_kswapd(zone, gfp_mask, order, high_zoneidx);
4007 last_pgdat = zone->zone_pgdat;
4008 }
4009 }
4010
4011 static inline unsigned int
4012 gfp_to_alloc_flags(gfp_t gfp_mask)
4013 {
4014 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4015
4016 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
4017 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4018
4019 /*
4020 * The caller may dip into page reserves a bit more if the caller
4021 * cannot run direct reclaim, or if the caller has realtime scheduling
4022 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4023 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4024 */
4025 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
4026
4027 if (gfp_mask & __GFP_ATOMIC) {
4028 /*
4029 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4030 * if it can't schedule.
4031 */
4032 if (!(gfp_mask & __GFP_NOMEMALLOC))
4033 alloc_flags |= ALLOC_HARDER;
4034 /*
4035 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4036 * comment for __cpuset_node_allowed().
4037 */
4038 alloc_flags &= ~ALLOC_CPUSET;
4039 } else if (unlikely(rt_task(current)) && !in_interrupt())
4040 alloc_flags |= ALLOC_HARDER;
4041
4042 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
4043 alloc_flags |= ALLOC_KSWAPD;
4044
4045 #ifdef CONFIG_CMA
4046 if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
4047 alloc_flags |= ALLOC_CMA;
4048 #endif
4049 return alloc_flags;
4050 }
4051
4052 static bool oom_reserves_allowed(struct task_struct *tsk)
4053 {
4054 if (!tsk_is_oom_victim(tsk))
4055 return false;
4056
4057 /*
4058 * !MMU doesn't have oom reaper so give access to memory reserves
4059 * only to the thread with TIF_MEMDIE set
4060 */
4061 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4062 return false;
4063
4064 return true;
4065 }
4066
4067 /*
4068 * Distinguish requests which really need access to full memory
4069 * reserves from oom victims which can live with a portion of it
4070 */
4071 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4072 {
4073 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4074 return 0;
4075 if (gfp_mask & __GFP_MEMALLOC)
4076 return ALLOC_NO_WATERMARKS;
4077 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4078 return ALLOC_NO_WATERMARKS;
4079 if (!in_interrupt()) {
4080 if (current->flags & PF_MEMALLOC)
4081 return ALLOC_NO_WATERMARKS;
4082 else if (oom_reserves_allowed(current))
4083 return ALLOC_OOM;
4084 }
4085
4086 return 0;
4087 }
4088
4089 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4090 {
4091 return !!__gfp_pfmemalloc_flags(gfp_mask);
4092 }
4093
4094 /*
4095 * Checks whether it makes sense to retry the reclaim to make a forward progress
4096 * for the given allocation request.
4097 *
4098 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4099 * without success, or when we couldn't even meet the watermark if we
4100 * reclaimed all remaining pages on the LRU lists.
4101 *
4102 * Returns true if a retry is viable or false to enter the oom path.
4103 */
4104 static inline bool
4105 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4106 struct alloc_context *ac, int alloc_flags,
4107 bool did_some_progress, int *no_progress_loops)
4108 {
4109 struct zone *zone;
4110 struct zoneref *z;
4111 bool ret = false;
4112
4113 /*
4114 * Costly allocations might have made a progress but this doesn't mean
4115 * their order will become available due to high fragmentation so
4116 * always increment the no progress counter for them
4117 */
4118 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4119 *no_progress_loops = 0;
4120 else
4121 (*no_progress_loops)++;
4122
4123 /*
4124 * Make sure we converge to OOM if we cannot make any progress
4125 * several times in the row.
4126 */
4127 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4128 /* Before OOM, exhaust highatomic_reserve */
4129 return unreserve_highatomic_pageblock(ac, true);
4130 }
4131
4132 /*
4133 * Keep reclaiming pages while there is a chance this will lead
4134 * somewhere. If none of the target zones can satisfy our allocation
4135 * request even if all reclaimable pages are considered then we are
4136 * screwed and have to go OOM.
4137 */
4138 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4139 ac->nodemask) {
4140 unsigned long available;
4141 unsigned long reclaimable;
4142 unsigned long min_wmark = min_wmark_pages(zone);
4143 bool wmark;
4144
4145 available = reclaimable = zone_reclaimable_pages(zone);
4146 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4147
4148 /*
4149 * Would the allocation succeed if we reclaimed all
4150 * reclaimable pages?
4151 */
4152 wmark = __zone_watermark_ok(zone, order, min_wmark,
4153 ac_classzone_idx(ac), alloc_flags, available);
4154 trace_reclaim_retry_zone(z, order, reclaimable,
4155 available, min_wmark, *no_progress_loops, wmark);
4156 if (wmark) {
4157 /*
4158 * If we didn't make any progress and have a lot of
4159 * dirty + writeback pages then we should wait for
4160 * an IO to complete to slow down the reclaim and
4161 * prevent from pre mature OOM
4162 */
4163 if (!did_some_progress) {
4164 unsigned long write_pending;
4165
4166 write_pending = zone_page_state_snapshot(zone,
4167 NR_ZONE_WRITE_PENDING);
4168
4169 if (2 * write_pending > reclaimable) {
4170 congestion_wait(BLK_RW_ASYNC, HZ/10);
4171 return true;
4172 }
4173 }
4174
4175 ret = true;
4176 goto out;
4177 }
4178 }
4179
4180 out:
4181 /*
4182 * Memory allocation/reclaim might be called from a WQ context and the
4183 * current implementation of the WQ concurrency control doesn't
4184 * recognize that a particular WQ is congested if the worker thread is
4185 * looping without ever sleeping. Therefore we have to do a short sleep
4186 * here rather than calling cond_resched().
4187 */
4188 if (current->flags & PF_WQ_WORKER)
4189 schedule_timeout_uninterruptible(1);
4190 else
4191 cond_resched();
4192 return ret;
4193 }
4194
4195 static inline bool
4196 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4197 {
4198 /*
4199 * It's possible that cpuset's mems_allowed and the nodemask from
4200 * mempolicy don't intersect. This should be normally dealt with by
4201 * policy_nodemask(), but it's possible to race with cpuset update in
4202 * such a way the check therein was true, and then it became false
4203 * before we got our cpuset_mems_cookie here.
4204 * This assumes that for all allocations, ac->nodemask can come only
4205 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4206 * when it does not intersect with the cpuset restrictions) or the
4207 * caller can deal with a violated nodemask.
4208 */
4209 if (cpusets_enabled() && ac->nodemask &&
4210 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4211 ac->nodemask = NULL;
4212 return true;
4213 }
4214
4215 /*
4216 * When updating a task's mems_allowed or mempolicy nodemask, it is
4217 * possible to race with parallel threads in such a way that our
4218 * allocation can fail while the mask is being updated. If we are about
4219 * to fail, check if the cpuset changed during allocation and if so,
4220 * retry.
4221 */
4222 if (read_mems_allowed_retry(cpuset_mems_cookie))
4223 return true;
4224
4225 return false;
4226 }
4227
4228 static inline struct page *
4229 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4230 struct alloc_context *ac)
4231 {
4232 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4233 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4234 struct page *page = NULL;
4235 unsigned int alloc_flags;
4236 unsigned long did_some_progress;
4237 enum compact_priority compact_priority;
4238 enum compact_result compact_result;
4239 int compaction_retries;
4240 int no_progress_loops;
4241 unsigned int cpuset_mems_cookie;
4242 int reserve_flags;
4243
4244 /*
4245 * We also sanity check to catch abuse of atomic reserves being used by
4246 * callers that are not in atomic context.
4247 */
4248 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4249 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4250 gfp_mask &= ~__GFP_ATOMIC;
4251
4252 retry_cpuset:
4253 compaction_retries = 0;
4254 no_progress_loops = 0;
4255 compact_priority = DEF_COMPACT_PRIORITY;
4256 cpuset_mems_cookie = read_mems_allowed_begin();
4257
4258 /*
4259 * The fast path uses conservative alloc_flags to succeed only until
4260 * kswapd needs to be woken up, and to avoid the cost of setting up
4261 * alloc_flags precisely. So we do that now.
4262 */
4263 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4264
4265 /*
4266 * We need to recalculate the starting point for the zonelist iterator
4267 * because we might have used different nodemask in the fast path, or
4268 * there was a cpuset modification and we are retrying - otherwise we
4269 * could end up iterating over non-eligible zones endlessly.
4270 */
4271 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4272 ac->high_zoneidx, ac->nodemask);
4273 if (!ac->preferred_zoneref->zone)
4274 goto nopage;
4275
4276 if (alloc_flags & ALLOC_KSWAPD)
4277 wake_all_kswapds(order, gfp_mask, ac);
4278
4279 /*
4280 * The adjusted alloc_flags might result in immediate success, so try
4281 * that first
4282 */
4283 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4284 if (page)
4285 goto got_pg;
4286
4287 /*
4288 * For costly allocations, try direct compaction first, as it's likely
4289 * that we have enough base pages and don't need to reclaim. For non-
4290 * movable high-order allocations, do that as well, as compaction will
4291 * try prevent permanent fragmentation by migrating from blocks of the
4292 * same migratetype.
4293 * Don't try this for allocations that are allowed to ignore
4294 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4295 */
4296 if (can_direct_reclaim &&
4297 (costly_order ||
4298 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4299 && !gfp_pfmemalloc_allowed(gfp_mask)) {
4300 page = __alloc_pages_direct_compact(gfp_mask, order,
4301 alloc_flags, ac,
4302 INIT_COMPACT_PRIORITY,
4303 &compact_result);
4304 if (page)
4305 goto got_pg;
4306
4307 /*
4308 * Checks for costly allocations with __GFP_NORETRY, which
4309 * includes THP page fault allocations
4310 */
4311 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4312 /*
4313 * If compaction is deferred for high-order allocations,
4314 * it is because sync compaction recently failed. If
4315 * this is the case and the caller requested a THP
4316 * allocation, we do not want to heavily disrupt the
4317 * system, so we fail the allocation instead of entering
4318 * direct reclaim.
4319 */
4320 if (compact_result == COMPACT_DEFERRED)
4321 goto nopage;
4322
4323 /*
4324 * Looks like reclaim/compaction is worth trying, but
4325 * sync compaction could be very expensive, so keep
4326 * using async compaction.
4327 */
4328 compact_priority = INIT_COMPACT_PRIORITY;
4329 }
4330 }
4331
4332 retry:
4333 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4334 if (alloc_flags & ALLOC_KSWAPD)
4335 wake_all_kswapds(order, gfp_mask, ac);
4336
4337 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4338 if (reserve_flags)
4339 alloc_flags = reserve_flags;
4340
4341 /*
4342 * Reset the nodemask and zonelist iterators if memory policies can be
4343 * ignored. These allocations are high priority and system rather than
4344 * user oriented.
4345 */
4346 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4347 ac->nodemask = NULL;
4348 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4349 ac->high_zoneidx, ac->nodemask);
4350 }
4351
4352 /* Attempt with potentially adjusted zonelist and alloc_flags */
4353 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4354 if (page)
4355 goto got_pg;
4356
4357 /* Caller is not willing to reclaim, we can't balance anything */
4358 if (!can_direct_reclaim)
4359 goto nopage;
4360
4361 /* Avoid recursion of direct reclaim */
4362 if (current->flags & PF_MEMALLOC)
4363 goto nopage;
4364
4365 /* Try direct reclaim and then allocating */
4366 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4367 &did_some_progress);
4368 if (page)
4369 goto got_pg;
4370
4371 /* Try direct compaction and then allocating */
4372 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4373 compact_priority, &compact_result);
4374 if (page)
4375 goto got_pg;
4376
4377 /* Do not loop if specifically requested */
4378 if (gfp_mask & __GFP_NORETRY)
4379 goto nopage;
4380
4381 /*
4382 * Do not retry costly high order allocations unless they are
4383 * __GFP_RETRY_MAYFAIL
4384 */
4385 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4386 goto nopage;
4387
4388 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4389 did_some_progress > 0, &no_progress_loops))
4390 goto retry;
4391
4392 /*
4393 * It doesn't make any sense to retry for the compaction if the order-0
4394 * reclaim is not able to make any progress because the current
4395 * implementation of the compaction depends on the sufficient amount
4396 * of free memory (see __compaction_suitable)
4397 */
4398 if (did_some_progress > 0 &&
4399 should_compact_retry(ac, order, alloc_flags,
4400 compact_result, &compact_priority,
4401 &compaction_retries))
4402 goto retry;
4403
4404
4405 /* Deal with possible cpuset update races before we start OOM killing */
4406 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4407 goto retry_cpuset;
4408
4409 /* Reclaim has failed us, start killing things */
4410 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4411 if (page)
4412 goto got_pg;
4413
4414 /* Avoid allocations with no watermarks from looping endlessly */
4415 if (tsk_is_oom_victim(current) &&
4416 (alloc_flags == ALLOC_OOM ||
4417 (gfp_mask & __GFP_NOMEMALLOC)))
4418 goto nopage;
4419
4420 /* Retry as long as the OOM killer is making progress */
4421 if (did_some_progress) {
4422 no_progress_loops = 0;
4423 goto retry;
4424 }
4425
4426 nopage:
4427 /* Deal with possible cpuset update races before we fail */
4428 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4429 goto retry_cpuset;
4430
4431 /*
4432 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4433 * we always retry
4434 */
4435 if (gfp_mask & __GFP_NOFAIL) {
4436 /*
4437 * All existing users of the __GFP_NOFAIL are blockable, so warn
4438 * of any new users that actually require GFP_NOWAIT
4439 */
4440 if (WARN_ON_ONCE(!can_direct_reclaim))
4441 goto fail;
4442
4443 /*
4444 * PF_MEMALLOC request from this context is rather bizarre
4445 * because we cannot reclaim anything and only can loop waiting
4446 * for somebody to do a work for us
4447 */
4448 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4449
4450 /*
4451 * non failing costly orders are a hard requirement which we
4452 * are not prepared for much so let's warn about these users
4453 * so that we can identify them and convert them to something
4454 * else.
4455 */
4456 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
4457
4458 /*
4459 * Help non-failing allocations by giving them access to memory
4460 * reserves but do not use ALLOC_NO_WATERMARKS because this
4461 * could deplete whole memory reserves which would just make
4462 * the situation worse
4463 */
4464 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
4465 if (page)
4466 goto got_pg;
4467
4468 cond_resched();
4469 goto retry;
4470 }
4471 fail:
4472 warn_alloc(gfp_mask, ac->nodemask,
4473 "page allocation failure: order:%u", order);
4474 got_pg:
4475 return page;
4476 }
4477
4478 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4479 int preferred_nid, nodemask_t *nodemask,
4480 struct alloc_context *ac, gfp_t *alloc_mask,
4481 unsigned int *alloc_flags)
4482 {
4483 ac->high_zoneidx = gfp_zone(gfp_mask);
4484 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4485 ac->nodemask = nodemask;
4486 ac->migratetype = gfpflags_to_migratetype(gfp_mask);
4487
4488 if (cpusets_enabled()) {
4489 *alloc_mask |= __GFP_HARDWALL;
4490 if (!ac->nodemask)
4491 ac->nodemask = &cpuset_current_mems_allowed;
4492 else
4493 *alloc_flags |= ALLOC_CPUSET;
4494 }
4495
4496 fs_reclaim_acquire(gfp_mask);
4497 fs_reclaim_release(gfp_mask);
4498
4499 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
4500
4501 if (should_fail_alloc_page(gfp_mask, order))
4502 return false;
4503
4504 if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
4505 *alloc_flags |= ALLOC_CMA;
4506
4507 return true;
4508 }
4509
4510 /* Determine whether to spread dirty pages and what the first usable zone */
4511 static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
4512 {
4513 /* Dirty zone balancing only done in the fast path */
4514 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4515
4516 /*
4517 * The preferred zone is used for statistics but crucially it is
4518 * also used as the starting point for the zonelist iterator. It
4519 * may get reset for allocations that ignore memory policies.
4520 */
4521 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4522 ac->high_zoneidx, ac->nodemask);
4523 }
4524
4525 /*
4526 * This is the 'heart' of the zoned buddy allocator.
4527 */
4528 struct page *
4529 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
4530 nodemask_t *nodemask)
4531 {
4532 struct page *page;
4533 unsigned int alloc_flags = ALLOC_WMARK_LOW;
4534 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
4535 struct alloc_context ac = { };
4536
4537 /*
4538 * There are several places where we assume that the order value is sane
4539 * so bail out early if the request is out of bound.
4540 */
4541 if (unlikely(order >= MAX_ORDER)) {
4542 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
4543 return NULL;
4544 }
4545
4546 gfp_mask &= gfp_allowed_mask;
4547 alloc_mask = gfp_mask;
4548 if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
4549 return NULL;
4550
4551 finalise_ac(gfp_mask, &ac);
4552
4553 /*
4554 * Forbid the first pass from falling back to types that fragment
4555 * memory until all local zones are considered.
4556 */
4557 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
4558
4559 /* First allocation attempt */
4560 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
4561 if (likely(page))
4562 goto out;
4563
4564 /*
4565 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4566 * resp. GFP_NOIO which has to be inherited for all allocation requests
4567 * from a particular context which has been marked by
4568 * memalloc_no{fs,io}_{save,restore}.
4569 */
4570 alloc_mask = current_gfp_context(gfp_mask);
4571 ac.spread_dirty_pages = false;
4572
4573 /*
4574 * Restore the original nodemask if it was potentially replaced with
4575 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4576 */
4577 if (unlikely(ac.nodemask != nodemask))
4578 ac.nodemask = nodemask;
4579
4580 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
4581
4582 out:
4583 if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
4584 unlikely(memcg_kmem_charge(page, gfp_mask, order) != 0)) {
4585 __free_pages(page, order);
4586 page = NULL;
4587 }
4588
4589 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
4590
4591 return page;
4592 }
4593 EXPORT_SYMBOL(__alloc_pages_nodemask);
4594
4595 /*
4596 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4597 * address cannot represent highmem pages. Use alloc_pages and then kmap if
4598 * you need to access high mem.
4599 */
4600 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
4601 {
4602 struct page *page;
4603
4604 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
4605 if (!page)
4606 return 0;
4607 return (unsigned long) page_address(page);
4608 }
4609 EXPORT_SYMBOL(__get_free_pages);
4610
4611 unsigned long get_zeroed_page(gfp_t gfp_mask)
4612 {
4613 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
4614 }
4615 EXPORT_SYMBOL(get_zeroed_page);
4616
4617 static inline void free_the_page(struct page *page, unsigned int order)
4618 {
4619 if (order == 0) /* Via pcp? */
4620 free_unref_page(page);
4621 else
4622 __free_pages_ok(page, order);
4623 }
4624
4625 void __free_pages(struct page *page, unsigned int order)
4626 {
4627 if (put_page_testzero(page))
4628 free_the_page(page, order);
4629 }
4630 EXPORT_SYMBOL(__free_pages);
4631
4632 void free_pages(unsigned long addr, unsigned int order)
4633 {
4634 if (addr != 0) {
4635 VM_BUG_ON(!virt_addr_valid((void *)addr));
4636 __free_pages(virt_to_page((void *)addr), order);
4637 }
4638 }
4639
4640 EXPORT_SYMBOL(free_pages);
4641
4642 /*
4643 * Page Fragment:
4644 * An arbitrary-length arbitrary-offset area of memory which resides
4645 * within a 0 or higher order page. Multiple fragments within that page
4646 * are individually refcounted, in the page's reference counter.
4647 *
4648 * The page_frag functions below provide a simple allocation framework for
4649 * page fragments. This is used by the network stack and network device
4650 * drivers to provide a backing region of memory for use as either an
4651 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4652 */
4653 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
4654 gfp_t gfp_mask)
4655 {
4656 struct page *page = NULL;
4657 gfp_t gfp = gfp_mask;
4658
4659 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4660 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
4661 __GFP_NOMEMALLOC;
4662 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
4663 PAGE_FRAG_CACHE_MAX_ORDER);
4664 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
4665 #endif
4666 if (unlikely(!page))
4667 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
4668
4669 nc->va = page ? page_address(page) : NULL;
4670
4671 return page;
4672 }
4673
4674 void __page_frag_cache_drain(struct page *page, unsigned int count)
4675 {
4676 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
4677
4678 if (page_ref_sub_and_test(page, count))
4679 free_the_page(page, compound_order(page));
4680 }
4681 EXPORT_SYMBOL(__page_frag_cache_drain);
4682
4683 void *page_frag_alloc(struct page_frag_cache *nc,
4684 unsigned int fragsz, gfp_t gfp_mask)
4685 {
4686 unsigned int size = PAGE_SIZE;
4687 struct page *page;
4688 int offset;
4689
4690 if (unlikely(!nc->va)) {
4691 refill:
4692 page = __page_frag_cache_refill(nc, gfp_mask);
4693 if (!page)
4694 return NULL;
4695
4696 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4697 /* if size can vary use size else just use PAGE_SIZE */
4698 size = nc->size;
4699 #endif
4700 /* Even if we own the page, we do not use atomic_set().
4701 * This would break get_page_unless_zero() users.
4702 */
4703 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
4704
4705 /* reset page count bias and offset to start of new frag */
4706 nc->pfmemalloc = page_is_pfmemalloc(page);
4707 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4708 nc->offset = size;
4709 }
4710
4711 offset = nc->offset - fragsz;
4712 if (unlikely(offset < 0)) {
4713 page = virt_to_page(nc->va);
4714
4715 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
4716 goto refill;
4717
4718 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4719 /* if size can vary use size else just use PAGE_SIZE */
4720 size = nc->size;
4721 #endif
4722 /* OK, page count is 0, we can safely set it */
4723 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
4724
4725 /* reset page count bias and offset to start of new frag */
4726 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4727 offset = size - fragsz;
4728 }
4729
4730 nc->pagecnt_bias--;
4731 nc->offset = offset;
4732
4733 return nc->va + offset;
4734 }
4735 EXPORT_SYMBOL(page_frag_alloc);
4736
4737 /*
4738 * Frees a page fragment allocated out of either a compound or order 0 page.
4739 */
4740 void page_frag_free(void *addr)
4741 {
4742 struct page *page = virt_to_head_page(addr);
4743
4744 if (unlikely(put_page_testzero(page)))
4745 free_the_page(page, compound_order(page));
4746 }
4747 EXPORT_SYMBOL(page_frag_free);
4748
4749 static void *make_alloc_exact(unsigned long addr, unsigned int order,
4750 size_t size)
4751 {
4752 if (addr) {
4753 unsigned long alloc_end = addr + (PAGE_SIZE << order);
4754 unsigned long used = addr + PAGE_ALIGN(size);
4755
4756 split_page(virt_to_page((void *)addr), order);
4757 while (used < alloc_end) {
4758 free_page(used);
4759 used += PAGE_SIZE;
4760 }
4761 }
4762 return (void *)addr;
4763 }
4764
4765 /**
4766 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
4767 * @size: the number of bytes to allocate
4768 * @gfp_mask: GFP flags for the allocation
4769 *
4770 * This function is similar to alloc_pages(), except that it allocates the
4771 * minimum number of pages to satisfy the request. alloc_pages() can only
4772 * allocate memory in power-of-two pages.
4773 *
4774 * This function is also limited by MAX_ORDER.
4775 *
4776 * Memory allocated by this function must be released by free_pages_exact().
4777 */
4778 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
4779 {
4780 unsigned int order = get_order(size);
4781 unsigned long addr;
4782
4783 addr = __get_free_pages(gfp_mask, order);
4784 return make_alloc_exact(addr, order, size);
4785 }
4786 EXPORT_SYMBOL(alloc_pages_exact);
4787
4788 /**
4789 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
4790 * pages on a node.
4791 * @nid: the preferred node ID where memory should be allocated
4792 * @size: the number of bytes to allocate
4793 * @gfp_mask: GFP flags for the allocation
4794 *
4795 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
4796 * back.
4797 */
4798 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
4799 {
4800 unsigned int order = get_order(size);
4801 struct page *p = alloc_pages_node(nid, gfp_mask, order);
4802 if (!p)
4803 return NULL;
4804 return make_alloc_exact((unsigned long)page_address(p), order, size);
4805 }
4806
4807 /**
4808 * free_pages_exact - release memory allocated via alloc_pages_exact()
4809 * @virt: the value returned by alloc_pages_exact.
4810 * @size: size of allocation, same value as passed to alloc_pages_exact().
4811 *
4812 * Release the memory allocated by a previous call to alloc_pages_exact.
4813 */
4814 void free_pages_exact(void *virt, size_t size)
4815 {
4816 unsigned long addr = (unsigned long)virt;
4817 unsigned long end = addr + PAGE_ALIGN(size);
4818
4819 while (addr < end) {
4820 free_page(addr);
4821 addr += PAGE_SIZE;
4822 }
4823 }
4824 EXPORT_SYMBOL(free_pages_exact);
4825
4826 /**
4827 * nr_free_zone_pages - count number of pages beyond high watermark
4828 * @offset: The zone index of the highest zone
4829 *
4830 * nr_free_zone_pages() counts the number of counts pages which are beyond the
4831 * high watermark within all zones at or below a given zone index. For each
4832 * zone, the number of pages is calculated as:
4833 *
4834 * nr_free_zone_pages = managed_pages - high_pages
4835 */
4836 static unsigned long nr_free_zone_pages(int offset)
4837 {
4838 struct zoneref *z;
4839 struct zone *zone;
4840
4841 /* Just pick one node, since fallback list is circular */
4842 unsigned long sum = 0;
4843
4844 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
4845
4846 for_each_zone_zonelist(zone, z, zonelist, offset) {
4847 unsigned long size = zone_managed_pages(zone);
4848 unsigned long high = high_wmark_pages(zone);
4849 if (size > high)
4850 sum += size - high;
4851 }
4852
4853 return sum;
4854 }
4855
4856 /**
4857 * nr_free_buffer_pages - count number of pages beyond high watermark
4858 *
4859 * nr_free_buffer_pages() counts the number of pages which are beyond the high
4860 * watermark within ZONE_DMA and ZONE_NORMAL.
4861 */
4862 unsigned long nr_free_buffer_pages(void)
4863 {
4864 return nr_free_zone_pages(gfp_zone(GFP_USER));
4865 }
4866 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
4867
4868 /**
4869 * nr_free_pagecache_pages - count number of pages beyond high watermark
4870 *
4871 * nr_free_pagecache_pages() counts the number of pages which are beyond the
4872 * high watermark within all zones.
4873 */
4874 unsigned long nr_free_pagecache_pages(void)
4875 {
4876 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
4877 }
4878
4879 static inline void show_node(struct zone *zone)
4880 {
4881 if (IS_ENABLED(CONFIG_NUMA))
4882 printk("Node %d ", zone_to_nid(zone));
4883 }
4884
4885 long si_mem_available(void)
4886 {
4887 long available;
4888 unsigned long pagecache;
4889 unsigned long wmark_low = 0;
4890 unsigned long pages[NR_LRU_LISTS];
4891 unsigned long reclaimable;
4892 struct zone *zone;
4893 int lru;
4894
4895 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
4896 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
4897
4898 for_each_zone(zone)
4899 wmark_low += low_wmark_pages(zone);
4900
4901 /*
4902 * Estimate the amount of memory available for userspace allocations,
4903 * without causing swapping.
4904 */
4905 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
4906
4907 /*
4908 * Not all the page cache can be freed, otherwise the system will
4909 * start swapping. Assume at least half of the page cache, or the
4910 * low watermark worth of cache, needs to stay.
4911 */
4912 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
4913 pagecache -= min(pagecache / 2, wmark_low);
4914 available += pagecache;
4915
4916 /*
4917 * Part of the reclaimable slab and other kernel memory consists of
4918 * items that are in use, and cannot be freed. Cap this estimate at the
4919 * low watermark.
4920 */
4921 reclaimable = global_node_page_state(NR_SLAB_RECLAIMABLE) +
4922 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
4923 available += reclaimable - min(reclaimable / 2, wmark_low);
4924
4925 if (available < 0)
4926 available = 0;
4927 return available;
4928 }
4929 EXPORT_SYMBOL_GPL(si_mem_available);
4930
4931 void si_meminfo(struct sysinfo *val)
4932 {
4933 val->totalram = totalram_pages();
4934 val->sharedram = global_node_page_state(NR_SHMEM);
4935 val->freeram = global_zone_page_state(NR_FREE_PAGES);
4936 val->bufferram = nr_blockdev_pages();
4937 val->totalhigh = totalhigh_pages();
4938 val->freehigh = nr_free_highpages();
4939 val->mem_unit = PAGE_SIZE;
4940 }
4941
4942 EXPORT_SYMBOL(si_meminfo);
4943
4944 #ifdef CONFIG_NUMA
4945 void si_meminfo_node(struct sysinfo *val, int nid)
4946 {
4947 int zone_type; /* needs to be signed */
4948 unsigned long managed_pages = 0;
4949 unsigned long managed_highpages = 0;
4950 unsigned long free_highpages = 0;
4951 pg_data_t *pgdat = NODE_DATA(nid);
4952
4953 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
4954 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
4955 val->totalram = managed_pages;
4956 val->sharedram = node_page_state(pgdat, NR_SHMEM);
4957 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
4958 #ifdef CONFIG_HIGHMEM
4959 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
4960 struct zone *zone = &pgdat->node_zones[zone_type];
4961
4962 if (is_highmem(zone)) {
4963 managed_highpages += zone_managed_pages(zone);
4964 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
4965 }
4966 }
4967 val->totalhigh = managed_highpages;
4968 val->freehigh = free_highpages;
4969 #else
4970 val->totalhigh = managed_highpages;
4971 val->freehigh = free_highpages;
4972 #endif
4973 val->mem_unit = PAGE_SIZE;
4974 }
4975 #endif
4976
4977 /*
4978 * Determine whether the node should be displayed or not, depending on whether
4979 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
4980 */
4981 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
4982 {
4983 if (!(flags & SHOW_MEM_FILTER_NODES))
4984 return false;
4985
4986 /*
4987 * no node mask - aka implicit memory numa policy. Do not bother with
4988 * the synchronization - read_mems_allowed_begin - because we do not
4989 * have to be precise here.
4990 */
4991 if (!nodemask)
4992 nodemask = &cpuset_current_mems_allowed;
4993
4994 return !node_isset(nid, *nodemask);
4995 }
4996
4997 #define K(x) ((x) << (PAGE_SHIFT-10))
4998
4999 static void show_migration_types(unsigned char type)
5000 {
5001 static const char types[MIGRATE_TYPES] = {
5002 [MIGRATE_UNMOVABLE] = 'U',
5003 [MIGRATE_MOVABLE] = 'M',
5004 [MIGRATE_RECLAIMABLE] = 'E',
5005 [MIGRATE_HIGHATOMIC] = 'H',
5006 #ifdef CONFIG_CMA
5007 [MIGRATE_CMA] = 'C',
5008 #endif
5009 #ifdef CONFIG_MEMORY_ISOLATION
5010 [MIGRATE_ISOLATE] = 'I',
5011 #endif
5012 };
5013 char tmp[MIGRATE_TYPES + 1];
5014 char *p = tmp;
5015 int i;
5016
5017 for (i = 0; i < MIGRATE_TYPES; i++) {
5018 if (type & (1 << i))
5019 *p++ = types[i];
5020 }
5021
5022 *p = '\0';
5023 printk(KERN_CONT "(%s) ", tmp);
5024 }
5025
5026 /*
5027 * Show free area list (used inside shift_scroll-lock stuff)
5028 * We also calculate the percentage fragmentation. We do this by counting the
5029 * memory on each free list with the exception of the first item on the list.
5030 *
5031 * Bits in @filter:
5032 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5033 * cpuset.
5034 */
5035 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5036 {
5037 unsigned long free_pcp = 0;
5038 int cpu;
5039 struct zone *zone;
5040 pg_data_t *pgdat;
5041
5042 for_each_populated_zone(zone) {
5043 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5044 continue;
5045
5046 for_each_online_cpu(cpu)
5047 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5048 }
5049
5050 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5051 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5052 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
5053 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5054 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5055 " free:%lu free_pcp:%lu free_cma:%lu\n",
5056 global_node_page_state(NR_ACTIVE_ANON),
5057 global_node_page_state(NR_INACTIVE_ANON),
5058 global_node_page_state(NR_ISOLATED_ANON),
5059 global_node_page_state(NR_ACTIVE_FILE),
5060 global_node_page_state(NR_INACTIVE_FILE),
5061 global_node_page_state(NR_ISOLATED_FILE),
5062 global_node_page_state(NR_UNEVICTABLE),
5063 global_node_page_state(NR_FILE_DIRTY),
5064 global_node_page_state(NR_WRITEBACK),
5065 global_node_page_state(NR_UNSTABLE_NFS),
5066 global_node_page_state(NR_SLAB_RECLAIMABLE),
5067 global_node_page_state(NR_SLAB_UNRECLAIMABLE),
5068 global_node_page_state(NR_FILE_MAPPED),
5069 global_node_page_state(NR_SHMEM),
5070 global_zone_page_state(NR_PAGETABLE),
5071 global_zone_page_state(NR_BOUNCE),
5072 global_zone_page_state(NR_FREE_PAGES),
5073 free_pcp,
5074 global_zone_page_state(NR_FREE_CMA_PAGES));
5075
5076 for_each_online_pgdat(pgdat) {
5077 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5078 continue;
5079
5080 printk("Node %d"
5081 " active_anon:%lukB"
5082 " inactive_anon:%lukB"
5083 " active_file:%lukB"
5084 " inactive_file:%lukB"
5085 " unevictable:%lukB"
5086 " isolated(anon):%lukB"
5087 " isolated(file):%lukB"
5088 " mapped:%lukB"
5089 " dirty:%lukB"
5090 " writeback:%lukB"
5091 " shmem:%lukB"
5092 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5093 " shmem_thp: %lukB"
5094 " shmem_pmdmapped: %lukB"
5095 " anon_thp: %lukB"
5096 #endif
5097 " writeback_tmp:%lukB"
5098 " unstable:%lukB"
5099 " all_unreclaimable? %s"
5100 "\n",
5101 pgdat->node_id,
5102 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5103 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5104 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5105 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5106 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5107 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5108 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5109 K(node_page_state(pgdat, NR_FILE_MAPPED)),
5110 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5111 K(node_page_state(pgdat, NR_WRITEBACK)),
5112 K(node_page_state(pgdat, NR_SHMEM)),
5113 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5114 K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5115 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5116 * HPAGE_PMD_NR),
5117 K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5118 #endif
5119 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5120 K(node_page_state(pgdat, NR_UNSTABLE_NFS)),
5121 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5122 "yes" : "no");
5123 }
5124
5125 for_each_populated_zone(zone) {
5126 int i;
5127
5128 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5129 continue;
5130
5131 free_pcp = 0;
5132 for_each_online_cpu(cpu)
5133 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5134
5135 show_node(zone);
5136 printk(KERN_CONT
5137 "%s"
5138 " free:%lukB"
5139 " min:%lukB"
5140 " low:%lukB"
5141 " high:%lukB"
5142 " active_anon:%lukB"
5143 " inactive_anon:%lukB"
5144 " active_file:%lukB"
5145 " inactive_file:%lukB"
5146 " unevictable:%lukB"
5147 " writepending:%lukB"
5148 " present:%lukB"
5149 " managed:%lukB"
5150 " mlocked:%lukB"
5151 " kernel_stack:%lukB"
5152 " pagetables:%lukB"
5153 " bounce:%lukB"
5154 " free_pcp:%lukB"
5155 " local_pcp:%ukB"
5156 " free_cma:%lukB"
5157 "\n",
5158 zone->name,
5159 K(zone_page_state(zone, NR_FREE_PAGES)),
5160 K(min_wmark_pages(zone)),
5161 K(low_wmark_pages(zone)),
5162 K(high_wmark_pages(zone)),
5163 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5164 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5165 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5166 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5167 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5168 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5169 K(zone->present_pages),
5170 K(zone_managed_pages(zone)),
5171 K(zone_page_state(zone, NR_MLOCK)),
5172 zone_page_state(zone, NR_KERNEL_STACK_KB),
5173 K(zone_page_state(zone, NR_PAGETABLE)),
5174 K(zone_page_state(zone, NR_BOUNCE)),
5175 K(free_pcp),
5176 K(this_cpu_read(zone->pageset->pcp.count)),
5177 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5178 printk("lowmem_reserve[]:");
5179 for (i = 0; i < MAX_NR_ZONES; i++)
5180 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5181 printk(KERN_CONT "\n");
5182 }
5183
5184 for_each_populated_zone(zone) {
5185 unsigned int order;
5186 unsigned long nr[MAX_ORDER], flags, total = 0;
5187 unsigned char types[MAX_ORDER];
5188
5189 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5190 continue;
5191 show_node(zone);
5192 printk(KERN_CONT "%s: ", zone->name);
5193
5194 spin_lock_irqsave(&zone->lock, flags);
5195 for (order = 0; order < MAX_ORDER; order++) {
5196 struct free_area *area = &zone->free_area[order];
5197 int type;
5198
5199 nr[order] = area->nr_free;
5200 total += nr[order] << order;
5201
5202 types[order] = 0;
5203 for (type = 0; type < MIGRATE_TYPES; type++) {
5204 if (!list_empty(&area->free_list[type]))
5205 types[order] |= 1 << type;
5206 }
5207 }
5208 spin_unlock_irqrestore(&zone->lock, flags);
5209 for (order = 0; order < MAX_ORDER; order++) {
5210 printk(KERN_CONT "%lu*%lukB ",
5211 nr[order], K(1UL) << order);
5212 if (nr[order])
5213 show_migration_types(types[order]);
5214 }
5215 printk(KERN_CONT "= %lukB\n", K(total));
5216 }
5217
5218 hugetlb_show_meminfo();
5219
5220 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5221
5222 show_swap_cache_info();
5223 }
5224
5225 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5226 {
5227 zoneref->zone = zone;
5228 zoneref->zone_idx = zone_idx(zone);
5229 }
5230
5231 /*
5232 * Builds allocation fallback zone lists.
5233 *
5234 * Add all populated zones of a node to the zonelist.
5235 */
5236 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5237 {
5238 struct zone *zone;
5239 enum zone_type zone_type = MAX_NR_ZONES;
5240 int nr_zones = 0;
5241
5242 do {
5243 zone_type--;
5244 zone = pgdat->node_zones + zone_type;
5245 if (managed_zone(zone)) {
5246 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5247 check_highest_zone(zone_type);
5248 }
5249 } while (zone_type);
5250
5251 return nr_zones;
5252 }
5253
5254 #ifdef CONFIG_NUMA
5255
5256 static int __parse_numa_zonelist_order(char *s)
5257 {
5258 /*
5259 * We used to support different zonlists modes but they turned
5260 * out to be just not useful. Let's keep the warning in place
5261 * if somebody still use the cmd line parameter so that we do
5262 * not fail it silently
5263 */
5264 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5265 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
5266 return -EINVAL;
5267 }
5268 return 0;
5269 }
5270
5271 static __init int setup_numa_zonelist_order(char *s)
5272 {
5273 if (!s)
5274 return 0;
5275
5276 return __parse_numa_zonelist_order(s);
5277 }
5278 early_param("numa_zonelist_order", setup_numa_zonelist_order);
5279
5280 char numa_zonelist_order[] = "Node";
5281
5282 /*
5283 * sysctl handler for numa_zonelist_order
5284 */
5285 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5286 void __user *buffer, size_t *length,
5287 loff_t *ppos)
5288 {
5289 char *str;
5290 int ret;
5291
5292 if (!write)
5293 return proc_dostring(table, write, buffer, length, ppos);
5294 str = memdup_user_nul(buffer, 16);
5295 if (IS_ERR(str))
5296 return PTR_ERR(str);
5297
5298 ret = __parse_numa_zonelist_order(str);
5299 kfree(str);
5300 return ret;
5301 }
5302
5303
5304 #define MAX_NODE_LOAD (nr_online_nodes)
5305 static int node_load[MAX_NUMNODES];
5306
5307 /**
5308 * find_next_best_node - find the next node that should appear in a given node's fallback list
5309 * @node: node whose fallback list we're appending
5310 * @used_node_mask: nodemask_t of already used nodes
5311 *
5312 * We use a number of factors to determine which is the next node that should
5313 * appear on a given node's fallback list. The node should not have appeared
5314 * already in @node's fallback list, and it should be the next closest node
5315 * according to the distance array (which contains arbitrary distance values
5316 * from each node to each node in the system), and should also prefer nodes
5317 * with no CPUs, since presumably they'll have very little allocation pressure
5318 * on them otherwise.
5319 * It returns -1 if no node is found.
5320 */
5321 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5322 {
5323 int n, val;
5324 int min_val = INT_MAX;
5325 int best_node = NUMA_NO_NODE;
5326 const struct cpumask *tmp = cpumask_of_node(0);
5327
5328 /* Use the local node if we haven't already */
5329 if (!node_isset(node, *used_node_mask)) {
5330 node_set(node, *used_node_mask);
5331 return node;
5332 }
5333
5334 for_each_node_state(n, N_MEMORY) {
5335
5336 /* Don't want a node to appear more than once */
5337 if (node_isset(n, *used_node_mask))
5338 continue;
5339
5340 /* Use the distance array to find the distance */
5341 val = node_distance(node, n);
5342
5343 /* Penalize nodes under us ("prefer the next node") */
5344 val += (n < node);
5345
5346 /* Give preference to headless and unused nodes */
5347 tmp = cpumask_of_node(n);
5348 if (!cpumask_empty(tmp))
5349 val += PENALTY_FOR_NODE_WITH_CPUS;
5350
5351 /* Slight preference for less loaded node */
5352 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5353 val += node_load[n];
5354
5355 if (val < min_val) {
5356 min_val = val;
5357 best_node = n;
5358 }
5359 }
5360
5361 if (best_node >= 0)
5362 node_set(best_node, *used_node_mask);
5363
5364 return best_node;
5365 }
5366
5367
5368 /*
5369 * Build zonelists ordered by node and zones within node.
5370 * This results in maximum locality--normal zone overflows into local
5371 * DMA zone, if any--but risks exhausting DMA zone.
5372 */
5373 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5374 unsigned nr_nodes)
5375 {
5376 struct zoneref *zonerefs;
5377 int i;
5378
5379 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5380
5381 for (i = 0; i < nr_nodes; i++) {
5382 int nr_zones;
5383
5384 pg_data_t *node = NODE_DATA(node_order[i]);
5385
5386 nr_zones = build_zonerefs_node(node, zonerefs);
5387 zonerefs += nr_zones;
5388 }
5389 zonerefs->zone = NULL;
5390 zonerefs->zone_idx = 0;
5391 }
5392
5393 /*
5394 * Build gfp_thisnode zonelists
5395 */
5396 static void build_thisnode_zonelists(pg_data_t *pgdat)
5397 {
5398 struct zoneref *zonerefs;
5399 int nr_zones;
5400
5401 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5402 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5403 zonerefs += nr_zones;
5404 zonerefs->zone = NULL;
5405 zonerefs->zone_idx = 0;
5406 }
5407
5408 /*
5409 * Build zonelists ordered by zone and nodes within zones.
5410 * This results in conserving DMA zone[s] until all Normal memory is
5411 * exhausted, but results in overflowing to remote node while memory
5412 * may still exist in local DMA zone.
5413 */
5414
5415 static void build_zonelists(pg_data_t *pgdat)
5416 {
5417 static int node_order[MAX_NUMNODES];
5418 int node, load, nr_nodes = 0;
5419 nodemask_t used_mask;
5420 int local_node, prev_node;
5421
5422 /* NUMA-aware ordering of nodes */
5423 local_node = pgdat->node_id;
5424 load = nr_online_nodes;
5425 prev_node = local_node;
5426 nodes_clear(used_mask);
5427
5428 memset(node_order, 0, sizeof(node_order));
5429 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5430 /*
5431 * We don't want to pressure a particular node.
5432 * So adding penalty to the first node in same
5433 * distance group to make it round-robin.
5434 */
5435 if (node_distance(local_node, node) !=
5436 node_distance(local_node, prev_node))
5437 node_load[node] = load;
5438
5439 node_order[nr_nodes++] = node;
5440 prev_node = node;
5441 load--;
5442 }
5443
5444 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5445 build_thisnode_zonelists(pgdat);
5446 }
5447
5448 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5449 /*
5450 * Return node id of node used for "local" allocations.
5451 * I.e., first node id of first zone in arg node's generic zonelist.
5452 * Used for initializing percpu 'numa_mem', which is used primarily
5453 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5454 */
5455 int local_memory_node(int node)
5456 {
5457 struct zoneref *z;
5458
5459 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5460 gfp_zone(GFP_KERNEL),
5461 NULL);
5462 return zone_to_nid(z->zone);
5463 }
5464 #endif
5465
5466 static void setup_min_unmapped_ratio(void);
5467 static void setup_min_slab_ratio(void);
5468 #else /* CONFIG_NUMA */
5469
5470 static void build_zonelists(pg_data_t *pgdat)
5471 {
5472 int node, local_node;
5473 struct zoneref *zonerefs;
5474 int nr_zones;
5475
5476 local_node = pgdat->node_id;
5477
5478 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5479 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5480 zonerefs += nr_zones;
5481
5482 /*
5483 * Now we build the zonelist so that it contains the zones
5484 * of all the other nodes.
5485 * We don't want to pressure a particular node, so when
5486 * building the zones for node N, we make sure that the
5487 * zones coming right after the local ones are those from
5488 * node N+1 (modulo N)
5489 */
5490 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
5491 if (!node_online(node))
5492 continue;
5493 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5494 zonerefs += nr_zones;
5495 }
5496 for (node = 0; node < local_node; node++) {
5497 if (!node_online(node))
5498 continue;
5499 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5500 zonerefs += nr_zones;
5501 }
5502
5503 zonerefs->zone = NULL;
5504 zonerefs->zone_idx = 0;
5505 }
5506
5507 #endif /* CONFIG_NUMA */
5508
5509 /*
5510 * Boot pageset table. One per cpu which is going to be used for all
5511 * zones and all nodes. The parameters will be set in such a way
5512 * that an item put on a list will immediately be handed over to
5513 * the buddy list. This is safe since pageset manipulation is done
5514 * with interrupts disabled.
5515 *
5516 * The boot_pagesets must be kept even after bootup is complete for
5517 * unused processors and/or zones. They do play a role for bootstrapping
5518 * hotplugged processors.
5519 *
5520 * zoneinfo_show() and maybe other functions do
5521 * not check if the processor is online before following the pageset pointer.
5522 * Other parts of the kernel may not check if the zone is available.
5523 */
5524 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
5525 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
5526 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
5527
5528 static void __build_all_zonelists(void *data)
5529 {
5530 int nid;
5531 int __maybe_unused cpu;
5532 pg_data_t *self = data;
5533 static DEFINE_SPINLOCK(lock);
5534
5535 spin_lock(&lock);
5536
5537 #ifdef CONFIG_NUMA
5538 memset(node_load, 0, sizeof(node_load));
5539 #endif
5540
5541 /*
5542 * This node is hotadded and no memory is yet present. So just
5543 * building zonelists is fine - no need to touch other nodes.
5544 */
5545 if (self && !node_online(self->node_id)) {
5546 build_zonelists(self);
5547 } else {
5548 for_each_online_node(nid) {
5549 pg_data_t *pgdat = NODE_DATA(nid);
5550
5551 build_zonelists(pgdat);
5552 }
5553
5554 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5555 /*
5556 * We now know the "local memory node" for each node--
5557 * i.e., the node of the first zone in the generic zonelist.
5558 * Set up numa_mem percpu variable for on-line cpus. During
5559 * boot, only the boot cpu should be on-line; we'll init the
5560 * secondary cpus' numa_mem as they come on-line. During
5561 * node/memory hotplug, we'll fixup all on-line cpus.
5562 */
5563 for_each_online_cpu(cpu)
5564 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5565 #endif
5566 }
5567
5568 spin_unlock(&lock);
5569 }
5570
5571 static noinline void __init
5572 build_all_zonelists_init(void)
5573 {
5574 int cpu;
5575
5576 __build_all_zonelists(NULL);
5577
5578 /*
5579 * Initialize the boot_pagesets that are going to be used
5580 * for bootstrapping processors. The real pagesets for
5581 * each zone will be allocated later when the per cpu
5582 * allocator is available.
5583 *
5584 * boot_pagesets are used also for bootstrapping offline
5585 * cpus if the system is already booted because the pagesets
5586 * are needed to initialize allocators on a specific cpu too.
5587 * F.e. the percpu allocator needs the page allocator which
5588 * needs the percpu allocator in order to allocate its pagesets
5589 * (a chicken-egg dilemma).
5590 */
5591 for_each_possible_cpu(cpu)
5592 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
5593
5594 mminit_verify_zonelist();
5595 cpuset_init_current_mems_allowed();
5596 }
5597
5598 /*
5599 * unless system_state == SYSTEM_BOOTING.
5600 *
5601 * __ref due to call of __init annotated helper build_all_zonelists_init
5602 * [protected by SYSTEM_BOOTING].
5603 */
5604 void __ref build_all_zonelists(pg_data_t *pgdat)
5605 {
5606 if (system_state == SYSTEM_BOOTING) {
5607 build_all_zonelists_init();
5608 } else {
5609 __build_all_zonelists(pgdat);
5610 /* cpuset refresh routine should be here */
5611 }
5612 vm_total_pages = nr_free_pagecache_pages();
5613 /*
5614 * Disable grouping by mobility if the number of pages in the
5615 * system is too low to allow the mechanism to work. It would be
5616 * more accurate, but expensive to check per-zone. This check is
5617 * made on memory-hotadd so a system can start with mobility
5618 * disabled and enable it later
5619 */
5620 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5621 page_group_by_mobility_disabled = 1;
5622 else
5623 page_group_by_mobility_disabled = 0;
5624
5625 pr_info("Built %i zonelists, mobility grouping %s. Total pages: %ld\n",
5626 nr_online_nodes,
5627 page_group_by_mobility_disabled ? "off" : "on",
5628 vm_total_pages);
5629 #ifdef CONFIG_NUMA
5630 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5631 #endif
5632 }
5633
5634 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5635 static bool __meminit
5636 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
5637 {
5638 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5639 static struct memblock_region *r;
5640
5641 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
5642 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
5643 for_each_memblock(memory, r) {
5644 if (*pfn < memblock_region_memory_end_pfn(r))
5645 break;
5646 }
5647 }
5648 if (*pfn >= memblock_region_memory_base_pfn(r) &&
5649 memblock_is_mirror(r)) {
5650 *pfn = memblock_region_memory_end_pfn(r);
5651 return true;
5652 }
5653 }
5654 #endif
5655 return false;
5656 }
5657
5658 /*
5659 * Initially all pages are reserved - free ones are freed
5660 * up by memblock_free_all() once the early boot process is
5661 * done. Non-atomic initialization, single-pass.
5662 */
5663 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
5664 unsigned long start_pfn, enum memmap_context context,
5665 struct vmem_altmap *altmap)
5666 {
5667 unsigned long pfn, end_pfn = start_pfn + size;
5668 struct page *page;
5669
5670 if (highest_memmap_pfn < end_pfn - 1)
5671 highest_memmap_pfn = end_pfn - 1;
5672
5673 #ifdef CONFIG_ZONE_DEVICE
5674 /*
5675 * Honor reservation requested by the driver for this ZONE_DEVICE
5676 * memory. We limit the total number of pages to initialize to just
5677 * those that might contain the memory mapping. We will defer the
5678 * ZONE_DEVICE page initialization until after we have released
5679 * the hotplug lock.
5680 */
5681 if (zone == ZONE_DEVICE) {
5682 if (!altmap)
5683 return;
5684
5685 if (start_pfn == altmap->base_pfn)
5686 start_pfn += altmap->reserve;
5687 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5688 }
5689 #endif
5690
5691 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5692 /*
5693 * There can be holes in boot-time mem_map[]s handed to this
5694 * function. They do not exist on hotplugged memory.
5695 */
5696 if (context == MEMMAP_EARLY) {
5697 if (!early_pfn_valid(pfn))
5698 continue;
5699 if (!early_pfn_in_nid(pfn, nid))
5700 continue;
5701 if (overlap_memmap_init(zone, &pfn))
5702 continue;
5703 if (defer_init(nid, pfn, end_pfn))
5704 break;
5705 }
5706
5707 page = pfn_to_page(pfn);
5708 __init_single_page(page, pfn, zone, nid);
5709 if (context == MEMMAP_HOTPLUG)
5710 __SetPageReserved(page);
5711
5712 /*
5713 * Mark the block movable so that blocks are reserved for
5714 * movable at startup. This will force kernel allocations
5715 * to reserve their blocks rather than leaking throughout
5716 * the address space during boot when many long-lived
5717 * kernel allocations are made.
5718 *
5719 * bitmap is created for zone's valid pfn range. but memmap
5720 * can be created for invalid pages (for alignment)
5721 * check here not to call set_pageblock_migratetype() against
5722 * pfn out of zone.
5723 */
5724 if (!(pfn & (pageblock_nr_pages - 1))) {
5725 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5726 cond_resched();
5727 }
5728 }
5729 }
5730
5731 #ifdef CONFIG_ZONE_DEVICE
5732 void __ref memmap_init_zone_device(struct zone *zone,
5733 unsigned long start_pfn,
5734 unsigned long size,
5735 struct dev_pagemap *pgmap)
5736 {
5737 unsigned long pfn, end_pfn = start_pfn + size;
5738 struct pglist_data *pgdat = zone->zone_pgdat;
5739 unsigned long zone_idx = zone_idx(zone);
5740 unsigned long start = jiffies;
5741 int nid = pgdat->node_id;
5742
5743 if (WARN_ON_ONCE(!pgmap || !is_dev_zone(zone)))
5744 return;
5745
5746 /*
5747 * The call to memmap_init_zone should have already taken care
5748 * of the pages reserved for the memmap, so we can just jump to
5749 * the end of that region and start processing the device pages.
5750 */
5751 if (pgmap->altmap_valid) {
5752 struct vmem_altmap *altmap = &pgmap->altmap;
5753
5754 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5755 size = end_pfn - start_pfn;
5756 }
5757
5758 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5759 struct page *page = pfn_to_page(pfn);
5760
5761 __init_single_page(page, pfn, zone_idx, nid);
5762
5763 /*
5764 * Mark page reserved as it will need to wait for onlining
5765 * phase for it to be fully associated with a zone.
5766 *
5767 * We can use the non-atomic __set_bit operation for setting
5768 * the flag as we are still initializing the pages.
5769 */
5770 __SetPageReserved(page);
5771
5772 /*
5773 * ZONE_DEVICE pages union ->lru with a ->pgmap back
5774 * pointer and hmm_data. It is a bug if a ZONE_DEVICE
5775 * page is ever freed or placed on a driver-private list.
5776 */
5777 page->pgmap = pgmap;
5778 page->hmm_data = 0;
5779
5780 /*
5781 * Mark the block movable so that blocks are reserved for
5782 * movable at startup. This will force kernel allocations
5783 * to reserve their blocks rather than leaking throughout
5784 * the address space during boot when many long-lived
5785 * kernel allocations are made.
5786 *
5787 * bitmap is created for zone's valid pfn range. but memmap
5788 * can be created for invalid pages (for alignment)
5789 * check here not to call set_pageblock_migratetype() against
5790 * pfn out of zone.
5791 *
5792 * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
5793 * because this is done early in sparse_add_one_section
5794 */
5795 if (!(pfn & (pageblock_nr_pages - 1))) {
5796 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5797 cond_resched();
5798 }
5799 }
5800
5801 pr_info("%s initialised, %lu pages in %ums\n", dev_name(pgmap->dev),
5802 size, jiffies_to_msecs(jiffies - start));
5803 }
5804
5805 #endif
5806 static void __meminit zone_init_free_lists(struct zone *zone)
5807 {
5808 unsigned int order, t;
5809 for_each_migratetype_order(order, t) {
5810 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
5811 zone->free_area[order].nr_free = 0;
5812 }
5813 }
5814
5815 void __meminit __weak memmap_init(unsigned long size, int nid,
5816 unsigned long zone, unsigned long start_pfn)
5817 {
5818 memmap_init_zone(size, nid, zone, start_pfn, MEMMAP_EARLY, NULL);
5819 }
5820
5821 static int zone_batchsize(struct zone *zone)
5822 {
5823 #ifdef CONFIG_MMU
5824 int batch;
5825
5826 /*
5827 * The per-cpu-pages pools are set to around 1000th of the
5828 * size of the zone.
5829 */
5830 batch = zone_managed_pages(zone) / 1024;
5831 /* But no more than a meg. */
5832 if (batch * PAGE_SIZE > 1024 * 1024)
5833 batch = (1024 * 1024) / PAGE_SIZE;
5834 batch /= 4; /* We effectively *= 4 below */
5835 if (batch < 1)
5836 batch = 1;
5837
5838 /*
5839 * Clamp the batch to a 2^n - 1 value. Having a power
5840 * of 2 value was found to be more likely to have
5841 * suboptimal cache aliasing properties in some cases.
5842 *
5843 * For example if 2 tasks are alternately allocating
5844 * batches of pages, one task can end up with a lot
5845 * of pages of one half of the possible page colors
5846 * and the other with pages of the other colors.
5847 */
5848 batch = rounddown_pow_of_two(batch + batch/2) - 1;
5849
5850 return batch;
5851
5852 #else
5853 /* The deferral and batching of frees should be suppressed under NOMMU
5854 * conditions.
5855 *
5856 * The problem is that NOMMU needs to be able to allocate large chunks
5857 * of contiguous memory as there's no hardware page translation to
5858 * assemble apparent contiguous memory from discontiguous pages.
5859 *
5860 * Queueing large contiguous runs of pages for batching, however,
5861 * causes the pages to actually be freed in smaller chunks. As there
5862 * can be a significant delay between the individual batches being
5863 * recycled, this leads to the once large chunks of space being
5864 * fragmented and becoming unavailable for high-order allocations.
5865 */
5866 return 0;
5867 #endif
5868 }
5869
5870 /*
5871 * pcp->high and pcp->batch values are related and dependent on one another:
5872 * ->batch must never be higher then ->high.
5873 * The following function updates them in a safe manner without read side
5874 * locking.
5875 *
5876 * Any new users of pcp->batch and pcp->high should ensure they can cope with
5877 * those fields changing asynchronously (acording the the above rule).
5878 *
5879 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
5880 * outside of boot time (or some other assurance that no concurrent updaters
5881 * exist).
5882 */
5883 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
5884 unsigned long batch)
5885 {
5886 /* start with a fail safe value for batch */
5887 pcp->batch = 1;
5888 smp_wmb();
5889
5890 /* Update high, then batch, in order */
5891 pcp->high = high;
5892 smp_wmb();
5893
5894 pcp->batch = batch;
5895 }
5896
5897 /* a companion to pageset_set_high() */
5898 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
5899 {
5900 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
5901 }
5902
5903 static void pageset_init(struct per_cpu_pageset *p)
5904 {
5905 struct per_cpu_pages *pcp;
5906 int migratetype;
5907
5908 memset(p, 0, sizeof(*p));
5909
5910 pcp = &p->pcp;
5911 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
5912 INIT_LIST_HEAD(&pcp->lists[migratetype]);
5913 }
5914
5915 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
5916 {
5917 pageset_init(p);
5918 pageset_set_batch(p, batch);
5919 }
5920
5921 /*
5922 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
5923 * to the value high for the pageset p.
5924 */
5925 static void pageset_set_high(struct per_cpu_pageset *p,
5926 unsigned long high)
5927 {
5928 unsigned long batch = max(1UL, high / 4);
5929 if ((high / 4) > (PAGE_SHIFT * 8))
5930 batch = PAGE_SHIFT * 8;
5931
5932 pageset_update(&p->pcp, high, batch);
5933 }
5934
5935 static void pageset_set_high_and_batch(struct zone *zone,
5936 struct per_cpu_pageset *pcp)
5937 {
5938 if (percpu_pagelist_fraction)
5939 pageset_set_high(pcp,
5940 (zone_managed_pages(zone) /
5941 percpu_pagelist_fraction));
5942 else
5943 pageset_set_batch(pcp, zone_batchsize(zone));
5944 }
5945
5946 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
5947 {
5948 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
5949
5950 pageset_init(pcp);
5951 pageset_set_high_and_batch(zone, pcp);
5952 }
5953
5954 void __meminit setup_zone_pageset(struct zone *zone)
5955 {
5956 int cpu;
5957 zone->pageset = alloc_percpu(struct per_cpu_pageset);
5958 for_each_possible_cpu(cpu)
5959 zone_pageset_init(zone, cpu);
5960 }
5961
5962 /*
5963 * Allocate per cpu pagesets and initialize them.
5964 * Before this call only boot pagesets were available.
5965 */
5966 void __init setup_per_cpu_pageset(void)
5967 {
5968 struct pglist_data *pgdat;
5969 struct zone *zone;
5970
5971 for_each_populated_zone(zone)
5972 setup_zone_pageset(zone);
5973
5974 for_each_online_pgdat(pgdat)
5975 pgdat->per_cpu_nodestats =
5976 alloc_percpu(struct per_cpu_nodestat);
5977 }
5978
5979 static __meminit void zone_pcp_init(struct zone *zone)
5980 {
5981 /*
5982 * per cpu subsystem is not up at this point. The following code
5983 * relies on the ability of the linker to provide the
5984 * offset of a (static) per cpu variable into the per cpu area.
5985 */
5986 zone->pageset = &boot_pageset;
5987
5988 if (populated_zone(zone))
5989 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
5990 zone->name, zone->present_pages,
5991 zone_batchsize(zone));
5992 }
5993
5994 void __meminit init_currently_empty_zone(struct zone *zone,
5995 unsigned long zone_start_pfn,
5996 unsigned long size)
5997 {
5998 struct pglist_data *pgdat = zone->zone_pgdat;
5999 int zone_idx = zone_idx(zone) + 1;
6000
6001 if (zone_idx > pgdat->nr_zones)
6002 pgdat->nr_zones = zone_idx;
6003
6004 zone->zone_start_pfn = zone_start_pfn;
6005
6006 mminit_dprintk(MMINIT_TRACE, "memmap_init",
6007 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6008 pgdat->node_id,
6009 (unsigned long)zone_idx(zone),
6010 zone_start_pfn, (zone_start_pfn + size));
6011
6012 zone_init_free_lists(zone);
6013 zone->initialized = 1;
6014 }
6015
6016 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6017 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
6018
6019 /*
6020 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
6021 */
6022 int __meminit __early_pfn_to_nid(unsigned long pfn,
6023 struct mminit_pfnnid_cache *state)
6024 {
6025 unsigned long start_pfn, end_pfn;
6026 int nid;
6027
6028 if (state->last_start <= pfn && pfn < state->last_end)
6029 return state->last_nid;
6030
6031 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
6032 if (nid != -1) {
6033 state->last_start = start_pfn;
6034 state->last_end = end_pfn;
6035 state->last_nid = nid;
6036 }
6037
6038 return nid;
6039 }
6040 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
6041
6042 /**
6043 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
6044 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
6045 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
6046 *
6047 * If an architecture guarantees that all ranges registered contain no holes
6048 * and may be freed, this this function may be used instead of calling
6049 * memblock_free_early_nid() manually.
6050 */
6051 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
6052 {
6053 unsigned long start_pfn, end_pfn;
6054 int i, this_nid;
6055
6056 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
6057 start_pfn = min(start_pfn, max_low_pfn);
6058 end_pfn = min(end_pfn, max_low_pfn);
6059
6060 if (start_pfn < end_pfn)
6061 memblock_free_early_nid(PFN_PHYS(start_pfn),
6062 (end_pfn - start_pfn) << PAGE_SHIFT,
6063 this_nid);
6064 }
6065 }
6066
6067 /**
6068 * sparse_memory_present_with_active_regions - Call memory_present for each active range
6069 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
6070 *
6071 * If an architecture guarantees that all ranges registered contain no holes and may
6072 * be freed, this function may be used instead of calling memory_present() manually.
6073 */
6074 void __init sparse_memory_present_with_active_regions(int nid)
6075 {
6076 unsigned long start_pfn, end_pfn;
6077 int i, this_nid;
6078
6079 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
6080 memory_present(this_nid, start_pfn, end_pfn);
6081 }
6082
6083 /**
6084 * get_pfn_range_for_nid - Return the start and end page frames for a node
6085 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6086 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6087 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6088 *
6089 * It returns the start and end page frame of a node based on information
6090 * provided by memblock_set_node(). If called for a node
6091 * with no available memory, a warning is printed and the start and end
6092 * PFNs will be 0.
6093 */
6094 void __init get_pfn_range_for_nid(unsigned int nid,
6095 unsigned long *start_pfn, unsigned long *end_pfn)
6096 {
6097 unsigned long this_start_pfn, this_end_pfn;
6098 int i;
6099
6100 *start_pfn = -1UL;
6101 *end_pfn = 0;
6102
6103 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6104 *start_pfn = min(*start_pfn, this_start_pfn);
6105 *end_pfn = max(*end_pfn, this_end_pfn);
6106 }
6107
6108 if (*start_pfn == -1UL)
6109 *start_pfn = 0;
6110 }
6111
6112 /*
6113 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6114 * assumption is made that zones within a node are ordered in monotonic
6115 * increasing memory addresses so that the "highest" populated zone is used
6116 */
6117 static void __init find_usable_zone_for_movable(void)
6118 {
6119 int zone_index;
6120 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6121 if (zone_index == ZONE_MOVABLE)
6122 continue;
6123
6124 if (arch_zone_highest_possible_pfn[zone_index] >
6125 arch_zone_lowest_possible_pfn[zone_index])
6126 break;
6127 }
6128
6129 VM_BUG_ON(zone_index == -1);
6130 movable_zone = zone_index;
6131 }
6132
6133 /*
6134 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6135 * because it is sized independent of architecture. Unlike the other zones,
6136 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6137 * in each node depending on the size of each node and how evenly kernelcore
6138 * is distributed. This helper function adjusts the zone ranges
6139 * provided by the architecture for a given node by using the end of the
6140 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6141 * zones within a node are in order of monotonic increases memory addresses
6142 */
6143 static void __init adjust_zone_range_for_zone_movable(int nid,
6144 unsigned long zone_type,
6145 unsigned long node_start_pfn,
6146 unsigned long node_end_pfn,
6147 unsigned long *zone_start_pfn,
6148 unsigned long *zone_end_pfn)
6149 {
6150 /* Only adjust if ZONE_MOVABLE is on this node */
6151 if (zone_movable_pfn[nid]) {
6152 /* Size ZONE_MOVABLE */
6153 if (zone_type == ZONE_MOVABLE) {
6154 *zone_start_pfn = zone_movable_pfn[nid];
6155 *zone_end_pfn = min(node_end_pfn,
6156 arch_zone_highest_possible_pfn[movable_zone]);
6157
6158 /* Adjust for ZONE_MOVABLE starting within this range */
6159 } else if (!mirrored_kernelcore &&
6160 *zone_start_pfn < zone_movable_pfn[nid] &&
6161 *zone_end_pfn > zone_movable_pfn[nid]) {
6162 *zone_end_pfn = zone_movable_pfn[nid];
6163
6164 /* Check if this whole range is within ZONE_MOVABLE */
6165 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6166 *zone_start_pfn = *zone_end_pfn;
6167 }
6168 }
6169
6170 /*
6171 * Return the number of pages a zone spans in a node, including holes
6172 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6173 */
6174 static unsigned long __init zone_spanned_pages_in_node(int nid,
6175 unsigned long zone_type,
6176 unsigned long node_start_pfn,
6177 unsigned long node_end_pfn,
6178 unsigned long *zone_start_pfn,
6179 unsigned long *zone_end_pfn,
6180 unsigned long *ignored)
6181 {
6182 /* When hotadd a new node from cpu_up(), the node should be empty */
6183 if (!node_start_pfn && !node_end_pfn)
6184 return 0;
6185
6186 /* Get the start and end of the zone */
6187 *zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
6188 *zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
6189 adjust_zone_range_for_zone_movable(nid, zone_type,
6190 node_start_pfn, node_end_pfn,
6191 zone_start_pfn, zone_end_pfn);
6192
6193 /* Check that this node has pages within the zone's required range */
6194 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6195 return 0;
6196
6197 /* Move the zone boundaries inside the node if necessary */
6198 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6199 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6200
6201 /* Return the spanned pages */
6202 return *zone_end_pfn - *zone_start_pfn;
6203 }
6204
6205 /*
6206 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6207 * then all holes in the requested range will be accounted for.
6208 */
6209 unsigned long __init __absent_pages_in_range(int nid,
6210 unsigned long range_start_pfn,
6211 unsigned long range_end_pfn)
6212 {
6213 unsigned long nr_absent = range_end_pfn - range_start_pfn;
6214 unsigned long start_pfn, end_pfn;
6215 int i;
6216
6217 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6218 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6219 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6220 nr_absent -= end_pfn - start_pfn;
6221 }
6222 return nr_absent;
6223 }
6224
6225 /**
6226 * absent_pages_in_range - Return number of page frames in holes within a range
6227 * @start_pfn: The start PFN to start searching for holes
6228 * @end_pfn: The end PFN to stop searching for holes
6229 *
6230 * It returns the number of pages frames in memory holes within a range.
6231 */
6232 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6233 unsigned long end_pfn)
6234 {
6235 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6236 }
6237
6238 /* Return the number of page frames in holes in a zone on a node */
6239 static unsigned long __init zone_absent_pages_in_node(int nid,
6240 unsigned long zone_type,
6241 unsigned long node_start_pfn,
6242 unsigned long node_end_pfn,
6243 unsigned long *ignored)
6244 {
6245 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6246 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6247 unsigned long zone_start_pfn, zone_end_pfn;
6248 unsigned long nr_absent;
6249
6250 /* When hotadd a new node from cpu_up(), the node should be empty */
6251 if (!node_start_pfn && !node_end_pfn)
6252 return 0;
6253
6254 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6255 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6256
6257 adjust_zone_range_for_zone_movable(nid, zone_type,
6258 node_start_pfn, node_end_pfn,
6259 &zone_start_pfn, &zone_end_pfn);
6260 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6261
6262 /*
6263 * ZONE_MOVABLE handling.
6264 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6265 * and vice versa.
6266 */
6267 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6268 unsigned long start_pfn, end_pfn;
6269 struct memblock_region *r;
6270
6271 for_each_memblock(memory, r) {
6272 start_pfn = clamp(memblock_region_memory_base_pfn(r),
6273 zone_start_pfn, zone_end_pfn);
6274 end_pfn = clamp(memblock_region_memory_end_pfn(r),
6275 zone_start_pfn, zone_end_pfn);
6276
6277 if (zone_type == ZONE_MOVABLE &&
6278 memblock_is_mirror(r))
6279 nr_absent += end_pfn - start_pfn;
6280
6281 if (zone_type == ZONE_NORMAL &&
6282 !memblock_is_mirror(r))
6283 nr_absent += end_pfn - start_pfn;
6284 }
6285 }
6286
6287 return nr_absent;
6288 }
6289
6290 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6291 static inline unsigned long __init zone_spanned_pages_in_node(int nid,
6292 unsigned long zone_type,
6293 unsigned long node_start_pfn,
6294 unsigned long node_end_pfn,
6295 unsigned long *zone_start_pfn,
6296 unsigned long *zone_end_pfn,
6297 unsigned long *zones_size)
6298 {
6299 unsigned int zone;
6300
6301 *zone_start_pfn = node_start_pfn;
6302 for (zone = 0; zone < zone_type; zone++)
6303 *zone_start_pfn += zones_size[zone];
6304
6305 *zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
6306
6307 return zones_size[zone_type];
6308 }
6309
6310 static inline unsigned long __init zone_absent_pages_in_node(int nid,
6311 unsigned long zone_type,
6312 unsigned long node_start_pfn,
6313 unsigned long node_end_pfn,
6314 unsigned long *zholes_size)
6315 {
6316 if (!zholes_size)
6317 return 0;
6318
6319 return zholes_size[zone_type];
6320 }
6321
6322 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6323
6324 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6325 unsigned long node_start_pfn,
6326 unsigned long node_end_pfn,
6327 unsigned long *zones_size,
6328 unsigned long *zholes_size)
6329 {
6330 unsigned long realtotalpages = 0, totalpages = 0;
6331 enum zone_type i;
6332
6333 for (i = 0; i < MAX_NR_ZONES; i++) {
6334 struct zone *zone = pgdat->node_zones + i;
6335 unsigned long zone_start_pfn, zone_end_pfn;
6336 unsigned long size, real_size;
6337
6338 size = zone_spanned_pages_in_node(pgdat->node_id, i,
6339 node_start_pfn,
6340 node_end_pfn,
6341 &zone_start_pfn,
6342 &zone_end_pfn,
6343 zones_size);
6344 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
6345 node_start_pfn, node_end_pfn,
6346 zholes_size);
6347 if (size)
6348 zone->zone_start_pfn = zone_start_pfn;
6349 else
6350 zone->zone_start_pfn = 0;
6351 zone->spanned_pages = size;
6352 zone->present_pages = real_size;
6353
6354 totalpages += size;
6355 realtotalpages += real_size;
6356 }
6357
6358 pgdat->node_spanned_pages = totalpages;
6359 pgdat->node_present_pages = realtotalpages;
6360 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
6361 realtotalpages);
6362 }
6363
6364 #ifndef CONFIG_SPARSEMEM
6365 /*
6366 * Calculate the size of the zone->blockflags rounded to an unsigned long
6367 * Start by making sure zonesize is a multiple of pageblock_order by rounding
6368 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6369 * round what is now in bits to nearest long in bits, then return it in
6370 * bytes.
6371 */
6372 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
6373 {
6374 unsigned long usemapsize;
6375
6376 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
6377 usemapsize = roundup(zonesize, pageblock_nr_pages);
6378 usemapsize = usemapsize >> pageblock_order;
6379 usemapsize *= NR_PAGEBLOCK_BITS;
6380 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
6381
6382 return usemapsize / 8;
6383 }
6384
6385 static void __ref setup_usemap(struct pglist_data *pgdat,
6386 struct zone *zone,
6387 unsigned long zone_start_pfn,
6388 unsigned long zonesize)
6389 {
6390 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
6391 zone->pageblock_flags = NULL;
6392 if (usemapsize)
6393 zone->pageblock_flags =
6394 memblock_alloc_node_nopanic(usemapsize,
6395 pgdat->node_id);
6396 }
6397 #else
6398 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
6399 unsigned long zone_start_pfn, unsigned long zonesize) {}
6400 #endif /* CONFIG_SPARSEMEM */
6401
6402 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6403
6404 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
6405 void __init set_pageblock_order(void)
6406 {
6407 unsigned int order;
6408
6409 /* Check that pageblock_nr_pages has not already been setup */
6410 if (pageblock_order)
6411 return;
6412
6413 if (HPAGE_SHIFT > PAGE_SHIFT)
6414 order = HUGETLB_PAGE_ORDER;
6415 else
6416 order = MAX_ORDER - 1;
6417
6418 /*
6419 * Assume the largest contiguous order of interest is a huge page.
6420 * This value may be variable depending on boot parameters on IA64 and
6421 * powerpc.
6422 */
6423 pageblock_order = order;
6424 }
6425 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6426
6427 /*
6428 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6429 * is unused as pageblock_order is set at compile-time. See
6430 * include/linux/pageblock-flags.h for the values of pageblock_order based on
6431 * the kernel config
6432 */
6433 void __init set_pageblock_order(void)
6434 {
6435 }
6436
6437 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6438
6439 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
6440 unsigned long present_pages)
6441 {
6442 unsigned long pages = spanned_pages;
6443
6444 /*
6445 * Provide a more accurate estimation if there are holes within
6446 * the zone and SPARSEMEM is in use. If there are holes within the
6447 * zone, each populated memory region may cost us one or two extra
6448 * memmap pages due to alignment because memmap pages for each
6449 * populated regions may not be naturally aligned on page boundary.
6450 * So the (present_pages >> 4) heuristic is a tradeoff for that.
6451 */
6452 if (spanned_pages > present_pages + (present_pages >> 4) &&
6453 IS_ENABLED(CONFIG_SPARSEMEM))
6454 pages = present_pages;
6455
6456 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
6457 }
6458
6459 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6460 static void pgdat_init_split_queue(struct pglist_data *pgdat)
6461 {
6462 spin_lock_init(&pgdat->split_queue_lock);
6463 INIT_LIST_HEAD(&pgdat->split_queue);
6464 pgdat->split_queue_len = 0;
6465 }
6466 #else
6467 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
6468 #endif
6469
6470 #ifdef CONFIG_COMPACTION
6471 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
6472 {
6473 init_waitqueue_head(&pgdat->kcompactd_wait);
6474 }
6475 #else
6476 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
6477 #endif
6478
6479 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
6480 {
6481 pgdat_resize_init(pgdat);
6482
6483 pgdat_init_split_queue(pgdat);
6484 pgdat_init_kcompactd(pgdat);
6485
6486 init_waitqueue_head(&pgdat->kswapd_wait);
6487 init_waitqueue_head(&pgdat->pfmemalloc_wait);
6488
6489 pgdat_page_ext_init(pgdat);
6490 spin_lock_init(&pgdat->lru_lock);
6491 lruvec_init(node_lruvec(pgdat));
6492 }
6493
6494 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
6495 unsigned long remaining_pages)
6496 {
6497 atomic_long_set(&zone->managed_pages, remaining_pages);
6498 zone_set_nid(zone, nid);
6499 zone->name = zone_names[idx];
6500 zone->zone_pgdat = NODE_DATA(nid);
6501 spin_lock_init(&zone->lock);
6502 zone_seqlock_init(zone);
6503 zone_pcp_init(zone);
6504 }
6505
6506 /*
6507 * Set up the zone data structures
6508 * - init pgdat internals
6509 * - init all zones belonging to this node
6510 *
6511 * NOTE: this function is only called during memory hotplug
6512 */
6513 #ifdef CONFIG_MEMORY_HOTPLUG
6514 void __ref free_area_init_core_hotplug(int nid)
6515 {
6516 enum zone_type z;
6517 pg_data_t *pgdat = NODE_DATA(nid);
6518
6519 pgdat_init_internals(pgdat);
6520 for (z = 0; z < MAX_NR_ZONES; z++)
6521 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
6522 }
6523 #endif
6524
6525 /*
6526 * Set up the zone data structures:
6527 * - mark all pages reserved
6528 * - mark all memory queues empty
6529 * - clear the memory bitmaps
6530 *
6531 * NOTE: pgdat should get zeroed by caller.
6532 * NOTE: this function is only called during early init.
6533 */
6534 static void __init free_area_init_core(struct pglist_data *pgdat)
6535 {
6536 enum zone_type j;
6537 int nid = pgdat->node_id;
6538
6539 pgdat_init_internals(pgdat);
6540 pgdat->per_cpu_nodestats = &boot_nodestats;
6541
6542 for (j = 0; j < MAX_NR_ZONES; j++) {
6543 struct zone *zone = pgdat->node_zones + j;
6544 unsigned long size, freesize, memmap_pages;
6545 unsigned long zone_start_pfn = zone->zone_start_pfn;
6546
6547 size = zone->spanned_pages;
6548 freesize = zone->present_pages;
6549
6550 /*
6551 * Adjust freesize so that it accounts for how much memory
6552 * is used by this zone for memmap. This affects the watermark
6553 * and per-cpu initialisations
6554 */
6555 memmap_pages = calc_memmap_size(size, freesize);
6556 if (!is_highmem_idx(j)) {
6557 if (freesize >= memmap_pages) {
6558 freesize -= memmap_pages;
6559 if (memmap_pages)
6560 printk(KERN_DEBUG
6561 " %s zone: %lu pages used for memmap\n",
6562 zone_names[j], memmap_pages);
6563 } else
6564 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
6565 zone_names[j], memmap_pages, freesize);
6566 }
6567
6568 /* Account for reserved pages */
6569 if (j == 0 && freesize > dma_reserve) {
6570 freesize -= dma_reserve;
6571 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
6572 zone_names[0], dma_reserve);
6573 }
6574
6575 if (!is_highmem_idx(j))
6576 nr_kernel_pages += freesize;
6577 /* Charge for highmem memmap if there are enough kernel pages */
6578 else if (nr_kernel_pages > memmap_pages * 2)
6579 nr_kernel_pages -= memmap_pages;
6580 nr_all_pages += freesize;
6581
6582 /*
6583 * Set an approximate value for lowmem here, it will be adjusted
6584 * when the bootmem allocator frees pages into the buddy system.
6585 * And all highmem pages will be managed by the buddy system.
6586 */
6587 zone_init_internals(zone, j, nid, freesize);
6588
6589 if (!size)
6590 continue;
6591
6592 set_pageblock_order();
6593 setup_usemap(pgdat, zone, zone_start_pfn, size);
6594 init_currently_empty_zone(zone, zone_start_pfn, size);
6595 memmap_init(size, nid, j, zone_start_pfn);
6596 }
6597 }
6598
6599 #ifdef CONFIG_FLAT_NODE_MEM_MAP
6600 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
6601 {
6602 unsigned long __maybe_unused start = 0;
6603 unsigned long __maybe_unused offset = 0;
6604
6605 /* Skip empty nodes */
6606 if (!pgdat->node_spanned_pages)
6607 return;
6608
6609 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
6610 offset = pgdat->node_start_pfn - start;
6611 /* ia64 gets its own node_mem_map, before this, without bootmem */
6612 if (!pgdat->node_mem_map) {
6613 unsigned long size, end;
6614 struct page *map;
6615
6616 /*
6617 * The zone's endpoints aren't required to be MAX_ORDER
6618 * aligned but the node_mem_map endpoints must be in order
6619 * for the buddy allocator to function correctly.
6620 */
6621 end = pgdat_end_pfn(pgdat);
6622 end = ALIGN(end, MAX_ORDER_NR_PAGES);
6623 size = (end - start) * sizeof(struct page);
6624 map = memblock_alloc_node_nopanic(size, pgdat->node_id);
6625 pgdat->node_mem_map = map + offset;
6626 }
6627 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6628 __func__, pgdat->node_id, (unsigned long)pgdat,
6629 (unsigned long)pgdat->node_mem_map);
6630 #ifndef CONFIG_NEED_MULTIPLE_NODES
6631 /*
6632 * With no DISCONTIG, the global mem_map is just set as node 0's
6633 */
6634 if (pgdat == NODE_DATA(0)) {
6635 mem_map = NODE_DATA(0)->node_mem_map;
6636 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
6637 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
6638 mem_map -= offset;
6639 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6640 }
6641 #endif
6642 }
6643 #else
6644 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
6645 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6646
6647 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
6648 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
6649 {
6650 pgdat->first_deferred_pfn = ULONG_MAX;
6651 }
6652 #else
6653 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
6654 #endif
6655
6656 void __init free_area_init_node(int nid, unsigned long *zones_size,
6657 unsigned long node_start_pfn,
6658 unsigned long *zholes_size)
6659 {
6660 pg_data_t *pgdat = NODE_DATA(nid);
6661 unsigned long start_pfn = 0;
6662 unsigned long end_pfn = 0;
6663
6664 /* pg_data_t should be reset to zero when it's allocated */
6665 WARN_ON(pgdat->nr_zones || pgdat->kswapd_classzone_idx);
6666
6667 pgdat->node_id = nid;
6668 pgdat->node_start_pfn = node_start_pfn;
6669 pgdat->per_cpu_nodestats = NULL;
6670 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6671 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
6672 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
6673 (u64)start_pfn << PAGE_SHIFT,
6674 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
6675 #else
6676 start_pfn = node_start_pfn;
6677 #endif
6678 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
6679 zones_size, zholes_size);
6680
6681 alloc_node_mem_map(pgdat);
6682 pgdat_set_deferred_range(pgdat);
6683
6684 free_area_init_core(pgdat);
6685 }
6686
6687 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6688 /*
6689 * Zero all valid struct pages in range [spfn, epfn), return number of struct
6690 * pages zeroed
6691 */
6692 static u64 zero_pfn_range(unsigned long spfn, unsigned long epfn)
6693 {
6694 unsigned long pfn;
6695 u64 pgcnt = 0;
6696
6697 for (pfn = spfn; pfn < epfn; pfn++) {
6698 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6699 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6700 + pageblock_nr_pages - 1;
6701 continue;
6702 }
6703 mm_zero_struct_page(pfn_to_page(pfn));
6704 pgcnt++;
6705 }
6706
6707 return pgcnt;
6708 }
6709
6710 /*
6711 * Only struct pages that are backed by physical memory are zeroed and
6712 * initialized by going through __init_single_page(). But, there are some
6713 * struct pages which are reserved in memblock allocator and their fields
6714 * may be accessed (for example page_to_pfn() on some configuration accesses
6715 * flags). We must explicitly zero those struct pages.
6716 *
6717 * This function also addresses a similar issue where struct pages are left
6718 * uninitialized because the physical address range is not covered by
6719 * memblock.memory or memblock.reserved. That could happen when memblock
6720 * layout is manually configured via memmap=.
6721 */
6722 void __init zero_resv_unavail(void)
6723 {
6724 phys_addr_t start, end;
6725 u64 i, pgcnt;
6726 phys_addr_t next = 0;
6727
6728 /*
6729 * Loop through unavailable ranges not covered by memblock.memory.
6730 */
6731 pgcnt = 0;
6732 for_each_mem_range(i, &memblock.memory, NULL,
6733 NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
6734 if (next < start)
6735 pgcnt += zero_pfn_range(PFN_DOWN(next), PFN_UP(start));
6736 next = end;
6737 }
6738 pgcnt += zero_pfn_range(PFN_DOWN(next), max_pfn);
6739
6740 /*
6741 * Struct pages that do not have backing memory. This could be because
6742 * firmware is using some of this memory, or for some other reasons.
6743 */
6744 if (pgcnt)
6745 pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
6746 }
6747 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
6748
6749 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6750
6751 #if MAX_NUMNODES > 1
6752 /*
6753 * Figure out the number of possible node ids.
6754 */
6755 void __init setup_nr_node_ids(void)
6756 {
6757 unsigned int highest;
6758
6759 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
6760 nr_node_ids = highest + 1;
6761 }
6762 #endif
6763
6764 /**
6765 * node_map_pfn_alignment - determine the maximum internode alignment
6766 *
6767 * This function should be called after node map is populated and sorted.
6768 * It calculates the maximum power of two alignment which can distinguish
6769 * all the nodes.
6770 *
6771 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
6772 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
6773 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
6774 * shifted, 1GiB is enough and this function will indicate so.
6775 *
6776 * This is used to test whether pfn -> nid mapping of the chosen memory
6777 * model has fine enough granularity to avoid incorrect mapping for the
6778 * populated node map.
6779 *
6780 * Returns the determined alignment in pfn's. 0 if there is no alignment
6781 * requirement (single node).
6782 */
6783 unsigned long __init node_map_pfn_alignment(void)
6784 {
6785 unsigned long accl_mask = 0, last_end = 0;
6786 unsigned long start, end, mask;
6787 int last_nid = -1;
6788 int i, nid;
6789
6790 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
6791 if (!start || last_nid < 0 || last_nid == nid) {
6792 last_nid = nid;
6793 last_end = end;
6794 continue;
6795 }
6796
6797 /*
6798 * Start with a mask granular enough to pin-point to the
6799 * start pfn and tick off bits one-by-one until it becomes
6800 * too coarse to separate the current node from the last.
6801 */
6802 mask = ~((1 << __ffs(start)) - 1);
6803 while (mask && last_end <= (start & (mask << 1)))
6804 mask <<= 1;
6805
6806 /* accumulate all internode masks */
6807 accl_mask |= mask;
6808 }
6809
6810 /* convert mask to number of pages */
6811 return ~accl_mask + 1;
6812 }
6813
6814 /* Find the lowest pfn for a node */
6815 static unsigned long __init find_min_pfn_for_node(int nid)
6816 {
6817 unsigned long min_pfn = ULONG_MAX;
6818 unsigned long start_pfn;
6819 int i;
6820
6821 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
6822 min_pfn = min(min_pfn, start_pfn);
6823
6824 if (min_pfn == ULONG_MAX) {
6825 pr_warn("Could not find start_pfn for node %d\n", nid);
6826 return 0;
6827 }
6828
6829 return min_pfn;
6830 }
6831
6832 /**
6833 * find_min_pfn_with_active_regions - Find the minimum PFN registered
6834 *
6835 * It returns the minimum PFN based on information provided via
6836 * memblock_set_node().
6837 */
6838 unsigned long __init find_min_pfn_with_active_regions(void)
6839 {
6840 return find_min_pfn_for_node(MAX_NUMNODES);
6841 }
6842
6843 /*
6844 * early_calculate_totalpages()
6845 * Sum pages in active regions for movable zone.
6846 * Populate N_MEMORY for calculating usable_nodes.
6847 */
6848 static unsigned long __init early_calculate_totalpages(void)
6849 {
6850 unsigned long totalpages = 0;
6851 unsigned long start_pfn, end_pfn;
6852 int i, nid;
6853
6854 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
6855 unsigned long pages = end_pfn - start_pfn;
6856
6857 totalpages += pages;
6858 if (pages)
6859 node_set_state(nid, N_MEMORY);
6860 }
6861 return totalpages;
6862 }
6863
6864 /*
6865 * Find the PFN the Movable zone begins in each node. Kernel memory
6866 * is spread evenly between nodes as long as the nodes have enough
6867 * memory. When they don't, some nodes will have more kernelcore than
6868 * others
6869 */
6870 static void __init find_zone_movable_pfns_for_nodes(void)
6871 {
6872 int i, nid;
6873 unsigned long usable_startpfn;
6874 unsigned long kernelcore_node, kernelcore_remaining;
6875 /* save the state before borrow the nodemask */
6876 nodemask_t saved_node_state = node_states[N_MEMORY];
6877 unsigned long totalpages = early_calculate_totalpages();
6878 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
6879 struct memblock_region *r;
6880
6881 /* Need to find movable_zone earlier when movable_node is specified. */
6882 find_usable_zone_for_movable();
6883
6884 /*
6885 * If movable_node is specified, ignore kernelcore and movablecore
6886 * options.
6887 */
6888 if (movable_node_is_enabled()) {
6889 for_each_memblock(memory, r) {
6890 if (!memblock_is_hotpluggable(r))
6891 continue;
6892
6893 nid = r->nid;
6894
6895 usable_startpfn = PFN_DOWN(r->base);
6896 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
6897 min(usable_startpfn, zone_movable_pfn[nid]) :
6898 usable_startpfn;
6899 }
6900
6901 goto out2;
6902 }
6903
6904 /*
6905 * If kernelcore=mirror is specified, ignore movablecore option
6906 */
6907 if (mirrored_kernelcore) {
6908 bool mem_below_4gb_not_mirrored = false;
6909
6910 for_each_memblock(memory, r) {
6911 if (memblock_is_mirror(r))
6912 continue;
6913
6914 nid = r->nid;
6915
6916 usable_startpfn = memblock_region_memory_base_pfn(r);
6917
6918 if (usable_startpfn < 0x100000) {
6919 mem_below_4gb_not_mirrored = true;
6920 continue;
6921 }
6922
6923 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
6924 min(usable_startpfn, zone_movable_pfn[nid]) :
6925 usable_startpfn;
6926 }
6927
6928 if (mem_below_4gb_not_mirrored)
6929 pr_warn("This configuration results in unmirrored kernel memory.");
6930
6931 goto out2;
6932 }
6933
6934 /*
6935 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
6936 * amount of necessary memory.
6937 */
6938 if (required_kernelcore_percent)
6939 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
6940 10000UL;
6941 if (required_movablecore_percent)
6942 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
6943 10000UL;
6944
6945 /*
6946 * If movablecore= was specified, calculate what size of
6947 * kernelcore that corresponds so that memory usable for
6948 * any allocation type is evenly spread. If both kernelcore
6949 * and movablecore are specified, then the value of kernelcore
6950 * will be used for required_kernelcore if it's greater than
6951 * what movablecore would have allowed.
6952 */
6953 if (required_movablecore) {
6954 unsigned long corepages;
6955
6956 /*
6957 * Round-up so that ZONE_MOVABLE is at least as large as what
6958 * was requested by the user
6959 */
6960 required_movablecore =
6961 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
6962 required_movablecore = min(totalpages, required_movablecore);
6963 corepages = totalpages - required_movablecore;
6964
6965 required_kernelcore = max(required_kernelcore, corepages);
6966 }
6967
6968 /*
6969 * If kernelcore was not specified or kernelcore size is larger
6970 * than totalpages, there is no ZONE_MOVABLE.
6971 */
6972 if (!required_kernelcore || required_kernelcore >= totalpages)
6973 goto out;
6974
6975 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
6976 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
6977
6978 restart:
6979 /* Spread kernelcore memory as evenly as possible throughout nodes */
6980 kernelcore_node = required_kernelcore / usable_nodes;
6981 for_each_node_state(nid, N_MEMORY) {
6982 unsigned long start_pfn, end_pfn;
6983
6984 /*
6985 * Recalculate kernelcore_node if the division per node
6986 * now exceeds what is necessary to satisfy the requested
6987 * amount of memory for the kernel
6988 */
6989 if (required_kernelcore < kernelcore_node)
6990 kernelcore_node = required_kernelcore / usable_nodes;
6991
6992 /*
6993 * As the map is walked, we track how much memory is usable
6994 * by the kernel using kernelcore_remaining. When it is
6995 * 0, the rest of the node is usable by ZONE_MOVABLE
6996 */
6997 kernelcore_remaining = kernelcore_node;
6998
6999 /* Go through each range of PFNs within this node */
7000 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7001 unsigned long size_pages;
7002
7003 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7004 if (start_pfn >= end_pfn)
7005 continue;
7006
7007 /* Account for what is only usable for kernelcore */
7008 if (start_pfn < usable_startpfn) {
7009 unsigned long kernel_pages;
7010 kernel_pages = min(end_pfn, usable_startpfn)
7011 - start_pfn;
7012
7013 kernelcore_remaining -= min(kernel_pages,
7014 kernelcore_remaining);
7015 required_kernelcore -= min(kernel_pages,
7016 required_kernelcore);
7017
7018 /* Continue if range is now fully accounted */
7019 if (end_pfn <= usable_startpfn) {
7020
7021 /*
7022 * Push zone_movable_pfn to the end so
7023 * that if we have to rebalance
7024 * kernelcore across nodes, we will
7025 * not double account here
7026 */
7027 zone_movable_pfn[nid] = end_pfn;
7028 continue;
7029 }
7030 start_pfn = usable_startpfn;
7031 }
7032
7033 /*
7034 * The usable PFN range for ZONE_MOVABLE is from
7035 * start_pfn->end_pfn. Calculate size_pages as the
7036 * number of pages used as kernelcore
7037 */
7038 size_pages = end_pfn - start_pfn;
7039 if (size_pages > kernelcore_remaining)
7040 size_pages = kernelcore_remaining;
7041 zone_movable_pfn[nid] = start_pfn + size_pages;
7042
7043 /*
7044 * Some kernelcore has been met, update counts and
7045 * break if the kernelcore for this node has been
7046 * satisfied
7047 */
7048 required_kernelcore -= min(required_kernelcore,
7049 size_pages);
7050 kernelcore_remaining -= size_pages;
7051 if (!kernelcore_remaining)
7052 break;
7053 }
7054 }
7055
7056 /*
7057 * If there is still required_kernelcore, we do another pass with one
7058 * less node in the count. This will push zone_movable_pfn[nid] further
7059 * along on the nodes that still have memory until kernelcore is
7060 * satisfied
7061 */
7062 usable_nodes--;
7063 if (usable_nodes && required_kernelcore > usable_nodes)
7064 goto restart;
7065
7066 out2:
7067 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7068 for (nid = 0; nid < MAX_NUMNODES; nid++)
7069 zone_movable_pfn[nid] =
7070 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7071
7072 out:
7073 /* restore the node_state */
7074 node_states[N_MEMORY] = saved_node_state;
7075 }
7076
7077 /* Any regular or high memory on that node ? */
7078 static void check_for_memory(pg_data_t *pgdat, int nid)
7079 {
7080 enum zone_type zone_type;
7081
7082 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7083 struct zone *zone = &pgdat->node_zones[zone_type];
7084 if (populated_zone(zone)) {
7085 if (IS_ENABLED(CONFIG_HIGHMEM))
7086 node_set_state(nid, N_HIGH_MEMORY);
7087 if (zone_type <= ZONE_NORMAL)
7088 node_set_state(nid, N_NORMAL_MEMORY);
7089 break;
7090 }
7091 }
7092 }
7093
7094 /**
7095 * free_area_init_nodes - Initialise all pg_data_t and zone data
7096 * @max_zone_pfn: an array of max PFNs for each zone
7097 *
7098 * This will call free_area_init_node() for each active node in the system.
7099 * Using the page ranges provided by memblock_set_node(), the size of each
7100 * zone in each node and their holes is calculated. If the maximum PFN
7101 * between two adjacent zones match, it is assumed that the zone is empty.
7102 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7103 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7104 * starts where the previous one ended. For example, ZONE_DMA32 starts
7105 * at arch_max_dma_pfn.
7106 */
7107 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
7108 {
7109 unsigned long start_pfn, end_pfn;
7110 int i, nid;
7111
7112 /* Record where the zone boundaries are */
7113 memset(arch_zone_lowest_possible_pfn, 0,
7114 sizeof(arch_zone_lowest_possible_pfn));
7115 memset(arch_zone_highest_possible_pfn, 0,
7116 sizeof(arch_zone_highest_possible_pfn));
7117
7118 start_pfn = find_min_pfn_with_active_regions();
7119
7120 for (i = 0; i < MAX_NR_ZONES; i++) {
7121 if (i == ZONE_MOVABLE)
7122 continue;
7123
7124 end_pfn = max(max_zone_pfn[i], start_pfn);
7125 arch_zone_lowest_possible_pfn[i] = start_pfn;
7126 arch_zone_highest_possible_pfn[i] = end_pfn;
7127
7128 start_pfn = end_pfn;
7129 }
7130
7131 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7132 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7133 find_zone_movable_pfns_for_nodes();
7134
7135 /* Print out the zone ranges */
7136 pr_info("Zone ranges:\n");
7137 for (i = 0; i < MAX_NR_ZONES; i++) {
7138 if (i == ZONE_MOVABLE)
7139 continue;
7140 pr_info(" %-8s ", zone_names[i]);
7141 if (arch_zone_lowest_possible_pfn[i] ==
7142 arch_zone_highest_possible_pfn[i])
7143 pr_cont("empty\n");
7144 else
7145 pr_cont("[mem %#018Lx-%#018Lx]\n",
7146 (u64)arch_zone_lowest_possible_pfn[i]
7147 << PAGE_SHIFT,
7148 ((u64)arch_zone_highest_possible_pfn[i]
7149 << PAGE_SHIFT) - 1);
7150 }
7151
7152 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7153 pr_info("Movable zone start for each node\n");
7154 for (i = 0; i < MAX_NUMNODES; i++) {
7155 if (zone_movable_pfn[i])
7156 pr_info(" Node %d: %#018Lx\n", i,
7157 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7158 }
7159
7160 /* Print out the early node map */
7161 pr_info("Early memory node ranges\n");
7162 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
7163 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7164 (u64)start_pfn << PAGE_SHIFT,
7165 ((u64)end_pfn << PAGE_SHIFT) - 1);
7166
7167 /* Initialise every node */
7168 mminit_verify_pageflags_layout();
7169 setup_nr_node_ids();
7170 zero_resv_unavail();
7171 for_each_online_node(nid) {
7172 pg_data_t *pgdat = NODE_DATA(nid);
7173 free_area_init_node(nid, NULL,
7174 find_min_pfn_for_node(nid), NULL);
7175
7176 /* Any memory on that node */
7177 if (pgdat->node_present_pages)
7178 node_set_state(nid, N_MEMORY);
7179 check_for_memory(pgdat, nid);
7180 }
7181 }
7182
7183 static int __init cmdline_parse_core(char *p, unsigned long *core,
7184 unsigned long *percent)
7185 {
7186 unsigned long long coremem;
7187 char *endptr;
7188
7189 if (!p)
7190 return -EINVAL;
7191
7192 /* Value may be a percentage of total memory, otherwise bytes */
7193 coremem = simple_strtoull(p, &endptr, 0);
7194 if (*endptr == '%') {
7195 /* Paranoid check for percent values greater than 100 */
7196 WARN_ON(coremem > 100);
7197
7198 *percent = coremem;
7199 } else {
7200 coremem = memparse(p, &p);
7201 /* Paranoid check that UL is enough for the coremem value */
7202 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7203
7204 *core = coremem >> PAGE_SHIFT;
7205 *percent = 0UL;
7206 }
7207 return 0;
7208 }
7209
7210 /*
7211 * kernelcore=size sets the amount of memory for use for allocations that
7212 * cannot be reclaimed or migrated.
7213 */
7214 static int __init cmdline_parse_kernelcore(char *p)
7215 {
7216 /* parse kernelcore=mirror */
7217 if (parse_option_str(p, "mirror")) {
7218 mirrored_kernelcore = true;
7219 return 0;
7220 }
7221
7222 return cmdline_parse_core(p, &required_kernelcore,
7223 &required_kernelcore_percent);
7224 }
7225
7226 /*
7227 * movablecore=size sets the amount of memory for use for allocations that
7228 * can be reclaimed or migrated.
7229 */
7230 static int __init cmdline_parse_movablecore(char *p)
7231 {
7232 return cmdline_parse_core(p, &required_movablecore,
7233 &required_movablecore_percent);
7234 }
7235
7236 early_param("kernelcore", cmdline_parse_kernelcore);
7237 early_param("movablecore", cmdline_parse_movablecore);
7238
7239 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
7240
7241 void adjust_managed_page_count(struct page *page, long count)
7242 {
7243 atomic_long_add(count, &page_zone(page)->managed_pages);
7244 totalram_pages_add(count);
7245 #ifdef CONFIG_HIGHMEM
7246 if (PageHighMem(page))
7247 totalhigh_pages_add(count);
7248 #endif
7249 }
7250 EXPORT_SYMBOL(adjust_managed_page_count);
7251
7252 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7253 {
7254 void *pos;
7255 unsigned long pages = 0;
7256
7257 start = (void *)PAGE_ALIGN((unsigned long)start);
7258 end = (void *)((unsigned long)end & PAGE_MASK);
7259 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7260 struct page *page = virt_to_page(pos);
7261 void *direct_map_addr;
7262
7263 /*
7264 * 'direct_map_addr' might be different from 'pos'
7265 * because some architectures' virt_to_page()
7266 * work with aliases. Getting the direct map
7267 * address ensures that we get a _writeable_
7268 * alias for the memset().
7269 */
7270 direct_map_addr = page_address(page);
7271 if ((unsigned int)poison <= 0xFF)
7272 memset(direct_map_addr, poison, PAGE_SIZE);
7273
7274 free_reserved_page(page);
7275 }
7276
7277 if (pages && s)
7278 pr_info("Freeing %s memory: %ldK\n",
7279 s, pages << (PAGE_SHIFT - 10));
7280
7281 return pages;
7282 }
7283 EXPORT_SYMBOL(free_reserved_area);
7284
7285 #ifdef CONFIG_HIGHMEM
7286 void free_highmem_page(struct page *page)
7287 {
7288 __free_reserved_page(page);
7289 totalram_pages_inc();
7290 atomic_long_inc(&page_zone(page)->managed_pages);
7291 totalhigh_pages_inc();
7292 }
7293 #endif
7294
7295
7296 void __init mem_init_print_info(const char *str)
7297 {
7298 unsigned long physpages, codesize, datasize, rosize, bss_size;
7299 unsigned long init_code_size, init_data_size;
7300
7301 physpages = get_num_physpages();
7302 codesize = _etext - _stext;
7303 datasize = _edata - _sdata;
7304 rosize = __end_rodata - __start_rodata;
7305 bss_size = __bss_stop - __bss_start;
7306 init_data_size = __init_end - __init_begin;
7307 init_code_size = _einittext - _sinittext;
7308
7309 /*
7310 * Detect special cases and adjust section sizes accordingly:
7311 * 1) .init.* may be embedded into .data sections
7312 * 2) .init.text.* may be out of [__init_begin, __init_end],
7313 * please refer to arch/tile/kernel/vmlinux.lds.S.
7314 * 3) .rodata.* may be embedded into .text or .data sections.
7315 */
7316 #define adj_init_size(start, end, size, pos, adj) \
7317 do { \
7318 if (start <= pos && pos < end && size > adj) \
7319 size -= adj; \
7320 } while (0)
7321
7322 adj_init_size(__init_begin, __init_end, init_data_size,
7323 _sinittext, init_code_size);
7324 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7325 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7326 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7327 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7328
7329 #undef adj_init_size
7330
7331 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7332 #ifdef CONFIG_HIGHMEM
7333 ", %luK highmem"
7334 #endif
7335 "%s%s)\n",
7336 nr_free_pages() << (PAGE_SHIFT - 10),
7337 physpages << (PAGE_SHIFT - 10),
7338 codesize >> 10, datasize >> 10, rosize >> 10,
7339 (init_data_size + init_code_size) >> 10, bss_size >> 10,
7340 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7341 totalcma_pages << (PAGE_SHIFT - 10),
7342 #ifdef CONFIG_HIGHMEM
7343 totalhigh_pages() << (PAGE_SHIFT - 10),
7344 #endif
7345 str ? ", " : "", str ? str : "");
7346 }
7347
7348 /**
7349 * set_dma_reserve - set the specified number of pages reserved in the first zone
7350 * @new_dma_reserve: The number of pages to mark reserved
7351 *
7352 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7353 * In the DMA zone, a significant percentage may be consumed by kernel image
7354 * and other unfreeable allocations which can skew the watermarks badly. This
7355 * function may optionally be used to account for unfreeable pages in the
7356 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7357 * smaller per-cpu batchsize.
7358 */
7359 void __init set_dma_reserve(unsigned long new_dma_reserve)
7360 {
7361 dma_reserve = new_dma_reserve;
7362 }
7363
7364 void __init free_area_init(unsigned long *zones_size)
7365 {
7366 zero_resv_unavail();
7367 free_area_init_node(0, zones_size,
7368 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
7369 }
7370
7371 static int page_alloc_cpu_dead(unsigned int cpu)
7372 {
7373
7374 lru_add_drain_cpu(cpu);
7375 drain_pages(cpu);
7376
7377 /*
7378 * Spill the event counters of the dead processor
7379 * into the current processors event counters.
7380 * This artificially elevates the count of the current
7381 * processor.
7382 */
7383 vm_events_fold_cpu(cpu);
7384
7385 /*
7386 * Zero the differential counters of the dead processor
7387 * so that the vm statistics are consistent.
7388 *
7389 * This is only okay since the processor is dead and cannot
7390 * race with what we are doing.
7391 */
7392 cpu_vm_stats_fold(cpu);
7393 return 0;
7394 }
7395
7396 void __init page_alloc_init(void)
7397 {
7398 int ret;
7399
7400 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
7401 "mm/page_alloc:dead", NULL,
7402 page_alloc_cpu_dead);
7403 WARN_ON(ret < 0);
7404 }
7405
7406 /*
7407 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7408 * or min_free_kbytes changes.
7409 */
7410 static void calculate_totalreserve_pages(void)
7411 {
7412 struct pglist_data *pgdat;
7413 unsigned long reserve_pages = 0;
7414 enum zone_type i, j;
7415
7416 for_each_online_pgdat(pgdat) {
7417
7418 pgdat->totalreserve_pages = 0;
7419
7420 for (i = 0; i < MAX_NR_ZONES; i++) {
7421 struct zone *zone = pgdat->node_zones + i;
7422 long max = 0;
7423 unsigned long managed_pages = zone_managed_pages(zone);
7424
7425 /* Find valid and maximum lowmem_reserve in the zone */
7426 for (j = i; j < MAX_NR_ZONES; j++) {
7427 if (zone->lowmem_reserve[j] > max)
7428 max = zone->lowmem_reserve[j];
7429 }
7430
7431 /* we treat the high watermark as reserved pages. */
7432 max += high_wmark_pages(zone);
7433
7434 if (max > managed_pages)
7435 max = managed_pages;
7436
7437 pgdat->totalreserve_pages += max;
7438
7439 reserve_pages += max;
7440 }
7441 }
7442 totalreserve_pages = reserve_pages;
7443 }
7444
7445 /*
7446 * setup_per_zone_lowmem_reserve - called whenever
7447 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
7448 * has a correct pages reserved value, so an adequate number of
7449 * pages are left in the zone after a successful __alloc_pages().
7450 */
7451 static void setup_per_zone_lowmem_reserve(void)
7452 {
7453 struct pglist_data *pgdat;
7454 enum zone_type j, idx;
7455
7456 for_each_online_pgdat(pgdat) {
7457 for (j = 0; j < MAX_NR_ZONES; j++) {
7458 struct zone *zone = pgdat->node_zones + j;
7459 unsigned long managed_pages = zone_managed_pages(zone);
7460
7461 zone->lowmem_reserve[j] = 0;
7462
7463 idx = j;
7464 while (idx) {
7465 struct zone *lower_zone;
7466
7467 idx--;
7468 lower_zone = pgdat->node_zones + idx;
7469
7470 if (sysctl_lowmem_reserve_ratio[idx] < 1) {
7471 sysctl_lowmem_reserve_ratio[idx] = 0;
7472 lower_zone->lowmem_reserve[j] = 0;
7473 } else {
7474 lower_zone->lowmem_reserve[j] =
7475 managed_pages / sysctl_lowmem_reserve_ratio[idx];
7476 }
7477 managed_pages += zone_managed_pages(lower_zone);
7478 }
7479 }
7480 }
7481
7482 /* update totalreserve_pages */
7483 calculate_totalreserve_pages();
7484 }
7485
7486 static void __setup_per_zone_wmarks(void)
7487 {
7488 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
7489 unsigned long lowmem_pages = 0;
7490 struct zone *zone;
7491 unsigned long flags;
7492
7493 /* Calculate total number of !ZONE_HIGHMEM pages */
7494 for_each_zone(zone) {
7495 if (!is_highmem(zone))
7496 lowmem_pages += zone_managed_pages(zone);
7497 }
7498
7499 for_each_zone(zone) {
7500 u64 tmp;
7501
7502 spin_lock_irqsave(&zone->lock, flags);
7503 tmp = (u64)pages_min * zone_managed_pages(zone);
7504 do_div(tmp, lowmem_pages);
7505 if (is_highmem(zone)) {
7506 /*
7507 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7508 * need highmem pages, so cap pages_min to a small
7509 * value here.
7510 *
7511 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7512 * deltas control asynch page reclaim, and so should
7513 * not be capped for highmem.
7514 */
7515 unsigned long min_pages;
7516
7517 min_pages = zone_managed_pages(zone) / 1024;
7518 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
7519 zone->_watermark[WMARK_MIN] = min_pages;
7520 } else {
7521 /*
7522 * If it's a lowmem zone, reserve a number of pages
7523 * proportionate to the zone's size.
7524 */
7525 zone->_watermark[WMARK_MIN] = tmp;
7526 }
7527
7528 /*
7529 * Set the kswapd watermarks distance according to the
7530 * scale factor in proportion to available memory, but
7531 * ensure a minimum size on small systems.
7532 */
7533 tmp = max_t(u64, tmp >> 2,
7534 mult_frac(zone_managed_pages(zone),
7535 watermark_scale_factor, 10000));
7536
7537 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
7538 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
7539 zone->watermark_boost = 0;
7540
7541 spin_unlock_irqrestore(&zone->lock, flags);
7542 }
7543
7544 /* update totalreserve_pages */
7545 calculate_totalreserve_pages();
7546 }
7547
7548 /**
7549 * setup_per_zone_wmarks - called when min_free_kbytes changes
7550 * or when memory is hot-{added|removed}
7551 *
7552 * Ensures that the watermark[min,low,high] values for each zone are set
7553 * correctly with respect to min_free_kbytes.
7554 */
7555 void setup_per_zone_wmarks(void)
7556 {
7557 static DEFINE_SPINLOCK(lock);
7558
7559 spin_lock(&lock);
7560 __setup_per_zone_wmarks();
7561 spin_unlock(&lock);
7562 }
7563
7564 /*
7565 * Initialise min_free_kbytes.
7566 *
7567 * For small machines we want it small (128k min). For large machines
7568 * we want it large (64MB max). But it is not linear, because network
7569 * bandwidth does not increase linearly with machine size. We use
7570 *
7571 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7572 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
7573 *
7574 * which yields
7575 *
7576 * 16MB: 512k
7577 * 32MB: 724k
7578 * 64MB: 1024k
7579 * 128MB: 1448k
7580 * 256MB: 2048k
7581 * 512MB: 2896k
7582 * 1024MB: 4096k
7583 * 2048MB: 5792k
7584 * 4096MB: 8192k
7585 * 8192MB: 11584k
7586 * 16384MB: 16384k
7587 */
7588 int __meminit init_per_zone_wmark_min(void)
7589 {
7590 unsigned long lowmem_kbytes;
7591 int new_min_free_kbytes;
7592
7593 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
7594 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
7595
7596 if (new_min_free_kbytes > user_min_free_kbytes) {
7597 min_free_kbytes = new_min_free_kbytes;
7598 if (min_free_kbytes < 128)
7599 min_free_kbytes = 128;
7600 if (min_free_kbytes > 65536)
7601 min_free_kbytes = 65536;
7602 } else {
7603 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7604 new_min_free_kbytes, user_min_free_kbytes);
7605 }
7606 setup_per_zone_wmarks();
7607 refresh_zone_stat_thresholds();
7608 setup_per_zone_lowmem_reserve();
7609
7610 #ifdef CONFIG_NUMA
7611 setup_min_unmapped_ratio();
7612 setup_min_slab_ratio();
7613 #endif
7614
7615 return 0;
7616 }
7617 core_initcall(init_per_zone_wmark_min)
7618
7619 /*
7620 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7621 * that we can call two helper functions whenever min_free_kbytes
7622 * changes.
7623 */
7624 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
7625 void __user *buffer, size_t *length, loff_t *ppos)
7626 {
7627 int rc;
7628
7629 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7630 if (rc)
7631 return rc;
7632
7633 if (write) {
7634 user_min_free_kbytes = min_free_kbytes;
7635 setup_per_zone_wmarks();
7636 }
7637 return 0;
7638 }
7639
7640 int watermark_boost_factor_sysctl_handler(struct ctl_table *table, int write,
7641 void __user *buffer, size_t *length, loff_t *ppos)
7642 {
7643 int rc;
7644
7645 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7646 if (rc)
7647 return rc;
7648
7649 return 0;
7650 }
7651
7652 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
7653 void __user *buffer, size_t *length, loff_t *ppos)
7654 {
7655 int rc;
7656
7657 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7658 if (rc)
7659 return rc;
7660
7661 if (write)
7662 setup_per_zone_wmarks();
7663
7664 return 0;
7665 }
7666
7667 #ifdef CONFIG_NUMA
7668 static void setup_min_unmapped_ratio(void)
7669 {
7670 pg_data_t *pgdat;
7671 struct zone *zone;
7672
7673 for_each_online_pgdat(pgdat)
7674 pgdat->min_unmapped_pages = 0;
7675
7676 for_each_zone(zone)
7677 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
7678 sysctl_min_unmapped_ratio) / 100;
7679 }
7680
7681
7682 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
7683 void __user *buffer, size_t *length, loff_t *ppos)
7684 {
7685 int rc;
7686
7687 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7688 if (rc)
7689 return rc;
7690
7691 setup_min_unmapped_ratio();
7692
7693 return 0;
7694 }
7695
7696 static void setup_min_slab_ratio(void)
7697 {
7698 pg_data_t *pgdat;
7699 struct zone *zone;
7700
7701 for_each_online_pgdat(pgdat)
7702 pgdat->min_slab_pages = 0;
7703
7704 for_each_zone(zone)
7705 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
7706 sysctl_min_slab_ratio) / 100;
7707 }
7708
7709 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
7710 void __user *buffer, size_t *length, loff_t *ppos)
7711 {
7712 int rc;
7713
7714 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7715 if (rc)
7716 return rc;
7717
7718 setup_min_slab_ratio();
7719
7720 return 0;
7721 }
7722 #endif
7723
7724 /*
7725 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
7726 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
7727 * whenever sysctl_lowmem_reserve_ratio changes.
7728 *
7729 * The reserve ratio obviously has absolutely no relation with the
7730 * minimum watermarks. The lowmem reserve ratio can only make sense
7731 * if in function of the boot time zone sizes.
7732 */
7733 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
7734 void __user *buffer, size_t *length, loff_t *ppos)
7735 {
7736 proc_dointvec_minmax(table, write, buffer, length, ppos);
7737 setup_per_zone_lowmem_reserve();
7738 return 0;
7739 }
7740
7741 /*
7742 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
7743 * cpu. It is the fraction of total pages in each zone that a hot per cpu
7744 * pagelist can have before it gets flushed back to buddy allocator.
7745 */
7746 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
7747 void __user *buffer, size_t *length, loff_t *ppos)
7748 {
7749 struct zone *zone;
7750 int old_percpu_pagelist_fraction;
7751 int ret;
7752
7753 mutex_lock(&pcp_batch_high_lock);
7754 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
7755
7756 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
7757 if (!write || ret < 0)
7758 goto out;
7759
7760 /* Sanity checking to avoid pcp imbalance */
7761 if (percpu_pagelist_fraction &&
7762 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
7763 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
7764 ret = -EINVAL;
7765 goto out;
7766 }
7767
7768 /* No change? */
7769 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
7770 goto out;
7771
7772 for_each_populated_zone(zone) {
7773 unsigned int cpu;
7774
7775 for_each_possible_cpu(cpu)
7776 pageset_set_high_and_batch(zone,
7777 per_cpu_ptr(zone->pageset, cpu));
7778 }
7779 out:
7780 mutex_unlock(&pcp_batch_high_lock);
7781 return ret;
7782 }
7783
7784 #ifdef CONFIG_NUMA
7785 int hashdist = HASHDIST_DEFAULT;
7786
7787 static int __init set_hashdist(char *str)
7788 {
7789 if (!str)
7790 return 0;
7791 hashdist = simple_strtoul(str, &str, 0);
7792 return 1;
7793 }
7794 __setup("hashdist=", set_hashdist);
7795 #endif
7796
7797 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
7798 /*
7799 * Returns the number of pages that arch has reserved but
7800 * is not known to alloc_large_system_hash().
7801 */
7802 static unsigned long __init arch_reserved_kernel_pages(void)
7803 {
7804 return 0;
7805 }
7806 #endif
7807
7808 /*
7809 * Adaptive scale is meant to reduce sizes of hash tables on large memory
7810 * machines. As memory size is increased the scale is also increased but at
7811 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
7812 * quadruples the scale is increased by one, which means the size of hash table
7813 * only doubles, instead of quadrupling as well.
7814 * Because 32-bit systems cannot have large physical memory, where this scaling
7815 * makes sense, it is disabled on such platforms.
7816 */
7817 #if __BITS_PER_LONG > 32
7818 #define ADAPT_SCALE_BASE (64ul << 30)
7819 #define ADAPT_SCALE_SHIFT 2
7820 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
7821 #endif
7822
7823 /*
7824 * allocate a large system hash table from bootmem
7825 * - it is assumed that the hash table must contain an exact power-of-2
7826 * quantity of entries
7827 * - limit is the number of hash buckets, not the total allocation size
7828 */
7829 void *__init alloc_large_system_hash(const char *tablename,
7830 unsigned long bucketsize,
7831 unsigned long numentries,
7832 int scale,
7833 int flags,
7834 unsigned int *_hash_shift,
7835 unsigned int *_hash_mask,
7836 unsigned long low_limit,
7837 unsigned long high_limit)
7838 {
7839 unsigned long long max = high_limit;
7840 unsigned long log2qty, size;
7841 void *table = NULL;
7842 gfp_t gfp_flags;
7843
7844 /* allow the kernel cmdline to have a say */
7845 if (!numentries) {
7846 /* round applicable memory size up to nearest megabyte */
7847 numentries = nr_kernel_pages;
7848 numentries -= arch_reserved_kernel_pages();
7849
7850 /* It isn't necessary when PAGE_SIZE >= 1MB */
7851 if (PAGE_SHIFT < 20)
7852 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
7853
7854 #if __BITS_PER_LONG > 32
7855 if (!high_limit) {
7856 unsigned long adapt;
7857
7858 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
7859 adapt <<= ADAPT_SCALE_SHIFT)
7860 scale++;
7861 }
7862 #endif
7863
7864 /* limit to 1 bucket per 2^scale bytes of low memory */
7865 if (scale > PAGE_SHIFT)
7866 numentries >>= (scale - PAGE_SHIFT);
7867 else
7868 numentries <<= (PAGE_SHIFT - scale);
7869
7870 /* Make sure we've got at least a 0-order allocation.. */
7871 if (unlikely(flags & HASH_SMALL)) {
7872 /* Makes no sense without HASH_EARLY */
7873 WARN_ON(!(flags & HASH_EARLY));
7874 if (!(numentries >> *_hash_shift)) {
7875 numentries = 1UL << *_hash_shift;
7876 BUG_ON(!numentries);
7877 }
7878 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
7879 numentries = PAGE_SIZE / bucketsize;
7880 }
7881 numentries = roundup_pow_of_two(numentries);
7882
7883 /* limit allocation size to 1/16 total memory by default */
7884 if (max == 0) {
7885 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
7886 do_div(max, bucketsize);
7887 }
7888 max = min(max, 0x80000000ULL);
7889
7890 if (numentries < low_limit)
7891 numentries = low_limit;
7892 if (numentries > max)
7893 numentries = max;
7894
7895 log2qty = ilog2(numentries);
7896
7897 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
7898 do {
7899 size = bucketsize << log2qty;
7900 if (flags & HASH_EARLY) {
7901 if (flags & HASH_ZERO)
7902 table = memblock_alloc_nopanic(size,
7903 SMP_CACHE_BYTES);
7904 else
7905 table = memblock_alloc_raw(size,
7906 SMP_CACHE_BYTES);
7907 } else if (hashdist) {
7908 table = __vmalloc(size, gfp_flags, PAGE_KERNEL);
7909 } else {
7910 /*
7911 * If bucketsize is not a power-of-two, we may free
7912 * some pages at the end of hash table which
7913 * alloc_pages_exact() automatically does
7914 */
7915 if (get_order(size) < MAX_ORDER) {
7916 table = alloc_pages_exact(size, gfp_flags);
7917 kmemleak_alloc(table, size, 1, gfp_flags);
7918 }
7919 }
7920 } while (!table && size > PAGE_SIZE && --log2qty);
7921
7922 if (!table)
7923 panic("Failed to allocate %s hash table\n", tablename);
7924
7925 pr_info("%s hash table entries: %ld (order: %d, %lu bytes)\n",
7926 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size);
7927
7928 if (_hash_shift)
7929 *_hash_shift = log2qty;
7930 if (_hash_mask)
7931 *_hash_mask = (1 << log2qty) - 1;
7932
7933 return table;
7934 }
7935
7936 /*
7937 * This function checks whether pageblock includes unmovable pages or not.
7938 * If @count is not zero, it is okay to include less @count unmovable pages
7939 *
7940 * PageLRU check without isolation or lru_lock could race so that
7941 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
7942 * check without lock_page also may miss some movable non-lru pages at
7943 * race condition. So you can't expect this function should be exact.
7944 */
7945 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
7946 int migratetype, int flags)
7947 {
7948 unsigned long found;
7949 unsigned long iter = 0;
7950 unsigned long pfn = page_to_pfn(page);
7951 const char *reason = "unmovable page";
7952
7953 /*
7954 * TODO we could make this much more efficient by not checking every
7955 * page in the range if we know all of them are in MOVABLE_ZONE and
7956 * that the movable zone guarantees that pages are migratable but
7957 * the later is not the case right now unfortunatelly. E.g. movablecore
7958 * can still lead to having bootmem allocations in zone_movable.
7959 */
7960
7961 if (is_migrate_cma_page(page)) {
7962 /*
7963 * CMA allocations (alloc_contig_range) really need to mark
7964 * isolate CMA pageblocks even when they are not movable in fact
7965 * so consider them movable here.
7966 */
7967 if (is_migrate_cma(migratetype))
7968 return false;
7969
7970 reason = "CMA page";
7971 goto unmovable;
7972 }
7973
7974 for (found = 0; iter < pageblock_nr_pages; iter++) {
7975 unsigned long check = pfn + iter;
7976
7977 if (!pfn_valid_within(check))
7978 continue;
7979
7980 page = pfn_to_page(check);
7981
7982 if (PageReserved(page))
7983 goto unmovable;
7984
7985 /*
7986 * If the zone is movable and we have ruled out all reserved
7987 * pages then it should be reasonably safe to assume the rest
7988 * is movable.
7989 */
7990 if (zone_idx(zone) == ZONE_MOVABLE)
7991 continue;
7992
7993 /*
7994 * Hugepages are not in LRU lists, but they're movable.
7995 * We need not scan over tail pages bacause we don't
7996 * handle each tail page individually in migration.
7997 */
7998 if (PageHuge(page)) {
7999 struct page *head = compound_head(page);
8000 unsigned int skip_pages;
8001
8002 if (!hugepage_migration_supported(page_hstate(head)))
8003 goto unmovable;
8004
8005 skip_pages = (1 << compound_order(head)) - (page - head);
8006 iter += skip_pages - 1;
8007 continue;
8008 }
8009
8010 /*
8011 * We can't use page_count without pin a page
8012 * because another CPU can free compound page.
8013 * This check already skips compound tails of THP
8014 * because their page->_refcount is zero at all time.
8015 */
8016 if (!page_ref_count(page)) {
8017 if (PageBuddy(page))
8018 iter += (1 << page_order(page)) - 1;
8019 continue;
8020 }
8021
8022 /*
8023 * The HWPoisoned page may be not in buddy system, and
8024 * page_count() is not 0.
8025 */
8026 if ((flags & SKIP_HWPOISON) && PageHWPoison(page))
8027 continue;
8028
8029 if (__PageMovable(page))
8030 continue;
8031
8032 if (!PageLRU(page))
8033 found++;
8034 /*
8035 * If there are RECLAIMABLE pages, we need to check
8036 * it. But now, memory offline itself doesn't call
8037 * shrink_node_slabs() and it still to be fixed.
8038 */
8039 /*
8040 * If the page is not RAM, page_count()should be 0.
8041 * we don't need more check. This is an _used_ not-movable page.
8042 *
8043 * The problematic thing here is PG_reserved pages. PG_reserved
8044 * is set to both of a memory hole page and a _used_ kernel
8045 * page at boot.
8046 */
8047 if (found > count)
8048 goto unmovable;
8049 }
8050 return false;
8051 unmovable:
8052 WARN_ON_ONCE(zone_idx(zone) == ZONE_MOVABLE);
8053 if (flags & REPORT_FAILURE)
8054 dump_page(pfn_to_page(pfn + iter), reason);
8055 return true;
8056 }
8057
8058 #if (defined(CONFIG_MEMORY_ISOLATION) && defined(CONFIG_COMPACTION)) || defined(CONFIG_CMA)
8059
8060 static unsigned long pfn_max_align_down(unsigned long pfn)
8061 {
8062 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8063 pageblock_nr_pages) - 1);
8064 }
8065
8066 static unsigned long pfn_max_align_up(unsigned long pfn)
8067 {
8068 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8069 pageblock_nr_pages));
8070 }
8071
8072 /* [start, end) must belong to a single zone. */
8073 static int __alloc_contig_migrate_range(struct compact_control *cc,
8074 unsigned long start, unsigned long end)
8075 {
8076 /* This function is based on compact_zone() from compaction.c. */
8077 unsigned long nr_reclaimed;
8078 unsigned long pfn = start;
8079 unsigned int tries = 0;
8080 int ret = 0;
8081
8082 migrate_prep();
8083
8084 while (pfn < end || !list_empty(&cc->migratepages)) {
8085 if (fatal_signal_pending(current)) {
8086 ret = -EINTR;
8087 break;
8088 }
8089
8090 if (list_empty(&cc->migratepages)) {
8091 cc->nr_migratepages = 0;
8092 pfn = isolate_migratepages_range(cc, pfn, end);
8093 if (!pfn) {
8094 ret = -EINTR;
8095 break;
8096 }
8097 tries = 0;
8098 } else if (++tries == 5) {
8099 ret = ret < 0 ? ret : -EBUSY;
8100 break;
8101 }
8102
8103 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8104 &cc->migratepages);
8105 cc->nr_migratepages -= nr_reclaimed;
8106
8107 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
8108 NULL, 0, cc->mode, MR_CONTIG_RANGE);
8109 }
8110 if (ret < 0) {
8111 putback_movable_pages(&cc->migratepages);
8112 return ret;
8113 }
8114 return 0;
8115 }
8116
8117 /**
8118 * alloc_contig_range() -- tries to allocate given range of pages
8119 * @start: start PFN to allocate
8120 * @end: one-past-the-last PFN to allocate
8121 * @migratetype: migratetype of the underlaying pageblocks (either
8122 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8123 * in range must have the same migratetype and it must
8124 * be either of the two.
8125 * @gfp_mask: GFP mask to use during compaction
8126 *
8127 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8128 * aligned. The PFN range must belong to a single zone.
8129 *
8130 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8131 * pageblocks in the range. Once isolated, the pageblocks should not
8132 * be modified by others.
8133 *
8134 * Returns zero on success or negative error code. On success all
8135 * pages which PFN is in [start, end) are allocated for the caller and
8136 * need to be freed with free_contig_range().
8137 */
8138 int alloc_contig_range(unsigned long start, unsigned long end,
8139 unsigned migratetype, gfp_t gfp_mask)
8140 {
8141 unsigned long outer_start, outer_end;
8142 unsigned int order;
8143 int ret = 0;
8144
8145 struct compact_control cc = {
8146 .nr_migratepages = 0,
8147 .order = -1,
8148 .zone = page_zone(pfn_to_page(start)),
8149 .mode = MIGRATE_SYNC,
8150 .ignore_skip_hint = true,
8151 .no_set_skip_hint = true,
8152 .gfp_mask = current_gfp_context(gfp_mask),
8153 };
8154 INIT_LIST_HEAD(&cc.migratepages);
8155
8156 /*
8157 * What we do here is we mark all pageblocks in range as
8158 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8159 * have different sizes, and due to the way page allocator
8160 * work, we align the range to biggest of the two pages so
8161 * that page allocator won't try to merge buddies from
8162 * different pageblocks and change MIGRATE_ISOLATE to some
8163 * other migration type.
8164 *
8165 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8166 * migrate the pages from an unaligned range (ie. pages that
8167 * we are interested in). This will put all the pages in
8168 * range back to page allocator as MIGRATE_ISOLATE.
8169 *
8170 * When this is done, we take the pages in range from page
8171 * allocator removing them from the buddy system. This way
8172 * page allocator will never consider using them.
8173 *
8174 * This lets us mark the pageblocks back as
8175 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8176 * aligned range but not in the unaligned, original range are
8177 * put back to page allocator so that buddy can use them.
8178 */
8179
8180 ret = start_isolate_page_range(pfn_max_align_down(start),
8181 pfn_max_align_up(end), migratetype, 0);
8182 if (ret < 0)
8183 return ret;
8184
8185 /*
8186 * In case of -EBUSY, we'd like to know which page causes problem.
8187 * So, just fall through. test_pages_isolated() has a tracepoint
8188 * which will report the busy page.
8189 *
8190 * It is possible that busy pages could become available before
8191 * the call to test_pages_isolated, and the range will actually be
8192 * allocated. So, if we fall through be sure to clear ret so that
8193 * -EBUSY is not accidentally used or returned to caller.
8194 */
8195 ret = __alloc_contig_migrate_range(&cc, start, end);
8196 if (ret && ret != -EBUSY)
8197 goto done;
8198 ret =0;
8199
8200 /*
8201 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8202 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8203 * more, all pages in [start, end) are free in page allocator.
8204 * What we are going to do is to allocate all pages from
8205 * [start, end) (that is remove them from page allocator).
8206 *
8207 * The only problem is that pages at the beginning and at the
8208 * end of interesting range may be not aligned with pages that
8209 * page allocator holds, ie. they can be part of higher order
8210 * pages. Because of this, we reserve the bigger range and
8211 * once this is done free the pages we are not interested in.
8212 *
8213 * We don't have to hold zone->lock here because the pages are
8214 * isolated thus they won't get removed from buddy.
8215 */
8216
8217 lru_add_drain_all();
8218 drain_all_pages(cc.zone);
8219
8220 order = 0;
8221 outer_start = start;
8222 while (!PageBuddy(pfn_to_page(outer_start))) {
8223 if (++order >= MAX_ORDER) {
8224 outer_start = start;
8225 break;
8226 }
8227 outer_start &= ~0UL << order;
8228 }
8229
8230 if (outer_start != start) {
8231 order = page_order(pfn_to_page(outer_start));
8232
8233 /*
8234 * outer_start page could be small order buddy page and
8235 * it doesn't include start page. Adjust outer_start
8236 * in this case to report failed page properly
8237 * on tracepoint in test_pages_isolated()
8238 */
8239 if (outer_start + (1UL << order) <= start)
8240 outer_start = start;
8241 }
8242
8243 /* Make sure the range is really isolated. */
8244 if (test_pages_isolated(outer_start, end, false)) {
8245 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8246 __func__, outer_start, end);
8247 ret = -EBUSY;
8248 goto done;
8249 }
8250
8251 /* Grab isolated pages from freelists. */
8252 outer_end = isolate_freepages_range(&cc, outer_start, end);
8253 if (!outer_end) {
8254 ret = -EBUSY;
8255 goto done;
8256 }
8257
8258 /* Free head and tail (if any) */
8259 if (start != outer_start)
8260 free_contig_range(outer_start, start - outer_start);
8261 if (end != outer_end)
8262 free_contig_range(end, outer_end - end);
8263
8264 done:
8265 undo_isolate_page_range(pfn_max_align_down(start),
8266 pfn_max_align_up(end), migratetype);
8267 return ret;
8268 }
8269
8270 void free_contig_range(unsigned long pfn, unsigned nr_pages)
8271 {
8272 unsigned int count = 0;
8273
8274 for (; nr_pages--; pfn++) {
8275 struct page *page = pfn_to_page(pfn);
8276
8277 count += page_count(page) != 1;
8278 __free_page(page);
8279 }
8280 WARN(count != 0, "%d pages are still in use!\n", count);
8281 }
8282 #endif
8283
8284 #ifdef CONFIG_MEMORY_HOTPLUG
8285 /*
8286 * The zone indicated has a new number of managed_pages; batch sizes and percpu
8287 * page high values need to be recalulated.
8288 */
8289 void __meminit zone_pcp_update(struct zone *zone)
8290 {
8291 unsigned cpu;
8292 mutex_lock(&pcp_batch_high_lock);
8293 for_each_possible_cpu(cpu)
8294 pageset_set_high_and_batch(zone,
8295 per_cpu_ptr(zone->pageset, cpu));
8296 mutex_unlock(&pcp_batch_high_lock);
8297 }
8298 #endif
8299
8300 void zone_pcp_reset(struct zone *zone)
8301 {
8302 unsigned long flags;
8303 int cpu;
8304 struct per_cpu_pageset *pset;
8305
8306 /* avoid races with drain_pages() */
8307 local_irq_save(flags);
8308 if (zone->pageset != &boot_pageset) {
8309 for_each_online_cpu(cpu) {
8310 pset = per_cpu_ptr(zone->pageset, cpu);
8311 drain_zonestat(zone, pset);
8312 }
8313 free_percpu(zone->pageset);
8314 zone->pageset = &boot_pageset;
8315 }
8316 local_irq_restore(flags);
8317 }
8318
8319 #ifdef CONFIG_MEMORY_HOTREMOVE
8320 /*
8321 * All pages in the range must be in a single zone and isolated
8322 * before calling this.
8323 */
8324 void
8325 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
8326 {
8327 struct page *page;
8328 struct zone *zone;
8329 unsigned int order, i;
8330 unsigned long pfn;
8331 unsigned long flags;
8332 /* find the first valid pfn */
8333 for (pfn = start_pfn; pfn < end_pfn; pfn++)
8334 if (pfn_valid(pfn))
8335 break;
8336 if (pfn == end_pfn)
8337 return;
8338 offline_mem_sections(pfn, end_pfn);
8339 zone = page_zone(pfn_to_page(pfn));
8340 spin_lock_irqsave(&zone->lock, flags);
8341 pfn = start_pfn;
8342 while (pfn < end_pfn) {
8343 if (!pfn_valid(pfn)) {
8344 pfn++;
8345 continue;
8346 }
8347 page = pfn_to_page(pfn);
8348 /*
8349 * The HWPoisoned page may be not in buddy system, and
8350 * page_count() is not 0.
8351 */
8352 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
8353 pfn++;
8354 SetPageReserved(page);
8355 continue;
8356 }
8357
8358 BUG_ON(page_count(page));
8359 BUG_ON(!PageBuddy(page));
8360 order = page_order(page);
8361 #ifdef CONFIG_DEBUG_VM
8362 pr_info("remove from free list %lx %d %lx\n",
8363 pfn, 1 << order, end_pfn);
8364 #endif
8365 list_del(&page->lru);
8366 rmv_page_order(page);
8367 zone->free_area[order].nr_free--;
8368 for (i = 0; i < (1 << order); i++)
8369 SetPageReserved((page+i));
8370 pfn += (1 << order);
8371 }
8372 spin_unlock_irqrestore(&zone->lock, flags);
8373 }
8374 #endif
8375
8376 bool is_free_buddy_page(struct page *page)
8377 {
8378 struct zone *zone = page_zone(page);
8379 unsigned long pfn = page_to_pfn(page);
8380 unsigned long flags;
8381 unsigned int order;
8382
8383 spin_lock_irqsave(&zone->lock, flags);
8384 for (order = 0; order < MAX_ORDER; order++) {
8385 struct page *page_head = page - (pfn & ((1 << order) - 1));
8386
8387 if (PageBuddy(page_head) && page_order(page_head) >= order)
8388 break;
8389 }
8390 spin_unlock_irqrestore(&zone->lock, flags);
8391
8392 return order < MAX_ORDER;
8393 }
8394
8395 #ifdef CONFIG_MEMORY_FAILURE
8396 /*
8397 * Set PG_hwpoison flag if a given page is confirmed to be a free page. This
8398 * test is performed under the zone lock to prevent a race against page
8399 * allocation.
8400 */
8401 bool set_hwpoison_free_buddy_page(struct page *page)
8402 {
8403 struct zone *zone = page_zone(page);
8404 unsigned long pfn = page_to_pfn(page);
8405 unsigned long flags;
8406 unsigned int order;
8407 bool hwpoisoned = false;
8408
8409 spin_lock_irqsave(&zone->lock, flags);
8410 for (order = 0; order < MAX_ORDER; order++) {
8411 struct page *page_head = page - (pfn & ((1 << order) - 1));
8412
8413 if (PageBuddy(page_head) && page_order(page_head) >= order) {
8414 if (!TestSetPageHWPoison(page))
8415 hwpoisoned = true;
8416 break;
8417 }
8418 }
8419 spin_unlock_irqrestore(&zone->lock, flags);
8420
8421 return hwpoisoned;
8422 }
8423 #endif