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