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