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