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