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