Merge tag 'v3.10.57' into update
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / mm / page_alloc.c
CommitLineData
1da177e4
LT
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
1da177e4
LT
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>
10ed273f 22#include <linux/jiffies.h>
1da177e4 23#include <linux/bootmem.h>
edbe7d23 24#include <linux/memblock.h>
1da177e4 25#include <linux/compiler.h>
9f158333 26#include <linux/kernel.h>
b1eeab67 27#include <linux/kmemcheck.h>
1da177e4
LT
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>
a238ab5b 33#include <linux/ratelimit.h>
5a3135c2 34#include <linux/oom.h>
1da177e4
LT
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>
bdc8cb98 40#include <linux/memory_hotplug.h>
1da177e4
LT
41#include <linux/nodemask.h>
42#include <linux/vmalloc.h>
a6cccdc3 43#include <linux/vmstat.h>
4be38e35 44#include <linux/mempolicy.h>
6811378e 45#include <linux/stop_machine.h>
c713216d
MG
46#include <linux/sort.h>
47#include <linux/pfn.h>
3fcfab16 48#include <linux/backing-dev.h>
933e312e 49#include <linux/fault-inject.h>
a5d76b54 50#include <linux/page-isolation.h>
52d4b9ac 51#include <linux/page_cgroup.h>
3ac7fe5a 52#include <linux/debugobjects.h>
dbb1f81c 53#include <linux/kmemleak.h>
56de7263 54#include <linux/compaction.h>
0d3d062a 55#include <trace/events/kmem.h>
718a3821 56#include <linux/ftrace_event.h>
f212ad7c 57#include <linux/memcontrol.h>
268bb0ce 58#include <linux/prefetch.h>
041d3a8c 59#include <linux/migrate.h>
c0a32fc5 60#include <linux/page-debug-flags.h>
949f7ec5 61#include <linux/hugetlb.h>
8bd75c77 62#include <linux/sched/rt.h>
1da177e4
LT
63
64#include <asm/tlbflush.h>
ac924c60 65#include <asm/div64.h>
1da177e4
LT
66#include "internal.h"
67
72812019
LS
68#ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
69DEFINE_PER_CPU(int, numa_node);
70EXPORT_PER_CPU_SYMBOL(numa_node);
71#endif
72
7aac7898
LS
73#ifdef CONFIG_HAVE_MEMORYLESS_NODES
74/*
75 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
76 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
77 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
78 * defined in <linux/topology.h>.
79 */
80DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
81EXPORT_PER_CPU_SYMBOL(_numa_mem_);
82#endif
83
1da177e4 84/*
13808910 85 * Array of node states.
1da177e4 86 */
13808910
CL
87nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
88 [N_POSSIBLE] = NODE_MASK_ALL,
89 [N_ONLINE] = { { [0] = 1UL } },
90#ifndef CONFIG_NUMA
91 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
92#ifdef CONFIG_HIGHMEM
93 [N_HIGH_MEMORY] = { { [0] = 1UL } },
20b2f52b
LJ
94#endif
95#ifdef CONFIG_MOVABLE_NODE
96 [N_MEMORY] = { { [0] = 1UL } },
13808910
CL
97#endif
98 [N_CPU] = { { [0] = 1UL } },
99#endif /* NUMA */
100};
101EXPORT_SYMBOL(node_states);
102
6c231b7b 103unsigned long totalram_pages __read_mostly;
cb45b0e9 104unsigned long totalreserve_pages __read_mostly;
ab8fabd4
JW
105/*
106 * When calculating the number of globally allowed dirty pages, there
107 * is a certain number of per-zone reserves that should not be
108 * considered dirtyable memory. This is the sum of those reserves
109 * over all existing zones that contribute dirtyable memory.
110 */
111unsigned long dirty_balance_reserve __read_mostly;
112
1b76b02f 113int percpu_pagelist_fraction;
dcce284a 114gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
1da177e4 115
452aa699
RW
116#ifdef CONFIG_PM_SLEEP
117/*
118 * The following functions are used by the suspend/hibernate code to temporarily
119 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
120 * while devices are suspended. To avoid races with the suspend/hibernate code,
121 * they should always be called with pm_mutex held (gfp_allowed_mask also should
122 * only be modified with pm_mutex held, unless the suspend/hibernate code is
123 * guaranteed not to run in parallel with that modification).
124 */
c9e664f1
RW
125
126static gfp_t saved_gfp_mask;
127
128void pm_restore_gfp_mask(void)
452aa699
RW
129{
130 WARN_ON(!mutex_is_locked(&pm_mutex));
c9e664f1
RW
131 if (saved_gfp_mask) {
132 gfp_allowed_mask = saved_gfp_mask;
133 saved_gfp_mask = 0;
134 }
452aa699 135}
6fa3eb70 136EXPORT_SYMBOL_GPL(pm_restore_gfp_mask);
452aa699 137
c9e664f1 138void pm_restrict_gfp_mask(void)
452aa699 139{
452aa699 140 WARN_ON(!mutex_is_locked(&pm_mutex));
c9e664f1
RW
141 WARN_ON(saved_gfp_mask);
142 saved_gfp_mask = gfp_allowed_mask;
143 gfp_allowed_mask &= ~GFP_IOFS;
452aa699 144}
6fa3eb70 145EXPORT_SYMBOL_GPL(pm_restrict_gfp_mask);
f90ac398
MG
146
147bool pm_suspended_storage(void)
148{
149 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
150 return false;
151 return true;
152}
452aa699
RW
153#endif /* CONFIG_PM_SLEEP */
154
d9c23400
MG
155#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
156int pageblock_order __read_mostly;
157#endif
158
d98c7a09 159static void __free_pages_ok(struct page *page, unsigned int order);
a226f6c8 160
1da177e4
LT
161/*
162 * results with 256, 32 in the lowmem_reserve sysctl:
163 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
164 * 1G machine -> (16M dma, 784M normal, 224M high)
165 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
166 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
167 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
a2f1b424
AK
168 *
169 * TBD: should special case ZONE_DMA32 machines here - in those we normally
170 * don't need any ZONE_NORMAL reservation
1da177e4 171 */
2f1b6248 172int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
4b51d669 173#ifdef CONFIG_ZONE_DMA
2f1b6248 174 256,
4b51d669 175#endif
fb0e7942 176#ifdef CONFIG_ZONE_DMA32
2f1b6248 177 256,
fb0e7942 178#endif
e53ef38d 179#ifdef CONFIG_HIGHMEM
2a1e274a 180 32,
e53ef38d 181#endif
2a1e274a 182 32,
2f1b6248 183};
1da177e4
LT
184
185EXPORT_SYMBOL(totalram_pages);
1da177e4 186
15ad7cdc 187static char * const zone_names[MAX_NR_ZONES] = {
4b51d669 188#ifdef CONFIG_ZONE_DMA
2f1b6248 189 "DMA",
4b51d669 190#endif
fb0e7942 191#ifdef CONFIG_ZONE_DMA32
2f1b6248 192 "DMA32",
fb0e7942 193#endif
2f1b6248 194 "Normal",
e53ef38d 195#ifdef CONFIG_HIGHMEM
2a1e274a 196 "HighMem",
e53ef38d 197#endif
2a1e274a 198 "Movable",
2f1b6248
CL
199};
200
6fa3eb70
S
201/*
202 * Try to keep at least this much lowmem free. Do not allow normal
203 * allocations below this point, only high priority ones. Automatically
204 * tuned according to the amount of memory in the system.
205 */
1da177e4 206int min_free_kbytes = 1024;
6fa3eb70
S
207int min_free_order_shift = 1;
208
209/*
210 * Extra memory for the system to try freeing. Used to temporarily
211 * free memory, to make space for new workloads. Anyone can allocate
212 * down to the min watermarks controlled by min_free_kbytes above.
213 */
214int extra_free_kbytes = 0;
1da177e4 215
2c85f51d
JB
216static unsigned long __meminitdata nr_kernel_pages;
217static unsigned long __meminitdata nr_all_pages;
a3142c8e 218static unsigned long __meminitdata dma_reserve;
1da177e4 219
0ee332c1
TH
220#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
221static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
222static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
223static unsigned long __initdata required_kernelcore;
224static unsigned long __initdata required_movablecore;
225static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
226
227/* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
228int movable_zone;
229EXPORT_SYMBOL(movable_zone);
230#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 231
418508c1
MS
232#if MAX_NUMNODES > 1
233int nr_node_ids __read_mostly = MAX_NUMNODES;
62bc62a8 234int nr_online_nodes __read_mostly = 1;
418508c1 235EXPORT_SYMBOL(nr_node_ids);
62bc62a8 236EXPORT_SYMBOL(nr_online_nodes);
418508c1
MS
237#endif
238
9ef9acb0
MG
239int page_group_by_mobility_disabled __read_mostly;
240
ee6f509c 241void set_pageblock_migratetype(struct page *page, int migratetype)
b2a0ac88 242{
49255c61
MG
243
244 if (unlikely(page_group_by_mobility_disabled))
245 migratetype = MIGRATE_UNMOVABLE;
246
b2a0ac88
MG
247 set_pageblock_flags_group(page, (unsigned long)migratetype,
248 PB_migrate, PB_migrate_end);
249}
6fa3eb70
S
250#ifdef CONFIG_MTKPASR
251void __meminit set_pageblock_mobility(struct page *page, int mobility)
252{
253 set_pageblock_migratetype(page, mobility);
254}
255#endif
b2a0ac88 256
7f33d49a
RW
257bool oom_killer_disabled __read_mostly;
258
13e7444b 259#ifdef CONFIG_DEBUG_VM
c6a57e19 260static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
1da177e4 261{
bdc8cb98
DH
262 int ret = 0;
263 unsigned seq;
264 unsigned long pfn = page_to_pfn(page);
b5e6a5a2 265 unsigned long sp, start_pfn;
c6a57e19 266
bdc8cb98
DH
267 do {
268 seq = zone_span_seqbegin(zone);
b5e6a5a2
CS
269 start_pfn = zone->zone_start_pfn;
270 sp = zone->spanned_pages;
108bcc96 271 if (!zone_spans_pfn(zone, pfn))
bdc8cb98
DH
272 ret = 1;
273 } while (zone_span_seqretry(zone, seq));
274
b5e6a5a2
CS
275 if (ret)
276 pr_err("page %lu outside zone [ %lu - %lu ]\n",
277 pfn, start_pfn, start_pfn + sp);
278
bdc8cb98 279 return ret;
c6a57e19
DH
280}
281
282static int page_is_consistent(struct zone *zone, struct page *page)
283{
14e07298 284 if (!pfn_valid_within(page_to_pfn(page)))
c6a57e19 285 return 0;
1da177e4 286 if (zone != page_zone(page))
c6a57e19
DH
287 return 0;
288
289 return 1;
290}
291/*
292 * Temporary debugging check for pages not lying within a given zone.
293 */
294static int bad_range(struct zone *zone, struct page *page)
295{
296 if (page_outside_zone_boundaries(zone, page))
1da177e4 297 return 1;
c6a57e19
DH
298 if (!page_is_consistent(zone, page))
299 return 1;
300
1da177e4
LT
301 return 0;
302}
13e7444b
NP
303#else
304static inline int bad_range(struct zone *zone, struct page *page)
305{
306 return 0;
307}
308#endif
309
224abf92 310static void bad_page(struct page *page)
1da177e4 311{
d936cf9b
HD
312 static unsigned long resume;
313 static unsigned long nr_shown;
314 static unsigned long nr_unshown;
315
2a7684a2
WF
316 /* Don't complain about poisoned pages */
317 if (PageHWPoison(page)) {
22b751c3 318 page_mapcount_reset(page); /* remove PageBuddy */
2a7684a2
WF
319 return;
320 }
321
d936cf9b
HD
322 /*
323 * Allow a burst of 60 reports, then keep quiet for that minute;
324 * or allow a steady drip of one report per second.
325 */
326 if (nr_shown == 60) {
327 if (time_before(jiffies, resume)) {
328 nr_unshown++;
329 goto out;
330 }
331 if (nr_unshown) {
1e9e6365
HD
332 printk(KERN_ALERT
333 "BUG: Bad page state: %lu messages suppressed\n",
d936cf9b
HD
334 nr_unshown);
335 nr_unshown = 0;
336 }
337 nr_shown = 0;
338 }
339 if (nr_shown++ == 0)
340 resume = jiffies + 60 * HZ;
341
1e9e6365 342 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
3dc14741 343 current->comm, page_to_pfn(page));
718a3821 344 dump_page(page);
3dc14741 345
4f31888c 346 print_modules();
1da177e4 347 dump_stack();
d936cf9b 348out:
8cc3b392 349 /* Leave bad fields for debug, except PageBuddy could make trouble */
22b751c3 350 page_mapcount_reset(page); /* remove PageBuddy */
373d4d09 351 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1da177e4
LT
352}
353
1da177e4
LT
354/*
355 * Higher-order pages are called "compound pages". They are structured thusly:
356 *
357 * The first PAGE_SIZE page is called the "head page".
358 *
359 * The remaining PAGE_SIZE pages are called "tail pages".
360 *
6416b9fa
WSH
361 * All pages have PG_compound set. All tail pages have their ->first_page
362 * pointing at the head page.
1da177e4 363 *
41d78ba5
HD
364 * The first tail page's ->lru.next holds the address of the compound page's
365 * put_page() function. Its ->lru.prev holds the order of allocation.
366 * This usage means that zero-order pages may not be compound.
1da177e4 367 */
d98c7a09
HD
368
369static void free_compound_page(struct page *page)
370{
d85f3385 371 __free_pages_ok(page, compound_order(page));
d98c7a09
HD
372}
373
01ad1c08 374void prep_compound_page(struct page *page, unsigned long order)
18229df5
AW
375{
376 int i;
377 int nr_pages = 1 << order;
378
379 set_compound_page_dtor(page, free_compound_page);
380 set_compound_order(page, order);
381 __SetPageHead(page);
382 for (i = 1; i < nr_pages; i++) {
383 struct page *p = page + i;
58a84aa9 384 set_page_count(p, 0);
18229df5 385 p->first_page = page;
def52acc
DR
386 /* Make sure p->first_page is always valid for PageTail() */
387 smp_wmb();
388 __SetPageTail(p);
18229df5
AW
389 }
390}
391
59ff4216 392/* update __split_huge_page_refcount if you change this function */
8cc3b392 393static int destroy_compound_page(struct page *page, unsigned long order)
1da177e4
LT
394{
395 int i;
396 int nr_pages = 1 << order;
8cc3b392 397 int bad = 0;
1da177e4 398
0bb2c763 399 if (unlikely(compound_order(page) != order)) {
224abf92 400 bad_page(page);
8cc3b392
HD
401 bad++;
402 }
1da177e4 403
6d777953 404 __ClearPageHead(page);
8cc3b392 405
18229df5
AW
406 for (i = 1; i < nr_pages; i++) {
407 struct page *p = page + i;
1da177e4 408
e713a21d 409 if (unlikely(!PageTail(p) || (p->first_page != page))) {
224abf92 410 bad_page(page);
8cc3b392
HD
411 bad++;
412 }
d85f3385 413 __ClearPageTail(p);
1da177e4 414 }
8cc3b392
HD
415
416 return bad;
1da177e4 417}
1da177e4 418
17cf4406
NP
419static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
420{
421 int i;
422
6626c5d5
AM
423 /*
424 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
425 * and __GFP_HIGHMEM from hard or soft interrupt context.
426 */
725d704e 427 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
17cf4406
NP
428 for (i = 0; i < (1 << order); i++)
429 clear_highpage(page + i);
430}
431
c0a32fc5
SG
432#ifdef CONFIG_DEBUG_PAGEALLOC
433unsigned int _debug_guardpage_minorder;
434
435static int __init debug_guardpage_minorder_setup(char *buf)
436{
437 unsigned long res;
438
439 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
440 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
441 return 0;
442 }
443 _debug_guardpage_minorder = res;
444 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
445 return 0;
446}
447__setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
448
449static inline void set_page_guard_flag(struct page *page)
450{
451 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
452}
453
454static inline void clear_page_guard_flag(struct page *page)
455{
456 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
457}
458#else
459static inline void set_page_guard_flag(struct page *page) { }
460static inline void clear_page_guard_flag(struct page *page) { }
461#endif
462
6aa3001b
AM
463static inline void set_page_order(struct page *page, int order)
464{
4c21e2f2 465 set_page_private(page, order);
676165a8 466 __SetPageBuddy(page);
1da177e4
LT
467}
468
469static inline void rmv_page_order(struct page *page)
470{
676165a8 471 __ClearPageBuddy(page);
4c21e2f2 472 set_page_private(page, 0);
1da177e4
LT
473}
474
475/*
476 * Locate the struct page for both the matching buddy in our
477 * pair (buddy1) and the combined O(n+1) page they form (page).
478 *
479 * 1) Any buddy B1 will have an order O twin B2 which satisfies
480 * the following equation:
481 * B2 = B1 ^ (1 << O)
482 * For example, if the starting buddy (buddy2) is #8 its order
483 * 1 buddy is #10:
484 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
485 *
486 * 2) Any buddy B will have an order O+1 parent P which
487 * satisfies the following equation:
488 * P = B & ~(1 << O)
489 *
d6e05edc 490 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
1da177e4 491 */
1da177e4 492static inline unsigned long
43506fad 493__find_buddy_index(unsigned long page_idx, unsigned int order)
1da177e4 494{
43506fad 495 return page_idx ^ (1 << order);
1da177e4
LT
496}
497
498/*
499 * This function checks whether a page is free && is the buddy
500 * we can do coalesce a page and its buddy if
13e7444b 501 * (a) the buddy is not in a hole &&
676165a8 502 * (b) the buddy is in the buddy system &&
cb2b95e1
AW
503 * (c) a page and its buddy have the same order &&
504 * (d) a page and its buddy are in the same zone.
676165a8 505 *
5f24ce5f
AA
506 * For recording whether a page is in the buddy system, we set ->_mapcount -2.
507 * Setting, clearing, and testing _mapcount -2 is serialized by zone->lock.
1da177e4 508 *
676165a8 509 * For recording page's order, we use page_private(page).
1da177e4 510 */
cb2b95e1
AW
511static inline int page_is_buddy(struct page *page, struct page *buddy,
512 int order)
1da177e4 513{
14e07298 514 if (!pfn_valid_within(page_to_pfn(buddy)))
13e7444b 515 return 0;
13e7444b 516
cb2b95e1
AW
517 if (page_zone_id(page) != page_zone_id(buddy))
518 return 0;
519
c0a32fc5
SG
520 if (page_is_guard(buddy) && page_order(buddy) == order) {
521 VM_BUG_ON(page_count(buddy) != 0);
522 return 1;
523 }
524
cb2b95e1 525 if (PageBuddy(buddy) && page_order(buddy) == order) {
a3af9c38 526 VM_BUG_ON(page_count(buddy) != 0);
6aa3001b 527 return 1;
676165a8 528 }
6aa3001b 529 return 0;
1da177e4
LT
530}
531
532/*
533 * Freeing function for a buddy system allocator.
534 *
535 * The concept of a buddy system is to maintain direct-mapped table
536 * (containing bit values) for memory blocks of various "orders".
537 * The bottom level table contains the map for the smallest allocatable
538 * units of memory (here, pages), and each level above it describes
539 * pairs of units from the levels below, hence, "buddies".
540 * At a high level, all that happens here is marking the table entry
541 * at the bottom level available, and propagating the changes upward
542 * as necessary, plus some accounting needed to play nicely with other
543 * parts of the VM system.
544 * At each level, we keep a list of pages, which are heads of continuous
5f24ce5f 545 * free pages of length of (1 << order) and marked with _mapcount -2. Page's
4c21e2f2 546 * order is recorded in page_private(page) field.
1da177e4 547 * So when we are allocating or freeing one, we can derive the state of the
5f63b720
MN
548 * other. That is, if we allocate a small block, and both were
549 * free, the remainder of the region must be split into blocks.
1da177e4 550 * If a block is freed, and its buddy is also free, then this
5f63b720 551 * triggers coalescing into a block of larger size.
1da177e4 552 *
6d49e352 553 * -- nyc
1da177e4
LT
554 */
555
48db57f8 556static inline void __free_one_page(struct page *page,
ed0ae21d
MG
557 struct zone *zone, unsigned int order,
558 int migratetype)
1da177e4
LT
559{
560 unsigned long page_idx;
6dda9d55 561 unsigned long combined_idx;
43506fad 562 unsigned long uninitialized_var(buddy_idx);
6dda9d55 563 struct page *buddy;
1da177e4 564
d29bb978
CS
565 VM_BUG_ON(!zone_is_initialized(zone));
566
224abf92 567 if (unlikely(PageCompound(page)))
8cc3b392
HD
568 if (unlikely(destroy_compound_page(page, order)))
569 return;
1da177e4 570
ed0ae21d
MG
571 VM_BUG_ON(migratetype == -1);
572
1da177e4
LT
573 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
574
f2260e6b 575 VM_BUG_ON(page_idx & ((1 << order) - 1));
725d704e 576 VM_BUG_ON(bad_range(zone, page));
1da177e4 577
1da177e4 578 while (order < MAX_ORDER-1) {
43506fad
KC
579 buddy_idx = __find_buddy_index(page_idx, order);
580 buddy = page + (buddy_idx - page_idx);
cb2b95e1 581 if (!page_is_buddy(page, buddy, order))
3c82d0ce 582 break;
c0a32fc5
SG
583 /*
584 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
585 * merge with it and move up one order.
586 */
587 if (page_is_guard(buddy)) {
588 clear_page_guard_flag(buddy);
589 set_page_private(page, 0);
d1ce749a
BZ
590 __mod_zone_freepage_state(zone, 1 << order,
591 migratetype);
c0a32fc5
SG
592 } else {
593 list_del(&buddy->lru);
594 zone->free_area[order].nr_free--;
595 rmv_page_order(buddy);
596 }
43506fad 597 combined_idx = buddy_idx & page_idx;
1da177e4
LT
598 page = page + (combined_idx - page_idx);
599 page_idx = combined_idx;
600 order++;
601 }
602 set_page_order(page, order);
6dda9d55
CZ
603
604 /*
605 * If this is not the largest possible page, check if the buddy
606 * of the next-highest order is free. If it is, it's possible
607 * that pages are being freed that will coalesce soon. In case,
608 * that is happening, add the free page to the tail of the list
609 * so it's less likely to be used soon and more likely to be merged
610 * as a higher order page
611 */
b7f50cfa 612 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
6dda9d55 613 struct page *higher_page, *higher_buddy;
43506fad
KC
614 combined_idx = buddy_idx & page_idx;
615 higher_page = page + (combined_idx - page_idx);
616 buddy_idx = __find_buddy_index(combined_idx, order + 1);
0ba8f2d5 617 higher_buddy = higher_page + (buddy_idx - combined_idx);
6dda9d55
CZ
618 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
619 list_add_tail(&page->lru,
620 &zone->free_area[order].free_list[migratetype]);
621 goto out;
622 }
623 }
624
625 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
626out:
1da177e4
LT
627 zone->free_area[order].nr_free++;
628}
629
224abf92 630static inline int free_pages_check(struct page *page)
1da177e4 631{
92be2e33
NP
632 if (unlikely(page_mapcount(page) |
633 (page->mapping != NULL) |
a3af9c38 634 (atomic_read(&page->_count) != 0) |
f212ad7c
DN
635 (page->flags & PAGE_FLAGS_CHECK_AT_FREE) |
636 (mem_cgroup_bad_page_check(page)))) {
224abf92 637 bad_page(page);
79f4b7bf 638 return 1;
8cc3b392 639 }
22b751c3 640 page_nid_reset_last(page);
79f4b7bf
HD
641 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
642 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
643 return 0;
1da177e4
LT
644}
645
646/*
5f8dcc21 647 * Frees a number of pages from the PCP lists
1da177e4 648 * Assumes all pages on list are in same zone, and of same order.
207f36ee 649 * count is the number of pages to free.
1da177e4
LT
650 *
651 * If the zone was previously in an "all pages pinned" state then look to
652 * see if this freeing clears that state.
653 *
654 * And clear the zone's pages_scanned counter, to hold off the "all pages are
655 * pinned" detection logic.
656 */
5f8dcc21
MG
657static void free_pcppages_bulk(struct zone *zone, int count,
658 struct per_cpu_pages *pcp)
1da177e4 659{
5f8dcc21 660 int migratetype = 0;
a6f9edd6 661 int batch_free = 0;
72853e29 662 int to_free = count;
5f8dcc21 663
c54ad30c 664 spin_lock(&zone->lock);
93e4a89a 665 zone->all_unreclaimable = 0;
1da177e4 666 zone->pages_scanned = 0;
f2260e6b 667
72853e29 668 while (to_free) {
48db57f8 669 struct page *page;
5f8dcc21
MG
670 struct list_head *list;
671
672 /*
a6f9edd6
MG
673 * Remove pages from lists in a round-robin fashion. A
674 * batch_free count is maintained that is incremented when an
675 * empty list is encountered. This is so more pages are freed
676 * off fuller lists instead of spinning excessively around empty
677 * lists
5f8dcc21
MG
678 */
679 do {
a6f9edd6 680 batch_free++;
5f8dcc21
MG
681 if (++migratetype == MIGRATE_PCPTYPES)
682 migratetype = 0;
683 list = &pcp->lists[migratetype];
684 } while (list_empty(list));
48db57f8 685
1d16871d
NK
686 /* This is the only non-empty list. Free them all. */
687 if (batch_free == MIGRATE_PCPTYPES)
688 batch_free = to_free;
689
a6f9edd6 690 do {
770c8aaa
BZ
691 int mt; /* migratetype of the to-be-freed page */
692
a6f9edd6
MG
693 page = list_entry(list->prev, struct page, lru);
694 /* must delete as __free_one_page list manipulates */
695 list_del(&page->lru);
b12c4ad1 696 mt = get_freepage_migratetype(page);
a7016235 697 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
770c8aaa
BZ
698 __free_one_page(page, zone, 0, mt);
699 trace_mm_page_pcpu_drain(page, 0, mt);
194159fb 700 if (likely(!is_migrate_isolate_page(page))) {
97d0da22
WC
701 __mod_zone_page_state(zone, NR_FREE_PAGES, 1);
702 if (is_migrate_cma(mt))
703 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 1);
704 }
72853e29 705 } while (--to_free && --batch_free && !list_empty(list));
1da177e4 706 }
c54ad30c 707 spin_unlock(&zone->lock);
1da177e4
LT
708}
709
ed0ae21d
MG
710static void free_one_page(struct zone *zone, struct page *page, int order,
711 int migratetype)
1da177e4 712{
006d22d9 713 spin_lock(&zone->lock);
93e4a89a 714 zone->all_unreclaimable = 0;
006d22d9 715 zone->pages_scanned = 0;
f2260e6b 716
ed0ae21d 717 __free_one_page(page, zone, order, migratetype);
194159fb 718 if (unlikely(!is_migrate_isolate(migratetype)))
d1ce749a 719 __mod_zone_freepage_state(zone, 1 << order, migratetype);
006d22d9 720 spin_unlock(&zone->lock);
48db57f8
NP
721}
722
ec95f53a 723static bool free_pages_prepare(struct page *page, unsigned int order)
48db57f8 724{
1da177e4 725 int i;
8cc3b392 726 int bad = 0;
1da177e4 727
b413d48a 728 trace_mm_page_free(page, order);
b1eeab67
VN
729 kmemcheck_free_shadow(page, order);
730
8dd60a3a
AA
731 if (PageAnon(page))
732 page->mapping = NULL;
733 for (i = 0; i < (1 << order); i++)
734 bad += free_pages_check(page + i);
8cc3b392 735 if (bad)
ec95f53a 736 return false;
689bcebf 737
3ac7fe5a 738 if (!PageHighMem(page)) {
9858db50 739 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
3ac7fe5a
TG
740 debug_check_no_obj_freed(page_address(page),
741 PAGE_SIZE << order);
742 }
dafb1367 743 arch_free_page(page, order);
48db57f8 744 kernel_map_pages(page, 1 << order, 0);
dafb1367 745
ec95f53a
KM
746 return true;
747}
748
749static void __free_pages_ok(struct page *page, unsigned int order)
750{
751 unsigned long flags;
95e34412 752 int migratetype;
ec95f53a
KM
753
754 if (!free_pages_prepare(page, order))
755 return;
756
c54ad30c 757 local_irq_save(flags);
f8891e5e 758 __count_vm_events(PGFREE, 1 << order);
95e34412
MK
759 migratetype = get_pageblock_migratetype(page);
760 set_freepage_migratetype(page, migratetype);
761 free_one_page(page_zone(page), page, order, migratetype);
c54ad30c 762 local_irq_restore(flags);
1da177e4
LT
763}
764
9feedc9d
JL
765/*
766 * Read access to zone->managed_pages is safe because it's unsigned long,
767 * but we still need to serialize writers. Currently all callers of
768 * __free_pages_bootmem() except put_page_bootmem() should only be used
769 * at boot time. So for shorter boot time, we shift the burden to
770 * put_page_bootmem() to serialize writers.
771 */
af370fb8 772void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
a226f6c8 773{
c3993076
JW
774 unsigned int nr_pages = 1 << order;
775 unsigned int loop;
a226f6c8 776
c3993076
JW
777 prefetchw(page);
778 for (loop = 0; loop < nr_pages; loop++) {
779 struct page *p = &page[loop];
780
781 if (loop + 1 < nr_pages)
782 prefetchw(p + 1);
783 __ClearPageReserved(p);
784 set_page_count(p, 0);
a226f6c8 785 }
c3993076 786
9feedc9d 787 page_zone(page)->managed_pages += 1 << order;
c3993076
JW
788 set_page_refcounted(page);
789 __free_pages(page, order);
a226f6c8
DH
790}
791
47118af0
MN
792#ifdef CONFIG_CMA
793/* Free whole pageblock and set it's migration type to MIGRATE_CMA. */
794void __init init_cma_reserved_pageblock(struct page *page)
795{
796 unsigned i = pageblock_nr_pages;
797 struct page *p = page;
798
799 do {
800 __ClearPageReserved(p);
801 set_page_count(p, 0);
802 } while (++p, --i);
803
804 set_page_refcounted(page);
805 set_pageblock_migratetype(page, MIGRATE_CMA);
806 __free_pages(page, pageblock_order);
807 totalram_pages += pageblock_nr_pages;
41a79734
MS
808#ifdef CONFIG_HIGHMEM
809 if (PageHighMem(page))
810 totalhigh_pages += pageblock_nr_pages;
811#endif
47118af0
MN
812}
813#endif
1da177e4
LT
814
815/*
816 * The order of subdivision here is critical for the IO subsystem.
817 * Please do not alter this order without good reasons and regression
818 * testing. Specifically, as large blocks of memory are subdivided,
819 * the order in which smaller blocks are delivered depends on the order
820 * they're subdivided in this function. This is the primary factor
821 * influencing the order in which pages are delivered to the IO
822 * subsystem according to empirical testing, and this is also justified
823 * by considering the behavior of a buddy system containing a single
824 * large block of memory acted on by a series of small allocations.
825 * This behavior is a critical factor in sglist merging's success.
826 *
6d49e352 827 * -- nyc
1da177e4 828 */
085cc7d5 829static inline void expand(struct zone *zone, struct page *page,
b2a0ac88
MG
830 int low, int high, struct free_area *area,
831 int migratetype)
1da177e4
LT
832{
833 unsigned long size = 1 << high;
834
835 while (high > low) {
836 area--;
837 high--;
838 size >>= 1;
725d704e 839 VM_BUG_ON(bad_range(zone, &page[size]));
c0a32fc5
SG
840
841#ifdef CONFIG_DEBUG_PAGEALLOC
842 if (high < debug_guardpage_minorder()) {
843 /*
844 * Mark as guard pages (or page), that will allow to
845 * merge back to allocator when buddy will be freed.
846 * Corresponding page table entries will not be touched,
847 * pages will stay not present in virtual address space
848 */
849 INIT_LIST_HEAD(&page[size].lru);
850 set_page_guard_flag(&page[size]);
851 set_page_private(&page[size], high);
852 /* Guard pages are not available for any usage */
d1ce749a
BZ
853 __mod_zone_freepage_state(zone, -(1 << high),
854 migratetype);
c0a32fc5
SG
855 continue;
856 }
857#endif
b2a0ac88 858 list_add(&page[size].lru, &area->free_list[migratetype]);
1da177e4
LT
859 area->nr_free++;
860 set_page_order(&page[size], high);
861 }
1da177e4
LT
862}
863
1da177e4
LT
864/*
865 * This page is about to be returned from the page allocator
866 */
2a7684a2 867static inline int check_new_page(struct page *page)
1da177e4 868{
92be2e33
NP
869 if (unlikely(page_mapcount(page) |
870 (page->mapping != NULL) |
a3af9c38 871 (atomic_read(&page->_count) != 0) |
f212ad7c
DN
872 (page->flags & PAGE_FLAGS_CHECK_AT_PREP) |
873 (mem_cgroup_bad_page_check(page)))) {
224abf92 874 bad_page(page);
689bcebf 875 return 1;
8cc3b392 876 }
2a7684a2
WF
877 return 0;
878}
879
880static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
881{
882 int i;
883
884 for (i = 0; i < (1 << order); i++) {
885 struct page *p = page + i;
886 if (unlikely(check_new_page(p)))
887 return 1;
888 }
689bcebf 889
4c21e2f2 890 set_page_private(page, 0);
7835e98b 891 set_page_refcounted(page);
cc102509
NP
892
893 arch_alloc_page(page, order);
1da177e4 894 kernel_map_pages(page, 1 << order, 1);
17cf4406
NP
895
896 if (gfp_flags & __GFP_ZERO)
897 prep_zero_page(page, order, gfp_flags);
898
899 if (order && (gfp_flags & __GFP_COMP))
900 prep_compound_page(page, order);
901
689bcebf 902 return 0;
1da177e4
LT
903}
904
56fd56b8
MG
905/*
906 * Go through the free lists for the given migratetype and remove
907 * the smallest available page from the freelists
908 */
728ec980
MG
909static inline
910struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
56fd56b8
MG
911 int migratetype)
912{
913 unsigned int current_order;
914 struct free_area * area;
915 struct page *page;
916
917 /* Find a page of the appropriate size in the preferred list */
918 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
919 area = &(zone->free_area[current_order]);
920 if (list_empty(&area->free_list[migratetype]))
921 continue;
922
923 page = list_entry(area->free_list[migratetype].next,
924 struct page, lru);
925 list_del(&page->lru);
926 rmv_page_order(page);
927 area->nr_free--;
56fd56b8
MG
928 expand(zone, page, order, current_order, area, migratetype);
929 return page;
930 }
931
932 return NULL;
933}
934
935
b2a0ac88
MG
936/*
937 * This array describes the order lists are fallen back to when
938 * the free lists for the desirable migrate type are depleted
939 */
47118af0
MN
940static int fallbacks[MIGRATE_TYPES][4] = {
941 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
942 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
6fa3eb70 943
47118af0
MN
944#ifdef CONFIG_CMA
945 [MIGRATE_MOVABLE] = { MIGRATE_CMA, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
946 [MIGRATE_CMA] = { MIGRATE_RESERVE }, /* Never used */
6fa3eb70
S
947#else // CONFIG_CMA
948
949#ifndef CONFIG_MTKPASR
47118af0 950 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
6fa3eb70
S
951#else
952 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_MTKPASR, MIGRATE_RESERVE },
953 [MIGRATE_MTKPASR] = { MIGRATE_MOVABLE, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
47118af0 954#endif
6fa3eb70
S
955
956#endif // CONFIG_CMA
957
6d4a4916 958 [MIGRATE_RESERVE] = { MIGRATE_RESERVE }, /* Never used */
194159fb 959#ifdef CONFIG_MEMORY_ISOLATION
6d4a4916 960 [MIGRATE_ISOLATE] = { MIGRATE_RESERVE }, /* Never used */
194159fb 961#endif
b2a0ac88
MG
962};
963
c361be55
MG
964/*
965 * Move the free pages in a range to the free lists of the requested type.
d9c23400 966 * Note that start_page and end_pages are not aligned on a pageblock
c361be55
MG
967 * boundary. If alignment is required, use move_freepages_block()
968 */
435b405c 969int move_freepages(struct zone *zone,
b69a7288
AB
970 struct page *start_page, struct page *end_page,
971 int migratetype)
c361be55
MG
972{
973 struct page *page;
974 unsigned long order;
d100313f 975 int pages_moved = 0;
c361be55
MG
976
977#ifndef CONFIG_HOLES_IN_ZONE
978 /*
979 * page_zone is not safe to call in this context when
980 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
981 * anyway as we check zone boundaries in move_freepages_block().
982 * Remove at a later date when no bug reports exist related to
ac0e5b7a 983 * grouping pages by mobility
c361be55
MG
984 */
985 BUG_ON(page_zone(start_page) != page_zone(end_page));
986#endif
987
988 for (page = start_page; page <= end_page;) {
344c790e
AL
989 /* Make sure we are not inadvertently changing nodes */
990 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
991
c361be55
MG
992 if (!pfn_valid_within(page_to_pfn(page))) {
993 page++;
994 continue;
995 }
996
997 if (!PageBuddy(page)) {
998 page++;
999 continue;
1000 }
1001
1002 order = page_order(page);
84be48d8
KS
1003 list_move(&page->lru,
1004 &zone->free_area[order].free_list[migratetype]);
95e34412 1005 set_freepage_migratetype(page, migratetype);
c361be55 1006 page += 1 << order;
d100313f 1007 pages_moved += 1 << order;
c361be55
MG
1008 }
1009
d100313f 1010 return pages_moved;
c361be55
MG
1011}
1012
ee6f509c 1013int move_freepages_block(struct zone *zone, struct page *page,
68e3e926 1014 int migratetype)
c361be55
MG
1015{
1016 unsigned long start_pfn, end_pfn;
1017 struct page *start_page, *end_page;
1018
1019 start_pfn = page_to_pfn(page);
d9c23400 1020 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
c361be55 1021 start_page = pfn_to_page(start_pfn);
d9c23400
MG
1022 end_page = start_page + pageblock_nr_pages - 1;
1023 end_pfn = start_pfn + pageblock_nr_pages - 1;
c361be55
MG
1024
1025 /* Do not cross zone boundaries */
108bcc96 1026 if (!zone_spans_pfn(zone, start_pfn))
c361be55 1027 start_page = page;
108bcc96 1028 if (!zone_spans_pfn(zone, end_pfn))
c361be55
MG
1029 return 0;
1030
1031 return move_freepages(zone, start_page, end_page, migratetype);
1032}
1033
2f66a68f
MG
1034static void change_pageblock_range(struct page *pageblock_page,
1035 int start_order, int migratetype)
1036{
1037 int nr_pageblocks = 1 << (start_order - pageblock_order);
1038
1039 while (nr_pageblocks--) {
1040 set_pageblock_migratetype(pageblock_page, migratetype);
1041 pageblock_page += pageblock_nr_pages;
1042 }
1043}
1044
6fa3eb70 1045static int preferred_mt = MIGRATE_MOVABLE;
b2a0ac88 1046/* Remove an element from the buddy allocator from the fallback list */
0ac3a409
MG
1047static inline struct page *
1048__rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
b2a0ac88
MG
1049{
1050 struct free_area * area;
1051 int current_order;
1052 struct page *page;
1053 int migratetype, i;
1054
1055 /* Find the largest possible block of pages in the other list */
1056 for (current_order = MAX_ORDER-1; current_order >= order;
1057 --current_order) {
6d4a4916 1058 for (i = 0;; i++) {
b2a0ac88
MG
1059 migratetype = fallbacks[start_migratetype][i];
1060
56fd56b8
MG
1061 /* MIGRATE_RESERVE handled later if necessary */
1062 if (migratetype == MIGRATE_RESERVE)
6d4a4916 1063 break;
e010487d 1064
6fa3eb70
S
1065 /* No fallbacks to MIGRATE_MTKPASR if we are in MTKPASR stage */
1066 if (task_in_mtkpasr(current))
1067 if (is_migrate_mtkpasr(migratetype))
1068 continue;
1069
b2a0ac88
MG
1070 area = &(zone->free_area[current_order]);
1071 if (list_empty(&area->free_list[migratetype]))
1072 continue;
1073
1074 page = list_entry(area->free_list[migratetype].next,
1075 struct page, lru);
1076 area->nr_free--;
1077
6fa3eb70
S
1078 /* We don't want move pages with MIGRATE_MTKPASR to other mobilities either! */
1079 if (is_migrate_mtkpasr(migratetype)) {
1080 /* Speed up allocation for MIGRATE_MOVABLE */
1081 if (start_migratetype == MIGRATE_MOVABLE) {
1082#ifdef CONFIG_MTKPASR
1083 preferred_mt = MIGRATE_MTKPASR;
1084#endif
1085 }
1086 /* Remove the page from the freelists */
1087 list_del(&page->lru);
1088 rmv_page_order(page);
1089 goto no_move;
1090 }
1091
1092 /* We don't want move pages with other mobilities to MIGRATE_MTKPASR */
1093 if (is_migrate_mtkpasr(start_migratetype)) {
1094 preferred_mt = MIGRATE_MOVABLE;
1095 /* Remove the page from the freelists */
1096 list_del(&page->lru);
1097 rmv_page_order(page);
1098 goto no_move;
1099 }
1100
b2a0ac88 1101 /*
c361be55 1102 * If breaking a large block of pages, move all free
46dafbca
MG
1103 * pages to the preferred allocation list. If falling
1104 * back for a reclaimable kernel allocation, be more
25985edc 1105 * aggressive about taking ownership of free pages
47118af0
MN
1106 *
1107 * On the other hand, never change migration
1108 * type of MIGRATE_CMA pageblocks nor move CMA
1109 * pages on different free lists. We don't
1110 * want unmovable pages to be allocated from
1111 * MIGRATE_CMA areas.
b2a0ac88 1112 */
47118af0
MN
1113 if (!is_migrate_cma(migratetype) &&
1114 (unlikely(current_order >= pageblock_order / 2) ||
1115 start_migratetype == MIGRATE_RECLAIMABLE ||
1116 page_group_by_mobility_disabled)) {
1117 int pages;
46dafbca
MG
1118 pages = move_freepages_block(zone, page,
1119 start_migratetype);
1120
1121 /* Claim the whole block if over half of it is free */
dd5d241e
MG
1122 if (pages >= (1 << (pageblock_order-1)) ||
1123 page_group_by_mobility_disabled)
46dafbca
MG
1124 set_pageblock_migratetype(page,
1125 start_migratetype);
1126
b2a0ac88 1127 migratetype = start_migratetype;
c361be55 1128 }
b2a0ac88
MG
1129
1130 /* Remove the page from the freelists */
1131 list_del(&page->lru);
1132 rmv_page_order(page);
b2a0ac88 1133
2f66a68f 1134 /* Take ownership for orders >= pageblock_order */
47118af0
MN
1135 if (current_order >= pageblock_order &&
1136 !is_migrate_cma(migratetype))
2f66a68f 1137 change_pageblock_range(page, current_order,
b2a0ac88 1138 start_migratetype);
6fa3eb70 1139no_move:
47118af0 1140 expand(zone, page, order, current_order, area,
6fa3eb70 1141 (is_migrate_cma(migratetype) || is_migrate_mtkpasr(start_migratetype) || is_migrate_mtkpasr(migratetype))
47118af0 1142 ? migratetype : start_migratetype);
e0fff1bd
MG
1143
1144 trace_mm_page_alloc_extfrag(page, order, current_order,
1145 start_migratetype, migratetype);
1146
b2a0ac88
MG
1147 return page;
1148 }
1149 }
1150
728ec980 1151 return NULL;
b2a0ac88
MG
1152}
1153
56fd56b8 1154/*
1da177e4
LT
1155 * Do the hard work of removing an element from the buddy allocator.
1156 * Call me with the zone->lock already held.
1157 */
b2a0ac88
MG
1158static struct page *__rmqueue(struct zone *zone, unsigned int order,
1159 int migratetype)
1da177e4 1160{
1da177e4
LT
1161 struct page *page;
1162
728ec980 1163retry_reserve:
56fd56b8 1164 page = __rmqueue_smallest(zone, order, migratetype);
b2a0ac88 1165
728ec980 1166 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
56fd56b8 1167 page = __rmqueue_fallback(zone, order, migratetype);
b2a0ac88 1168
728ec980
MG
1169 /*
1170 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1171 * is used because __rmqueue_smallest is an inline function
1172 * and we want just one call site
1173 */
1174 if (!page) {
1175 migratetype = MIGRATE_RESERVE;
1176 goto retry_reserve;
1177 }
1178 }
1179
0d3d062a 1180 trace_mm_page_alloc_zone_locked(page, order, migratetype);
b2a0ac88 1181 return page;
1da177e4
LT
1182}
1183
5f63b720 1184/*
1da177e4
LT
1185 * Obtain a specified number of elements from the buddy allocator, all under
1186 * a single hold of the lock, for efficiency. Add them to the supplied list.
1187 * Returns the number of new pages which were placed at *list.
1188 */
5f63b720 1189static int rmqueue_bulk(struct zone *zone, unsigned int order,
b2a0ac88 1190 unsigned long count, struct list_head *list,
e084b2d9 1191 int migratetype, int cold)
1da177e4 1192{
47118af0 1193 int mt = migratetype, i;
5f63b720 1194
c54ad30c 1195 spin_lock(&zone->lock);
1da177e4 1196 for (i = 0; i < count; ++i) {
b2a0ac88 1197 struct page *page = __rmqueue(zone, order, migratetype);
085cc7d5 1198 if (unlikely(page == NULL))
1da177e4 1199 break;
81eabcbe
MG
1200
1201 /*
1202 * Split buddy pages returned by expand() are received here
1203 * in physical page order. The page is added to the callers and
1204 * list and the list head then moves forward. From the callers
1205 * perspective, the linked list is ordered by page number in
1206 * some conditions. This is useful for IO devices that can
1207 * merge IO requests if the physical pages are ordered
1208 * properly.
1209 */
e084b2d9
MG
1210 if (likely(cold == 0))
1211 list_add(&page->lru, list);
1212 else
1213 list_add_tail(&page->lru, list);
47118af0
MN
1214 if (IS_ENABLED(CONFIG_CMA)) {
1215 mt = get_pageblock_migratetype(page);
194159fb 1216 if (!is_migrate_cma(mt) && !is_migrate_isolate(mt))
47118af0
MN
1217 mt = migratetype;
1218 }
6fa3eb70
S
1219
1220 if (IS_ENABLED(CONFIG_MTKPASR)) {
1221 mt = get_pageblock_migratetype(page);
1222 /* No change on the mobility of "MIGRATE_MTKPASR" page */
1223 if (!is_migrate_mtkpasr(mt) && !is_migrate_mtkpasr(migratetype))
1224 mt = migratetype;
1225 }
1226
b12c4ad1 1227 set_freepage_migratetype(page, mt);
81eabcbe 1228 list = &page->lru;
d1ce749a
BZ
1229 if (is_migrate_cma(mt))
1230 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1231 -(1 << order));
1da177e4 1232 }
f2260e6b 1233 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
c54ad30c 1234 spin_unlock(&zone->lock);
085cc7d5 1235 return i;
1da177e4
LT
1236}
1237
4ae7c039 1238#ifdef CONFIG_NUMA
8fce4d8e 1239/*
4037d452
CL
1240 * Called from the vmstat counter updater to drain pagesets of this
1241 * currently executing processor on remote nodes after they have
1242 * expired.
1243 *
879336c3
CL
1244 * Note that this function must be called with the thread pinned to
1245 * a single processor.
8fce4d8e 1246 */
4037d452 1247void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
4ae7c039 1248{
4ae7c039 1249 unsigned long flags;
4037d452 1250 int to_drain;
4ae7c039 1251
4037d452
CL
1252 local_irq_save(flags);
1253 if (pcp->count >= pcp->batch)
1254 to_drain = pcp->batch;
1255 else
1256 to_drain = pcp->count;
2a13515c
KM
1257 if (to_drain > 0) {
1258 free_pcppages_bulk(zone, to_drain, pcp);
1259 pcp->count -= to_drain;
1260 }
4037d452 1261 local_irq_restore(flags);
4ae7c039
CL
1262}
1263#endif
1264
9f8f2172
CL
1265/*
1266 * Drain pages of the indicated processor.
1267 *
1268 * The processor must either be the current processor and the
1269 * thread pinned to the current processor or a processor that
1270 * is not online.
1271 */
1272static void drain_pages(unsigned int cpu)
1da177e4 1273{
c54ad30c 1274 unsigned long flags;
1da177e4 1275 struct zone *zone;
1da177e4 1276
ee99c71c 1277 for_each_populated_zone(zone) {
1da177e4 1278 struct per_cpu_pageset *pset;
3dfa5721 1279 struct per_cpu_pages *pcp;
1da177e4 1280
99dcc3e5
CL
1281 local_irq_save(flags);
1282 pset = per_cpu_ptr(zone->pageset, cpu);
3dfa5721
CL
1283
1284 pcp = &pset->pcp;
2ff754fa
DR
1285 if (pcp->count) {
1286 free_pcppages_bulk(zone, pcp->count, pcp);
1287 pcp->count = 0;
1288 }
3dfa5721 1289 local_irq_restore(flags);
1da177e4
LT
1290 }
1291}
1da177e4 1292
9f8f2172
CL
1293/*
1294 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1295 */
1296void drain_local_pages(void *arg)
1297{
1298 drain_pages(smp_processor_id());
1299}
1300
1301/*
74046494
GBY
1302 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1303 *
1304 * Note that this code is protected against sending an IPI to an offline
1305 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1306 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1307 * nothing keeps CPUs from showing up after we populated the cpumask and
1308 * before the call to on_each_cpu_mask().
9f8f2172
CL
1309 */
1310void drain_all_pages(void)
1311{
74046494
GBY
1312 int cpu;
1313 struct per_cpu_pageset *pcp;
1314 struct zone *zone;
1315
1316 /*
1317 * Allocate in the BSS so we wont require allocation in
1318 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1319 */
1320 static cpumask_t cpus_with_pcps;
1321
1322 /*
1323 * We don't care about racing with CPU hotplug event
1324 * as offline notification will cause the notified
1325 * cpu to drain that CPU pcps and on_each_cpu_mask
1326 * disables preemption as part of its processing
1327 */
1328 for_each_online_cpu(cpu) {
1329 bool has_pcps = false;
1330 for_each_populated_zone(zone) {
1331 pcp = per_cpu_ptr(zone->pageset, cpu);
1332 if (pcp->pcp.count) {
1333 has_pcps = true;
1334 break;
1335 }
1336 }
1337 if (has_pcps)
1338 cpumask_set_cpu(cpu, &cpus_with_pcps);
1339 else
1340 cpumask_clear_cpu(cpu, &cpus_with_pcps);
1341 }
1342 on_each_cpu_mask(&cpus_with_pcps, drain_local_pages, NULL, 1);
9f8f2172
CL
1343}
1344
296699de 1345#ifdef CONFIG_HIBERNATION
1da177e4
LT
1346
1347void mark_free_pages(struct zone *zone)
1348{
f623f0db
RW
1349 unsigned long pfn, max_zone_pfn;
1350 unsigned long flags;
b2a0ac88 1351 int order, t;
1da177e4
LT
1352 struct list_head *curr;
1353
1354 if (!zone->spanned_pages)
1355 return;
1356
1357 spin_lock_irqsave(&zone->lock, flags);
f623f0db 1358
108bcc96 1359 max_zone_pfn = zone_end_pfn(zone);
f623f0db
RW
1360 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1361 if (pfn_valid(pfn)) {
1362 struct page *page = pfn_to_page(pfn);
1363
7be98234
RW
1364 if (!swsusp_page_is_forbidden(page))
1365 swsusp_unset_page_free(page);
f623f0db 1366 }
1da177e4 1367
b2a0ac88
MG
1368 for_each_migratetype_order(order, t) {
1369 list_for_each(curr, &zone->free_area[order].free_list[t]) {
f623f0db 1370 unsigned long i;
1da177e4 1371
f623f0db
RW
1372 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1373 for (i = 0; i < (1UL << order); i++)
7be98234 1374 swsusp_set_page_free(pfn_to_page(pfn + i));
f623f0db 1375 }
b2a0ac88 1376 }
1da177e4
LT
1377 spin_unlock_irqrestore(&zone->lock, flags);
1378}
e2c55dc8 1379#endif /* CONFIG_PM */
1da177e4 1380
1da177e4
LT
1381/*
1382 * Free a 0-order page
fc91668e 1383 * cold == 1 ? free a cold page : free a hot page
1da177e4 1384 */
fc91668e 1385void free_hot_cold_page(struct page *page, int cold)
1da177e4
LT
1386{
1387 struct zone *zone = page_zone(page);
1388 struct per_cpu_pages *pcp;
1389 unsigned long flags;
5f8dcc21 1390 int migratetype;
1da177e4 1391
ec95f53a 1392 if (!free_pages_prepare(page, 0))
689bcebf
HD
1393 return;
1394
5f8dcc21 1395 migratetype = get_pageblock_migratetype(page);
b12c4ad1 1396 set_freepage_migratetype(page, migratetype);
1da177e4 1397 local_irq_save(flags);
f8891e5e 1398 __count_vm_event(PGFREE);
da456f14 1399
5f8dcc21
MG
1400 /*
1401 * We only track unmovable, reclaimable and movable on pcp lists.
1402 * Free ISOLATE pages back to the allocator because they are being
1403 * offlined but treat RESERVE as movable pages so we can get those
1404 * areas back if necessary. Otherwise, we may have to free
1405 * excessively into the page allocator
1406 */
1407 if (migratetype >= MIGRATE_PCPTYPES) {
194159fb 1408 if (unlikely(is_migrate_isolate(migratetype))) {
5f8dcc21
MG
1409 free_one_page(zone, page, 0, migratetype);
1410 goto out;
1411 }
1412 migratetype = MIGRATE_MOVABLE;
1413 }
1414
99dcc3e5 1415 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3dfa5721 1416 if (cold)
5f8dcc21 1417 list_add_tail(&page->lru, &pcp->lists[migratetype]);
3dfa5721 1418 else
5f8dcc21 1419 list_add(&page->lru, &pcp->lists[migratetype]);
1da177e4 1420 pcp->count++;
48db57f8 1421 if (pcp->count >= pcp->high) {
5f8dcc21 1422 free_pcppages_bulk(zone, pcp->batch, pcp);
48db57f8
NP
1423 pcp->count -= pcp->batch;
1424 }
5f8dcc21
MG
1425
1426out:
1da177e4 1427 local_irq_restore(flags);
1da177e4
LT
1428}
1429
cc59850e
KK
1430/*
1431 * Free a list of 0-order pages
1432 */
1433void free_hot_cold_page_list(struct list_head *list, int cold)
1434{
1435 struct page *page, *next;
1436
1437 list_for_each_entry_safe(page, next, list, lru) {
b413d48a 1438 trace_mm_page_free_batched(page, cold);
cc59850e
KK
1439 free_hot_cold_page(page, cold);
1440 }
1441}
1442
8dfcc9ba
NP
1443/*
1444 * split_page takes a non-compound higher-order page, and splits it into
1445 * n (1<<order) sub-pages: page[0..n]
1446 * Each sub-page must be freed individually.
1447 *
1448 * Note: this is probably too low level an operation for use in drivers.
1449 * Please consult with lkml before using this in your driver.
1450 */
1451void split_page(struct page *page, unsigned int order)
1452{
1453 int i;
1454
725d704e
NP
1455 VM_BUG_ON(PageCompound(page));
1456 VM_BUG_ON(!page_count(page));
b1eeab67
VN
1457
1458#ifdef CONFIG_KMEMCHECK
1459 /*
1460 * Split shadow pages too, because free(page[0]) would
1461 * otherwise free the whole shadow.
1462 */
1463 if (kmemcheck_page_is_tracked(page))
1464 split_page(virt_to_page(page[0].shadow), order);
1465#endif
1466
7835e98b
NP
1467 for (i = 1; i < (1 << order); i++)
1468 set_page_refcounted(page + i);
8dfcc9ba 1469}
5853ff23 1470EXPORT_SYMBOL_GPL(split_page);
8dfcc9ba 1471
8fb74b9f 1472static int __isolate_free_page(struct page *page, unsigned int order)
748446bb 1473{
748446bb
MG
1474 unsigned long watermark;
1475 struct zone *zone;
2139cbe6 1476 int mt;
748446bb
MG
1477
1478 BUG_ON(!PageBuddy(page));
1479
1480 zone = page_zone(page);
2e30abd1 1481 mt = get_pageblock_migratetype(page);
748446bb 1482
194159fb 1483 if (!is_migrate_isolate(mt)) {
2e30abd1
MS
1484 /* Obey watermarks as if the page was being allocated */
1485 watermark = low_wmark_pages(zone) + (1 << order);
1486 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1487 return 0;
1488
8fb74b9f 1489 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2e30abd1 1490 }
748446bb
MG
1491
1492 /* Remove page from free list */
1493 list_del(&page->lru);
1494 zone->free_area[order].nr_free--;
1495 rmv_page_order(page);
2139cbe6 1496
8fb74b9f 1497 /* Set the pageblock if the isolated page is at least a pageblock */
748446bb
MG
1498 if (order >= pageblock_order - 1) {
1499 struct page *endpage = page + (1 << order) - 1;
47118af0
MN
1500 for (; page < endpage; page += pageblock_nr_pages) {
1501 int mt = get_pageblock_migratetype(page);
194159fb 1502 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
47118af0
MN
1503 set_pageblock_migratetype(page,
1504 MIGRATE_MOVABLE);
1505 }
748446bb
MG
1506 }
1507
8fb74b9f 1508 return 1UL << order;
1fb3f8ca
MG
1509}
1510
1511/*
1512 * Similar to split_page except the page is already free. As this is only
1513 * being used for migration, the migratetype of the block also changes.
1514 * As this is called with interrupts disabled, the caller is responsible
1515 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1516 * are enabled.
1517 *
1518 * Note: this is probably too low level an operation for use in drivers.
1519 * Please consult with lkml before using this in your driver.
1520 */
1521int split_free_page(struct page *page)
1522{
1523 unsigned int order;
1524 int nr_pages;
1525
1fb3f8ca
MG
1526 order = page_order(page);
1527
8fb74b9f 1528 nr_pages = __isolate_free_page(page, order);
1fb3f8ca
MG
1529 if (!nr_pages)
1530 return 0;
1531
1532 /* Split into individual pages */
1533 set_page_refcounted(page);
1534 split_page(page, order);
1535 return nr_pages;
748446bb
MG
1536}
1537
1da177e4
LT
1538/*
1539 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1540 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1541 * or two.
1542 */
0a15c3e9
MG
1543static inline
1544struct page *buffered_rmqueue(struct zone *preferred_zone,
3dd28266
MG
1545 struct zone *zone, int order, gfp_t gfp_flags,
1546 int migratetype)
1da177e4
LT
1547{
1548 unsigned long flags;
689bcebf 1549 struct page *page;
1da177e4
LT
1550 int cold = !!(gfp_flags & __GFP_COLD);
1551
689bcebf 1552again:
48db57f8 1553 if (likely(order == 0)) {
1da177e4 1554 struct per_cpu_pages *pcp;
5f8dcc21 1555 struct list_head *list;
1da177e4 1556
1da177e4 1557 local_irq_save(flags);
99dcc3e5
CL
1558 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1559 list = &pcp->lists[migratetype];
5f8dcc21 1560 if (list_empty(list)) {
535131e6 1561 pcp->count += rmqueue_bulk(zone, 0,
5f8dcc21 1562 pcp->batch, list,
e084b2d9 1563 migratetype, cold);
5f8dcc21 1564 if (unlikely(list_empty(list)))
6fb332fa 1565 goto failed;
535131e6 1566 }
b92a6edd 1567
5f8dcc21
MG
1568 if (cold)
1569 page = list_entry(list->prev, struct page, lru);
1570 else
1571 page = list_entry(list->next, struct page, lru);
1572
b92a6edd
MG
1573 list_del(&page->lru);
1574 pcp->count--;
7fb1d9fc 1575 } else {
dab48dab
AM
1576 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1577 /*
1578 * __GFP_NOFAIL is not to be used in new code.
1579 *
1580 * All __GFP_NOFAIL callers should be fixed so that they
1581 * properly detect and handle allocation failures.
1582 *
1583 * We most definitely don't want callers attempting to
4923abf9 1584 * allocate greater than order-1 page units with
dab48dab
AM
1585 * __GFP_NOFAIL.
1586 */
4923abf9 1587 WARN_ON_ONCE(order > 1);
dab48dab 1588 }
1da177e4 1589 spin_lock_irqsave(&zone->lock, flags);
b2a0ac88 1590 page = __rmqueue(zone, order, migratetype);
a74609fa
NP
1591 spin_unlock(&zone->lock);
1592 if (!page)
1593 goto failed;
d1ce749a
BZ
1594 __mod_zone_freepage_state(zone, -(1 << order),
1595 get_pageblock_migratetype(page));
1da177e4
LT
1596 }
1597
f8891e5e 1598 __count_zone_vm_events(PGALLOC, zone, 1 << order);
78afd561 1599 zone_statistics(preferred_zone, zone, gfp_flags);
a74609fa 1600 local_irq_restore(flags);
1da177e4 1601
725d704e 1602 VM_BUG_ON(bad_range(zone, page));
17cf4406 1603 if (prep_new_page(page, order, gfp_flags))
a74609fa 1604 goto again;
1da177e4 1605 return page;
a74609fa
NP
1606
1607failed:
1608 local_irq_restore(flags);
a74609fa 1609 return NULL;
1da177e4
LT
1610}
1611
933e312e
AM
1612#ifdef CONFIG_FAIL_PAGE_ALLOC
1613
b2588c4b 1614static struct {
933e312e
AM
1615 struct fault_attr attr;
1616
1617 u32 ignore_gfp_highmem;
1618 u32 ignore_gfp_wait;
54114994 1619 u32 min_order;
933e312e
AM
1620} fail_page_alloc = {
1621 .attr = FAULT_ATTR_INITIALIZER,
6b1b60f4
DM
1622 .ignore_gfp_wait = 1,
1623 .ignore_gfp_highmem = 1,
54114994 1624 .min_order = 1,
933e312e
AM
1625};
1626
1627static int __init setup_fail_page_alloc(char *str)
1628{
1629 return setup_fault_attr(&fail_page_alloc.attr, str);
1630}
1631__setup("fail_page_alloc=", setup_fail_page_alloc);
1632
deaf386e 1633static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
933e312e 1634{
54114994 1635 if (order < fail_page_alloc.min_order)
deaf386e 1636 return false;
933e312e 1637 if (gfp_mask & __GFP_NOFAIL)
deaf386e 1638 return false;
933e312e 1639 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
deaf386e 1640 return false;
933e312e 1641 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
deaf386e 1642 return false;
933e312e
AM
1643
1644 return should_fail(&fail_page_alloc.attr, 1 << order);
1645}
1646
1647#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1648
1649static int __init fail_page_alloc_debugfs(void)
1650{
f4ae40a6 1651 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
933e312e 1652 struct dentry *dir;
933e312e 1653
dd48c085
AM
1654 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1655 &fail_page_alloc.attr);
1656 if (IS_ERR(dir))
1657 return PTR_ERR(dir);
933e312e 1658
b2588c4b
AM
1659 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1660 &fail_page_alloc.ignore_gfp_wait))
1661 goto fail;
1662 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1663 &fail_page_alloc.ignore_gfp_highmem))
1664 goto fail;
1665 if (!debugfs_create_u32("min-order", mode, dir,
1666 &fail_page_alloc.min_order))
1667 goto fail;
1668
1669 return 0;
1670fail:
dd48c085 1671 debugfs_remove_recursive(dir);
933e312e 1672
b2588c4b 1673 return -ENOMEM;
933e312e
AM
1674}
1675
1676late_initcall(fail_page_alloc_debugfs);
1677
1678#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1679
1680#else /* CONFIG_FAIL_PAGE_ALLOC */
1681
deaf386e 1682static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
933e312e 1683{
deaf386e 1684 return false;
933e312e
AM
1685}
1686
1687#endif /* CONFIG_FAIL_PAGE_ALLOC */
1688
1da177e4 1689/*
88f5acf8 1690 * Return true if free pages are above 'mark'. This takes into account the order
1da177e4
LT
1691 * of the allocation.
1692 */
88f5acf8
MG
1693static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1694 int classzone_idx, int alloc_flags, long free_pages)
1da177e4
LT
1695{
1696 /* free_pages my go negative - that's OK */
d23ad423 1697 long min = mark;
2cfed075 1698 long lowmem_reserve = z->lowmem_reserve[classzone_idx];
1da177e4 1699 int o;
026b0814 1700 long free_cma = 0;
1da177e4 1701
df0a6daa 1702 free_pages -= (1 << order) - 1;
7fb1d9fc 1703 if (alloc_flags & ALLOC_HIGH)
1da177e4 1704 min -= min / 2;
7fb1d9fc 1705 if (alloc_flags & ALLOC_HARDER)
1da177e4 1706 min -= min / 4;
d95ea5d1
BZ
1707#ifdef CONFIG_CMA
1708 /* If allocation can't use CMA areas don't use free CMA pages */
1709 if (!(alloc_flags & ALLOC_CMA))
026b0814 1710 free_cma = zone_page_state(z, NR_FREE_CMA_PAGES);
d95ea5d1 1711#endif
026b0814
TS
1712
1713 if (free_pages - free_cma <= min + lowmem_reserve)
88f5acf8 1714 return false;
1da177e4
LT
1715 for (o = 0; o < order; o++) {
1716 /* At the next order, this order's pages become unavailable */
1717 free_pages -= z->free_area[o].nr_free << o;
1718
1719 /* Require fewer higher order pages to be free */
6fa3eb70 1720 min >>= min_free_order_shift;
1da177e4
LT
1721
1722 if (free_pages <= min)
88f5acf8 1723 return false;
1da177e4 1724 }
88f5acf8
MG
1725 return true;
1726}
1727
1728bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1729 int classzone_idx, int alloc_flags)
1730{
1731 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1732 zone_page_state(z, NR_FREE_PAGES));
1733}
1734
1735bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
1736 int classzone_idx, int alloc_flags)
1737{
1738 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1739
1740 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1741 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1742
1743 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1744 free_pages);
1da177e4
LT
1745}
1746
9276b1bc
PJ
1747#ifdef CONFIG_NUMA
1748/*
1749 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1750 * skip over zones that are not allowed by the cpuset, or that have
1751 * been recently (in last second) found to be nearly full. See further
1752 * comments in mmzone.h. Reduces cache footprint of zonelist scans
183ff22b 1753 * that have to skip over a lot of full or unallowed zones.
9276b1bc
PJ
1754 *
1755 * If the zonelist cache is present in the passed in zonelist, then
1756 * returns a pointer to the allowed node mask (either the current
4b0ef1fe 1757 * tasks mems_allowed, or node_states[N_MEMORY].)
9276b1bc
PJ
1758 *
1759 * If the zonelist cache is not available for this zonelist, does
1760 * nothing and returns NULL.
1761 *
1762 * If the fullzones BITMAP in the zonelist cache is stale (more than
1763 * a second since last zap'd) then we zap it out (clear its bits.)
1764 *
1765 * We hold off even calling zlc_setup, until after we've checked the
1766 * first zone in the zonelist, on the theory that most allocations will
1767 * be satisfied from that first zone, so best to examine that zone as
1768 * quickly as we can.
1769 */
1770static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1771{
1772 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1773 nodemask_t *allowednodes; /* zonelist_cache approximation */
1774
1775 zlc = zonelist->zlcache_ptr;
1776 if (!zlc)
1777 return NULL;
1778
f05111f5 1779 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
9276b1bc
PJ
1780 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1781 zlc->last_full_zap = jiffies;
1782 }
1783
1784 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1785 &cpuset_current_mems_allowed :
4b0ef1fe 1786 &node_states[N_MEMORY];
9276b1bc
PJ
1787 return allowednodes;
1788}
1789
1790/*
1791 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1792 * if it is worth looking at further for free memory:
1793 * 1) Check that the zone isn't thought to be full (doesn't have its
1794 * bit set in the zonelist_cache fullzones BITMAP).
1795 * 2) Check that the zones node (obtained from the zonelist_cache
1796 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1797 * Return true (non-zero) if zone is worth looking at further, or
1798 * else return false (zero) if it is not.
1799 *
1800 * This check -ignores- the distinction between various watermarks,
1801 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1802 * found to be full for any variation of these watermarks, it will
1803 * be considered full for up to one second by all requests, unless
1804 * we are so low on memory on all allowed nodes that we are forced
1805 * into the second scan of the zonelist.
1806 *
1807 * In the second scan we ignore this zonelist cache and exactly
1808 * apply the watermarks to all zones, even it is slower to do so.
1809 * We are low on memory in the second scan, and should leave no stone
1810 * unturned looking for a free page.
1811 */
dd1a239f 1812static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
9276b1bc
PJ
1813 nodemask_t *allowednodes)
1814{
1815 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1816 int i; /* index of *z in zonelist zones */
1817 int n; /* node that zone *z is on */
1818
1819 zlc = zonelist->zlcache_ptr;
1820 if (!zlc)
1821 return 1;
1822
dd1a239f 1823 i = z - zonelist->_zonerefs;
9276b1bc
PJ
1824 n = zlc->z_to_n[i];
1825
1826 /* This zone is worth trying if it is allowed but not full */
1827 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1828}
1829
1830/*
1831 * Given 'z' scanning a zonelist, set the corresponding bit in
1832 * zlc->fullzones, so that subsequent attempts to allocate a page
1833 * from that zone don't waste time re-examining it.
1834 */
dd1a239f 1835static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
9276b1bc
PJ
1836{
1837 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1838 int i; /* index of *z in zonelist zones */
1839
1840 zlc = zonelist->zlcache_ptr;
1841 if (!zlc)
1842 return;
1843
dd1a239f 1844 i = z - zonelist->_zonerefs;
9276b1bc
PJ
1845
1846 set_bit(i, zlc->fullzones);
1847}
1848
76d3fbf8
MG
1849/*
1850 * clear all zones full, called after direct reclaim makes progress so that
1851 * a zone that was recently full is not skipped over for up to a second
1852 */
1853static void zlc_clear_zones_full(struct zonelist *zonelist)
1854{
1855 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1856
1857 zlc = zonelist->zlcache_ptr;
1858 if (!zlc)
1859 return;
1860
1861 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1862}
1863
957f822a
DR
1864static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1865{
1866 return node_isset(local_zone->node, zone->zone_pgdat->reclaim_nodes);
1867}
1868
1869static void __paginginit init_zone_allows_reclaim(int nid)
1870{
1871 int i;
1872
1873 for_each_online_node(i)
6b187d02 1874 if (node_distance(nid, i) <= RECLAIM_DISTANCE)
957f822a 1875 node_set(i, NODE_DATA(nid)->reclaim_nodes);
6b187d02 1876 else
957f822a 1877 zone_reclaim_mode = 1;
957f822a
DR
1878}
1879
9276b1bc
PJ
1880#else /* CONFIG_NUMA */
1881
1882static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1883{
1884 return NULL;
1885}
1886
dd1a239f 1887static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
9276b1bc
PJ
1888 nodemask_t *allowednodes)
1889{
1890 return 1;
1891}
1892
dd1a239f 1893static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
9276b1bc
PJ
1894{
1895}
76d3fbf8
MG
1896
1897static void zlc_clear_zones_full(struct zonelist *zonelist)
1898{
1899}
957f822a
DR
1900
1901static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1902{
1903 return true;
1904}
1905
1906static inline void init_zone_allows_reclaim(int nid)
1907{
1908}
9276b1bc
PJ
1909#endif /* CONFIG_NUMA */
1910
7fb1d9fc 1911/*
0798e519 1912 * get_page_from_freelist goes through the zonelist trying to allocate
7fb1d9fc
RS
1913 * a page.
1914 */
1915static struct page *
19770b32 1916get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
5117f45d 1917 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
3dd28266 1918 struct zone *preferred_zone, int migratetype)
753ee728 1919{
dd1a239f 1920 struct zoneref *z;
7fb1d9fc 1921 struct page *page = NULL;
54a6eb5c 1922 int classzone_idx;
5117f45d 1923 struct zone *zone;
9276b1bc
PJ
1924 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1925 int zlc_active = 0; /* set if using zonelist_cache */
1926 int did_zlc_setup = 0; /* just call zlc_setup() one time */
54a6eb5c 1927
19770b32 1928 classzone_idx = zone_idx(preferred_zone);
9276b1bc 1929zonelist_scan:
7fb1d9fc 1930 /*
9276b1bc 1931 * Scan zonelist, looking for a zone with enough free.
7fb1d9fc
RS
1932 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1933 */
19770b32
MG
1934 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1935 high_zoneidx, nodemask) {
e5adfffc 1936 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
9276b1bc
PJ
1937 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1938 continue;
7fb1d9fc 1939 if ((alloc_flags & ALLOC_CPUSET) &&
02a0e53d 1940 !cpuset_zone_allowed_softwall(zone, gfp_mask))
cd38b115 1941 continue;
a756cf59
JW
1942 /*
1943 * When allocating a page cache page for writing, we
1944 * want to get it from a zone that is within its dirty
1945 * limit, such that no single zone holds more than its
1946 * proportional share of globally allowed dirty pages.
1947 * The dirty limits take into account the zone's
1948 * lowmem reserves and high watermark so that kswapd
1949 * should be able to balance it without having to
1950 * write pages from its LRU list.
1951 *
1952 * This may look like it could increase pressure on
1953 * lower zones by failing allocations in higher zones
1954 * before they are full. But the pages that do spill
1955 * over are limited as the lower zones are protected
1956 * by this very same mechanism. It should not become
1957 * a practical burden to them.
1958 *
1959 * XXX: For now, allow allocations to potentially
1960 * exceed the per-zone dirty limit in the slowpath
1961 * (ALLOC_WMARK_LOW unset) before going into reclaim,
1962 * which is important when on a NUMA setup the allowed
1963 * zones are together not big enough to reach the
1964 * global limit. The proper fix for these situations
1965 * will require awareness of zones in the
1966 * dirty-throttling and the flusher threads.
1967 */
1968 if ((alloc_flags & ALLOC_WMARK_LOW) &&
1969 (gfp_mask & __GFP_WRITE) && !zone_dirty_ok(zone))
1970 goto this_zone_full;
7fb1d9fc 1971
41858966 1972 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
7fb1d9fc 1973 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
3148890b 1974 unsigned long mark;
fa5e084e
MG
1975 int ret;
1976
41858966 1977 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
fa5e084e
MG
1978 if (zone_watermark_ok(zone, order, mark,
1979 classzone_idx, alloc_flags))
1980 goto try_this_zone;
1981
e5adfffc
KS
1982 if (IS_ENABLED(CONFIG_NUMA) &&
1983 !did_zlc_setup && nr_online_nodes > 1) {
cd38b115
MG
1984 /*
1985 * we do zlc_setup if there are multiple nodes
1986 * and before considering the first zone allowed
1987 * by the cpuset.
1988 */
1989 allowednodes = zlc_setup(zonelist, alloc_flags);
1990 zlc_active = 1;
1991 did_zlc_setup = 1;
1992 }
1993
957f822a
DR
1994 if (zone_reclaim_mode == 0 ||
1995 !zone_allows_reclaim(preferred_zone, zone))
fa5e084e
MG
1996 goto this_zone_full;
1997
cd38b115
MG
1998 /*
1999 * As we may have just activated ZLC, check if the first
2000 * eligible zone has failed zone_reclaim recently.
2001 */
e5adfffc 2002 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
cd38b115
MG
2003 !zlc_zone_worth_trying(zonelist, z, allowednodes))
2004 continue;
2005
fa5e084e
MG
2006 ret = zone_reclaim(zone, gfp_mask, order);
2007 switch (ret) {
2008 case ZONE_RECLAIM_NOSCAN:
2009 /* did not scan */
cd38b115 2010 continue;
fa5e084e
MG
2011 case ZONE_RECLAIM_FULL:
2012 /* scanned but unreclaimable */
cd38b115 2013 continue;
fa5e084e
MG
2014 default:
2015 /* did we reclaim enough */
fed2719e 2016 if (zone_watermark_ok(zone, order, mark,
fa5e084e 2017 classzone_idx, alloc_flags))
fed2719e
MG
2018 goto try_this_zone;
2019
2020 /*
2021 * Failed to reclaim enough to meet watermark.
2022 * Only mark the zone full if checking the min
2023 * watermark or if we failed to reclaim just
2024 * 1<<order pages or else the page allocator
2025 * fastpath will prematurely mark zones full
2026 * when the watermark is between the low and
2027 * min watermarks.
2028 */
2029 if (((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN) ||
2030 ret == ZONE_RECLAIM_SOME)
9276b1bc 2031 goto this_zone_full;
fed2719e
MG
2032
2033 continue;
0798e519 2034 }
7fb1d9fc
RS
2035 }
2036
fa5e084e 2037try_this_zone:
3dd28266
MG
2038 page = buffered_rmqueue(preferred_zone, zone, order,
2039 gfp_mask, migratetype);
0798e519 2040 if (page)
7fb1d9fc 2041 break;
9276b1bc 2042this_zone_full:
e5adfffc 2043 if (IS_ENABLED(CONFIG_NUMA))
9276b1bc 2044 zlc_mark_zone_full(zonelist, z);
54a6eb5c 2045 }
9276b1bc 2046
e5adfffc 2047 if (unlikely(IS_ENABLED(CONFIG_NUMA) && page == NULL && zlc_active)) {
9276b1bc
PJ
2048 /* Disable zlc cache for second zonelist scan */
2049 zlc_active = 0;
2050 goto zonelist_scan;
2051 }
b121186a
AS
2052
2053 if (page)
2054 /*
2055 * page->pfmemalloc is set when ALLOC_NO_WATERMARKS was
2056 * necessary to allocate the page. The expectation is
2057 * that the caller is taking steps that will free more
2058 * memory. The caller should avoid the page being used
2059 * for !PFMEMALLOC purposes.
2060 */
2061 page->pfmemalloc = !!(alloc_flags & ALLOC_NO_WATERMARKS);
2062
7fb1d9fc 2063 return page;
753ee728
MH
2064}
2065
29423e77
DR
2066/*
2067 * Large machines with many possible nodes should not always dump per-node
2068 * meminfo in irq context.
2069 */
2070static inline bool should_suppress_show_mem(void)
2071{
2072 bool ret = false;
2073
2074#if NODES_SHIFT > 8
2075 ret = in_interrupt();
2076#endif
2077 return ret;
2078}
2079
a238ab5b
DH
2080static DEFINE_RATELIMIT_STATE(nopage_rs,
2081 DEFAULT_RATELIMIT_INTERVAL,
2082 DEFAULT_RATELIMIT_BURST);
2083
2084void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
2085{
a238ab5b 2086 unsigned int filter = SHOW_MEM_FILTER_NODES;
6fa3eb70
S
2087
2088 /* No warning message during PASR stage */
2089 if (task_in_mtkpasr(current)) {
2090 return;
2091 }
a238ab5b 2092
c0a32fc5
SG
2093 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2094 debug_guardpage_minorder() > 0)
a238ab5b
DH
2095 return;
2096
4b59e6c4
DR
2097 /*
2098 * Walking all memory to count page types is very expensive and should
2099 * be inhibited in non-blockable contexts.
2100 */
2101 if (!(gfp_mask & __GFP_WAIT))
2102 filter |= SHOW_MEM_FILTER_PAGE_COUNT;
2103
a238ab5b
DH
2104 /*
2105 * This documents exceptions given to allocations in certain
2106 * contexts that are allowed to allocate outside current's set
2107 * of allowed nodes.
2108 */
2109 if (!(gfp_mask & __GFP_NOMEMALLOC))
2110 if (test_thread_flag(TIF_MEMDIE) ||
2111 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2112 filter &= ~SHOW_MEM_FILTER_NODES;
2113 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
2114 filter &= ~SHOW_MEM_FILTER_NODES;
2115
2116 if (fmt) {
3ee9a4f0
JP
2117 struct va_format vaf;
2118 va_list args;
2119
a238ab5b 2120 va_start(args, fmt);
3ee9a4f0
JP
2121
2122 vaf.fmt = fmt;
2123 vaf.va = &args;
2124
2125 pr_warn("%pV", &vaf);
2126
a238ab5b
DH
2127 va_end(args);
2128 }
2129
3ee9a4f0
JP
2130 pr_warn("%s: page allocation failure: order:%d, mode:0x%x\n",
2131 current->comm, order, gfp_mask);
a238ab5b
DH
2132
2133 dump_stack();
2134 if (!should_suppress_show_mem())
2135 show_mem(filter);
2136}
2137
11e33f6a
MG
2138static inline int
2139should_alloc_retry(gfp_t gfp_mask, unsigned int order,
f90ac398 2140 unsigned long did_some_progress,
11e33f6a 2141 unsigned long pages_reclaimed)
1da177e4 2142{
11e33f6a
MG
2143 /* Do not loop if specifically requested */
2144 if (gfp_mask & __GFP_NORETRY)
2145 return 0;
1da177e4 2146
f90ac398
MG
2147 /* Always retry if specifically requested */
2148 if (gfp_mask & __GFP_NOFAIL)
2149 return 1;
2150
2151 /*
2152 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
2153 * making forward progress without invoking OOM. Suspend also disables
2154 * storage devices so kswapd will not help. Bail if we are suspending.
2155 */
2156 if (!did_some_progress && pm_suspended_storage())
2157 return 0;
2158
11e33f6a
MG
2159 /*
2160 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
2161 * means __GFP_NOFAIL, but that may not be true in other
2162 * implementations.
2163 */
2164 if (order <= PAGE_ALLOC_COSTLY_ORDER)
2165 return 1;
2166
2167 /*
2168 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
2169 * specified, then we retry until we no longer reclaim any pages
2170 * (above), or we've reclaimed an order of pages at least as
2171 * large as the allocation's order. In both cases, if the
2172 * allocation still fails, we stop retrying.
2173 */
2174 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
2175 return 1;
cf40bd16 2176
11e33f6a
MG
2177 return 0;
2178}
933e312e 2179
11e33f6a
MG
2180static inline struct page *
2181__alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2182 struct zonelist *zonelist, enum zone_type high_zoneidx,
3dd28266
MG
2183 nodemask_t *nodemask, struct zone *preferred_zone,
2184 int migratetype)
11e33f6a
MG
2185{
2186 struct page *page;
2187
2188 /* Acquire the OOM killer lock for the zones in zonelist */
ff321fea 2189 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
11e33f6a 2190 schedule_timeout_uninterruptible(1);
1da177e4
LT
2191 return NULL;
2192 }
6b1de916 2193
11e33f6a
MG
2194 /*
2195 * Go through the zonelist yet one more time, keep very high watermark
2196 * here, this is only to catch a parallel oom killing, we must fail if
2197 * we're still under heavy pressure.
2198 */
2199 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2200 order, zonelist, high_zoneidx,
5117f45d 2201 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
3dd28266 2202 preferred_zone, migratetype);
7fb1d9fc 2203 if (page)
11e33f6a
MG
2204 goto out;
2205
4365a567
KH
2206 if (!(gfp_mask & __GFP_NOFAIL)) {
2207 /* The OOM killer will not help higher order allocs */
2208 if (order > PAGE_ALLOC_COSTLY_ORDER)
2209 goto out;
03668b3c
DR
2210 /* The OOM killer does not needlessly kill tasks for lowmem */
2211 if (high_zoneidx < ZONE_NORMAL)
2212 goto out;
4365a567
KH
2213 /*
2214 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2215 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2216 * The caller should handle page allocation failure by itself if
2217 * it specifies __GFP_THISNODE.
2218 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2219 */
2220 if (gfp_mask & __GFP_THISNODE)
2221 goto out;
2222 }
11e33f6a 2223 /* Exhausted what can be done so it's blamo time */
08ab9b10 2224 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
11e33f6a
MG
2225
2226out:
2227 clear_zonelist_oom(zonelist, gfp_mask);
2228 return page;
2229}
2230
56de7263
MG
2231#ifdef CONFIG_COMPACTION
2232/* Try memory compaction for high-order allocations before reclaim */
2233static struct page *
2234__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2235 struct zonelist *zonelist, enum zone_type high_zoneidx,
2236 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
66199712 2237 int migratetype, bool sync_migration,
c67fe375 2238 bool *contended_compaction, bool *deferred_compaction,
66199712 2239 unsigned long *did_some_progress)
56de7263 2240{
66199712 2241 if (!order)
56de7263
MG
2242 return NULL;
2243
aff62249 2244 if (compaction_deferred(preferred_zone, order)) {
66199712
MG
2245 *deferred_compaction = true;
2246 return NULL;
2247 }
2248
c06b1fca 2249 current->flags |= PF_MEMALLOC;
56de7263 2250 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
c67fe375 2251 nodemask, sync_migration,
8fb74b9f 2252 contended_compaction);
c06b1fca 2253 current->flags &= ~PF_MEMALLOC;
56de7263 2254
1fb3f8ca 2255 if (*did_some_progress != COMPACT_SKIPPED) {
8fb74b9f
MG
2256 struct page *page;
2257
56de7263
MG
2258 /* Page migration frees to the PCP lists but we want merging */
2259 drain_pages(get_cpu());
2260 put_cpu();
2261
2262 page = get_page_from_freelist(gfp_mask, nodemask,
2263 order, zonelist, high_zoneidx,
cfd19c5a
MG
2264 alloc_flags & ~ALLOC_NO_WATERMARKS,
2265 preferred_zone, migratetype);
56de7263 2266 if (page) {
62997027 2267 preferred_zone->compact_blockskip_flush = false;
4f92e258
MG
2268 preferred_zone->compact_considered = 0;
2269 preferred_zone->compact_defer_shift = 0;
aff62249
RR
2270 if (order >= preferred_zone->compact_order_failed)
2271 preferred_zone->compact_order_failed = order + 1;
56de7263
MG
2272 count_vm_event(COMPACTSUCCESS);
2273 return page;
2274 }
2275
2276 /*
2277 * It's bad if compaction run occurs and fails.
2278 * The most likely reason is that pages exist,
2279 * but not enough to satisfy watermarks.
2280 */
2281 count_vm_event(COMPACTFAIL);
66199712
MG
2282
2283 /*
2284 * As async compaction considers a subset of pageblocks, only
2285 * defer if the failure was a sync compaction failure.
2286 */
2287 if (sync_migration)
aff62249 2288 defer_compaction(preferred_zone, order);
56de7263
MG
2289
2290 cond_resched();
2291 }
2292
2293 return NULL;
2294}
2295#else
2296static inline struct page *
2297__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2298 struct zonelist *zonelist, enum zone_type high_zoneidx,
2299 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
66199712 2300 int migratetype, bool sync_migration,
c67fe375 2301 bool *contended_compaction, bool *deferred_compaction,
66199712 2302 unsigned long *did_some_progress)
56de7263
MG
2303{
2304 return NULL;
2305}
2306#endif /* CONFIG_COMPACTION */
2307
bba90710
MS
2308/* Perform direct synchronous page reclaim */
2309static int
2310__perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2311 nodemask_t *nodemask)
11e33f6a 2312{
11e33f6a 2313 struct reclaim_state reclaim_state;
bba90710 2314 int progress;
11e33f6a
MG
2315
2316 cond_resched();
2317
2318 /* We now go into synchronous reclaim */
2319 cpuset_memory_pressure_bump();
c06b1fca 2320 current->flags |= PF_MEMALLOC;
11e33f6a
MG
2321 lockdep_set_current_reclaim_state(gfp_mask);
2322 reclaim_state.reclaimed_slab = 0;
c06b1fca 2323 current->reclaim_state = &reclaim_state;
11e33f6a 2324
bba90710 2325 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
11e33f6a 2326
c06b1fca 2327 current->reclaim_state = NULL;
11e33f6a 2328 lockdep_clear_current_reclaim_state();
c06b1fca 2329 current->flags &= ~PF_MEMALLOC;
11e33f6a
MG
2330
2331 cond_resched();
2332
bba90710
MS
2333 return progress;
2334}
2335
2336/* The really slow allocator path where we enter direct reclaim */
2337static inline struct page *
2338__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2339 struct zonelist *zonelist, enum zone_type high_zoneidx,
2340 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2341 int migratetype, unsigned long *did_some_progress)
2342{
2343 struct page *page = NULL;
2344 bool drained = false;
2345
2346 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2347 nodemask);
9ee493ce
MG
2348 if (unlikely(!(*did_some_progress)))
2349 return NULL;
11e33f6a 2350
76d3fbf8 2351 /* After successful reclaim, reconsider all zones for allocation */
e5adfffc 2352 if (IS_ENABLED(CONFIG_NUMA))
76d3fbf8
MG
2353 zlc_clear_zones_full(zonelist);
2354
9ee493ce
MG
2355retry:
2356 page = get_page_from_freelist(gfp_mask, nodemask, order,
5117f45d 2357 zonelist, high_zoneidx,
cfd19c5a
MG
2358 alloc_flags & ~ALLOC_NO_WATERMARKS,
2359 preferred_zone, migratetype);
9ee493ce
MG
2360
2361 /*
2362 * If an allocation failed after direct reclaim, it could be because
2363 * pages are pinned on the per-cpu lists. Drain them and try again
2364 */
2365 if (!page && !drained) {
2366 drain_all_pages();
2367 drained = true;
2368 goto retry;
2369 }
2370
11e33f6a
MG
2371 return page;
2372}
2373
1da177e4 2374/*
11e33f6a
MG
2375 * This is called in the allocator slow-path if the allocation request is of
2376 * sufficient urgency to ignore watermarks and take other desperate measures
1da177e4 2377 */
11e33f6a
MG
2378static inline struct page *
2379__alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2380 struct zonelist *zonelist, enum zone_type high_zoneidx,
3dd28266
MG
2381 nodemask_t *nodemask, struct zone *preferred_zone,
2382 int migratetype)
11e33f6a
MG
2383{
2384 struct page *page;
2385
2386 do {
2387 page = get_page_from_freelist(gfp_mask, nodemask, order,
5117f45d 2388 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
3dd28266 2389 preferred_zone, migratetype);
11e33f6a
MG
2390
2391 if (!page && gfp_mask & __GFP_NOFAIL)
0e093d99 2392 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
11e33f6a
MG
2393 } while (!page && (gfp_mask & __GFP_NOFAIL));
2394
2395 return page;
2396}
2397
2398static inline
2399void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
99504748
MG
2400 enum zone_type high_zoneidx,
2401 enum zone_type classzone_idx)
1da177e4 2402{
dd1a239f
MG
2403 struct zoneref *z;
2404 struct zone *zone;
1da177e4 2405
11e33f6a 2406 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
99504748 2407 wakeup_kswapd(zone, order, classzone_idx);
11e33f6a 2408}
cf40bd16 2409
341ce06f
PZ
2410static inline int
2411gfp_to_alloc_flags(gfp_t gfp_mask)
2412{
341ce06f 2413 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
1144d70b 2414 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
1da177e4 2415
a56f57ff 2416 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
e6223a3b 2417 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
933e312e 2418
341ce06f
PZ
2419 /*
2420 * The caller may dip into page reserves a bit more if the caller
2421 * cannot run direct reclaim, or if the caller has realtime scheduling
2422 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1144d70b 2423 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
341ce06f 2424 */
e6223a3b 2425 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
1da177e4 2426
1144d70b 2427 if (atomic) {
5c3240d9 2428 /*
1144d70b
DR
2429 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2430 * if it can't schedule.
5c3240d9 2431 */
1144d70b 2432 if (!(gfp_mask & __GFP_NOMEMALLOC))
5c3240d9 2433 alloc_flags |= ALLOC_HARDER;
523b9458 2434 /*
1144d70b
DR
2435 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2436 * comment for __cpuset_node_allowed_softwall().
523b9458 2437 */
341ce06f 2438 alloc_flags &= ~ALLOC_CPUSET;
c06b1fca 2439 } else if (unlikely(rt_task(current)) && !in_interrupt())
341ce06f
PZ
2440 alloc_flags |= ALLOC_HARDER;
2441
b37f1dd0
MG
2442 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2443 if (gfp_mask & __GFP_MEMALLOC)
2444 alloc_flags |= ALLOC_NO_WATERMARKS;
907aed48
MG
2445 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2446 alloc_flags |= ALLOC_NO_WATERMARKS;
2447 else if (!in_interrupt() &&
2448 ((current->flags & PF_MEMALLOC) ||
2449 unlikely(test_thread_flag(TIF_MEMDIE))))
341ce06f 2450 alloc_flags |= ALLOC_NO_WATERMARKS;
1da177e4 2451 }
d95ea5d1
BZ
2452#ifdef CONFIG_CMA
2453 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2454 alloc_flags |= ALLOC_CMA;
2455#endif
341ce06f
PZ
2456 return alloc_flags;
2457}
2458
072bb0aa
MG
2459bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2460{
b37f1dd0 2461 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
072bb0aa
MG
2462}
2463
6fa3eb70
S
2464/* Add for kswapd need too much CPU ANR issue */
2465#ifdef CONFIG_MT_ENG_BUILD
2466static uint32_t wakeup_kswapd_count = 0;
2467static unsigned long print_wakeup_kswapd_timeout = 0;
2468
2469static uint32_t wakeup_kswapd_dump_log_order = 1;
2470static uint32_t wakeup_kswapd_dump_bt_order = 1000;
2471
2472module_param_named(dump_log_order, wakeup_kswapd_dump_log_order, uint, S_IRUGO | S_IWUSR);
2473module_param_named(dump_bt_order, wakeup_kswapd_dump_bt_order, uint, S_IRUGO | S_IWUSR);
2474#endif
2475
11e33f6a
MG
2476static inline struct page *
2477__alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2478 struct zonelist *zonelist, enum zone_type high_zoneidx,
3dd28266
MG
2479 nodemask_t *nodemask, struct zone *preferred_zone,
2480 int migratetype)
11e33f6a
MG
2481{
2482 const gfp_t wait = gfp_mask & __GFP_WAIT;
2483 struct page *page = NULL;
2484 int alloc_flags;
2485 unsigned long pages_reclaimed = 0;
2486 unsigned long did_some_progress;
77f1fe6b 2487 bool sync_migration = false;
66199712 2488 bool deferred_compaction = false;
c67fe375 2489 bool contended_compaction = false;
1da177e4 2490
72807a74
MG
2491 /*
2492 * In the slowpath, we sanity check order to avoid ever trying to
2493 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2494 * be using allocators in order of preference for an area that is
2495 * too large.
2496 */
1fc28b70
MG
2497 if (order >= MAX_ORDER) {
2498 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
72807a74 2499 return NULL;
1fc28b70 2500 }
1da177e4 2501
952f3b51
CL
2502 /*
2503 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2504 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2505 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2506 * using a larger set of nodes after it has established that the
2507 * allowed per node queues are empty and that nodes are
2508 * over allocated.
2509 */
e5adfffc
KS
2510 if (IS_ENABLED(CONFIG_NUMA) &&
2511 (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
952f3b51
CL
2512 goto nopage;
2513
cc4a6851 2514restart:
6fa3eb70
S
2515 if (!(gfp_mask & __GFP_NO_KSWAPD)) {
2516 #ifdef CONFIG_MT_ENG_BUILD
2517 int print_debug_info = 0;
2518 wakeup_kswapd_count++;
2519
2520 if (time_after_eq(jiffies, print_wakeup_kswapd_timeout)) {
2521 print_debug_info = 1;
2522 print_wakeup_kswapd_timeout = jiffies+HZ;
2523 }
2524 if(print_debug_info) {
2525 if(order >= wakeup_kswapd_dump_log_order) {
2526 pr_debug("[WAKEUP_KSWAPD]%s wakeup kswapd, order:%d, mode:0x%x, trigger_count:%d\n",
2527 current->comm, order, gfp_mask, wakeup_kswapd_count);
2528 }
2529
2530 if(order >= wakeup_kswapd_dump_bt_order) {
2531 pr_debug("[WAKEUP_KSWAPD]dump_stack\n");
2532 dump_stack();
2533 }
2534 wakeup_kswapd_count = 0;/*reset*/
2535 }
2536 #endif
caf49191
LT
2537 wake_all_kswapd(order, zonelist, high_zoneidx,
2538 zone_idx(preferred_zone));
6fa3eb70 2539 }
9bf2229f 2540 /*
7fb1d9fc
RS
2541 * OK, we're below the kswapd watermark and have kicked background
2542 * reclaim. Now things get more complex, so set up alloc_flags according
2543 * to how we want to proceed.
9bf2229f 2544 */
341ce06f 2545 alloc_flags = gfp_to_alloc_flags(gfp_mask);
1da177e4 2546
f33261d7
DR
2547 /*
2548 * Find the true preferred zone if the allocation is unconstrained by
2549 * cpusets.
2550 */
2551 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask)
2552 first_zones_zonelist(zonelist, high_zoneidx, NULL,
2553 &preferred_zone);
2554
cfa54a0f 2555rebalance:
341ce06f 2556 /* This is the last chance, in general, before the goto nopage. */
19770b32 2557 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
341ce06f
PZ
2558 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2559 preferred_zone, migratetype);
7fb1d9fc
RS
2560 if (page)
2561 goto got_pg;
1da177e4 2562
11e33f6a 2563 /* Allocate without watermarks if the context allows */
341ce06f 2564 if (alloc_flags & ALLOC_NO_WATERMARKS) {
183f6371
MG
2565 /*
2566 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
2567 * the allocation is high priority and these type of
2568 * allocations are system rather than user orientated
2569 */
2570 zonelist = node_zonelist(numa_node_id(), gfp_mask);
2571
341ce06f
PZ
2572 page = __alloc_pages_high_priority(gfp_mask, order,
2573 zonelist, high_zoneidx, nodemask,
2574 preferred_zone, migratetype);
cfd19c5a 2575 if (page) {
341ce06f 2576 goto got_pg;
cfd19c5a 2577 }
1da177e4
LT
2578 }
2579
2580 /* Atomic allocations - we can't balance anything */
2581 if (!wait)
2582 goto nopage;
2583
341ce06f 2584 /* Avoid recursion of direct reclaim */
c06b1fca 2585 if (current->flags & PF_MEMALLOC)
341ce06f
PZ
2586 goto nopage;
2587
6583bb64
DR
2588 /* Avoid allocations with no watermarks from looping endlessly */
2589 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2590 goto nopage;
2591
77f1fe6b
MG
2592 /*
2593 * Try direct compaction. The first pass is asynchronous. Subsequent
2594 * attempts after direct reclaim are synchronous
2595 */
56de7263
MG
2596 page = __alloc_pages_direct_compact(gfp_mask, order,
2597 zonelist, high_zoneidx,
2598 nodemask,
2599 alloc_flags, preferred_zone,
66199712 2600 migratetype, sync_migration,
c67fe375 2601 &contended_compaction,
66199712
MG
2602 &deferred_compaction,
2603 &did_some_progress);
56de7263
MG
2604 if (page)
2605 goto got_pg;
c6a140bf 2606 sync_migration = true;
56de7263 2607
31f8d42d
LT
2608 /*
2609 * If compaction is deferred for high-order allocations, it is because
2610 * sync compaction recently failed. In this is the case and the caller
2611 * requested a movable allocation that does not heavily disrupt the
2612 * system then fail the allocation instead of entering direct reclaim.
2613 */
2614 if ((deferred_compaction || contended_compaction) &&
caf49191 2615 (gfp_mask & __GFP_NO_KSWAPD))
31f8d42d 2616 goto nopage;
66199712 2617
11e33f6a
MG
2618 /* Try direct reclaim and then allocating */
2619 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2620 zonelist, high_zoneidx,
2621 nodemask,
5117f45d 2622 alloc_flags, preferred_zone,
3dd28266 2623 migratetype, &did_some_progress);
11e33f6a
MG
2624 if (page)
2625 goto got_pg;
1da177e4 2626
e33c3b5e 2627 /*
11e33f6a
MG
2628 * If we failed to make any progress reclaiming, then we are
2629 * running out of options and have to consider going OOM
e33c3b5e 2630 */
11e33f6a
MG
2631 if (!did_some_progress) {
2632 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
7f33d49a
RW
2633 if (oom_killer_disabled)
2634 goto nopage;
29fd66d2
DR
2635 /* Coredumps can quickly deplete all memory reserves */
2636 if ((current->flags & PF_DUMPCORE) &&
2637 !(gfp_mask & __GFP_NOFAIL))
2638 goto nopage;
11e33f6a
MG
2639 page = __alloc_pages_may_oom(gfp_mask, order,
2640 zonelist, high_zoneidx,
3dd28266
MG
2641 nodemask, preferred_zone,
2642 migratetype);
11e33f6a
MG
2643 if (page)
2644 goto got_pg;
1da177e4 2645
03668b3c
DR
2646 if (!(gfp_mask & __GFP_NOFAIL)) {
2647 /*
2648 * The oom killer is not called for high-order
2649 * allocations that may fail, so if no progress
2650 * is being made, there are no other options and
2651 * retrying is unlikely to help.
2652 */
2653 if (order > PAGE_ALLOC_COSTLY_ORDER)
2654 goto nopage;
2655 /*
2656 * The oom killer is not called for lowmem
2657 * allocations to prevent needlessly killing
2658 * innocent tasks.
2659 */
2660 if (high_zoneidx < ZONE_NORMAL)
2661 goto nopage;
2662 }
e2c55dc8 2663
ff0ceb9d
DR
2664 goto restart;
2665 }
1da177e4
LT
2666 }
2667
11e33f6a 2668 /* Check if we should retry the allocation */
a41f24ea 2669 pages_reclaimed += did_some_progress;
f90ac398
MG
2670 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2671 pages_reclaimed)) {
11e33f6a 2672 /* Wait for some write requests to complete then retry */
0e093d99 2673 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
1da177e4 2674 goto rebalance;
3e7d3449
MG
2675 } else {
2676 /*
2677 * High-order allocations do not necessarily loop after
2678 * direct reclaim and reclaim/compaction depends on compaction
2679 * being called after reclaim so call directly if necessary
2680 */
2681 page = __alloc_pages_direct_compact(gfp_mask, order,
2682 zonelist, high_zoneidx,
2683 nodemask,
2684 alloc_flags, preferred_zone,
66199712 2685 migratetype, sync_migration,
c67fe375 2686 &contended_compaction,
66199712
MG
2687 &deferred_compaction,
2688 &did_some_progress);
3e7d3449
MG
2689 if (page)
2690 goto got_pg;
1da177e4
LT
2691 }
2692
2693nopage:
a238ab5b 2694 warn_alloc_failed(gfp_mask, order, NULL);
b1eeab67 2695 return page;
1da177e4 2696got_pg:
b1eeab67
VN
2697 if (kmemcheck_enabled)
2698 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
11e33f6a 2699
072bb0aa 2700 return page;
1da177e4 2701}
11e33f6a 2702
6fa3eb70
S
2703#ifdef CONFIG_MTKPASR
2704extern void try_to_release_mtkpasr_page(int x);
2705#else
2706#define try_to_release_mtkpasr_page(x) do {} while (0)
2707#endif
2708
2709#ifdef CONFIG_MT_ENG_BUILD
2710
2711#define __LOG_PAGE_ALLOC_ORDER__
2712#define __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2713#endif
2714
2715#ifdef __LOG_PAGE_ALLOC_ORDER__
2716
2717#define LOG_PAGE_LIMIT_NUM 10
2718#define LOG_PAGE_LIMIT_TIME 1000
2719
2720//static int page_alloc_order_log[11] = {0};
2721//static int page_alloc_order_log_size = 11;
2722static int page_alloc_dump_order_threshold = 4;
2723static int page_alloc_log_order_threshold = 3;
2724static u8 log_counter = 0;
2725static unsigned long log_time_c0 = 0;
2726static u8 log_limit_enable = 0;
2727
2728//module_param_array_named(order_log, page_alloc_order_log, int, &page_alloc_order_log_size,
2729// S_IRUGO);
2730//Jack remove page_alloc_order_log array for non-used
2731module_param_named(dump_order_threshold, page_alloc_dump_order_threshold, int, S_IRUGO | S_IWUSR);
2732module_param_named(log_order_threshold, page_alloc_log_order_threshold, int, S_IRUGO | S_IWUSR);
2733#endif // __LOG_PAGE_ALLOC_ORDER__
2734
11e33f6a
MG
2735/*
2736 * This is the 'heart' of the zoned buddy allocator.
2737 */
2738struct page *
2739__alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2740 struct zonelist *zonelist, nodemask_t *nodemask)
2741{
2742 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
5117f45d 2743 struct zone *preferred_zone;
cc9a6c87 2744 struct page *page = NULL;
3dd28266 2745 int migratetype = allocflags_to_migratetype(gfp_mask);
cc9a6c87 2746 unsigned int cpuset_mems_cookie;
d95ea5d1 2747 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET;
6a1a0d3b 2748 struct mem_cgroup *memcg = NULL;
11e33f6a 2749
dcce284a
BH
2750 gfp_mask &= gfp_allowed_mask;
2751
11e33f6a
MG
2752 lockdep_trace_alloc(gfp_mask);
2753
2754 might_sleep_if(gfp_mask & __GFP_WAIT);
2755
2756 if (should_fail_alloc_page(gfp_mask, order))
2757 return NULL;
2758
2759 /*
2760 * Check the zones suitable for the gfp_mask contain at least one
2761 * valid zone. It's possible to have an empty zonelist as a result
2762 * of GFP_THISNODE and a memoryless node
2763 */
2764 if (unlikely(!zonelist->_zonerefs->zone))
2765 return NULL;
2766
6a1a0d3b
GC
2767 /*
2768 * Will only have any effect when __GFP_KMEMCG is set. This is
2769 * verified in the (always inline) callee
2770 */
2771 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2772 return NULL;
2773
cc9a6c87
MG
2774retry_cpuset:
2775 cpuset_mems_cookie = get_mems_allowed();
2776
5117f45d 2777 /* The preferred zone is used for statistics later */
f33261d7
DR
2778 first_zones_zonelist(zonelist, high_zoneidx,
2779 nodemask ? : &cpuset_current_mems_allowed,
2780 &preferred_zone);
cc9a6c87
MG
2781 if (!preferred_zone)
2782 goto out;
5117f45d 2783
d95ea5d1
BZ
2784#ifdef CONFIG_CMA
2785 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2786 alloc_flags |= ALLOC_CMA;
2787#endif
6fa3eb70
S
2788
2789#ifdef CONFIG_MTKPASR
2790 /* Speed up allocation for MIGRATE_MOVABLE */
2791#ifdef CONFIG_HIGHMEM
2792 if (high_zoneidx >= ZONE_HIGHMEM) {
2793#endif
2794 if (migratetype == MIGRATE_MOVABLE) {
2795 migratetype = preferred_mt;
2796 }
2797#ifdef CONFIG_HIGHMEM
2798 }
2799#endif
2800#endif
2801
5117f45d 2802 /* First allocation attempt */
11e33f6a 2803 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
d95ea5d1 2804 zonelist, high_zoneidx, alloc_flags,
3dd28266 2805 preferred_zone, migratetype);
21caf2fc
ML
2806 if (unlikely(!page)) {
2807 /*
2808 * Runtime PM, block IO and its error handling path
2809 * can deadlock because I/O on the device might not
2810 * complete.
2811 */
2812 gfp_mask = memalloc_noio_flags(gfp_mask);
6fa3eb70
S
2813 if (gfp_mask & __GFP_SLOWHIGHMEM) {
2814 // setup highmem flag for slowhighmem
2815 gfp_mask |= __GFP_HIGHMEM;
2816 high_zoneidx = gfp_zone(gfp_mask);
2817 first_zones_zonelist(zonelist, high_zoneidx,
2818 nodemask ? : &cpuset_current_mems_allowed,
2819 &preferred_zone);
2820 if (!preferred_zone)
2821 goto out;
2822 }
2823
2824 /* Check whether we should release PASR reserved page */
2825 if (gfp_mask & __GFP_NOMTKPASR) {
2826 /* Do nothing, just go ahead */
2827 } else {
2828#ifdef CONFIG_HIGHMEM
2829 if (high_zoneidx >= ZONE_HIGHMEM) {
2830#endif
2831 try_to_release_mtkpasr_page(order);
2832 migratetype = preferred_mt;
2833#ifdef CONFIG_HIGHMEM
2834 }
2835#endif
2836 }
2837
11e33f6a 2838 page = __alloc_pages_slowpath(gfp_mask, order,
5117f45d 2839 zonelist, high_zoneidx, nodemask,
3dd28266 2840 preferred_zone, migratetype);
21caf2fc 2841 }
11e33f6a 2842
6fa3eb70
S
2843
2844#ifdef __LOG_PAGE_ALLOC_ORDER__
2845
2846#ifdef CONFIG_FREEZER //Added skip debug log in IPOH
2847 if (unlikely(!atomic_read(&system_freezing_cnt)))
2848 {
2849#endif
2850
2851 //page_alloc_order_log[order] += 1;
2852 // Enable the log in system server when boot completes
2853 if (order >= page_alloc_log_order_threshold) {
2854
2855
2856 if (log_counter == 0)
2857 {
2858 log_time_c0 = jiffies;
2859 }
2860 if (log_limit_enable == 0)
2861 {
2862 //printk("caller api is %p \r\n",__builtin_return_address(0));
2863 //printk_ratelimit()
2864#ifdef __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2865 printk("alloc large continuous pages, order: %d, gfp_mask = 0x%x, printk_ratelimit() = %d\n", order,gfp_mask,printk_ratelimit());
2866#else
2867 if (printk_ratelimit())
2868 printk("alloc large continuous pages, order: %d, gfp_mask = 0x%x, printk_ratelimit() = %d\n", order,gfp_mask,printk_ratelimit());
2869 //else
2870 // printk("alloc large cprintk_ratelimit() = 0 !!\n");
2871#endif
2872
2873 //printk("log_time_c0 = %d ms, jiffies = %d ms ",jiffies_to_msecs(log_time_c0),jiffies_to_msecs(jiffies));
2874 //printk("jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0) = %d ms",jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0));
2875
2876 }
2877#ifdef __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2878
2879 if (jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0) < LOG_PAGE_LIMIT_TIME)
2880 {
2881 log_counter++;
2882 if (log_limit_enable == 0)
2883 {
2884 if (log_counter > LOG_PAGE_LIMIT_NUM)
2885 {
2886 log_limit_enable = 1;
2887 printk("alloc page log limit enable, log_counter = %d!!\n",log_counter);
2888 }
2889 }
2890
2891 }
2892 else
2893 {
2894 if (log_limit_enable != 0)
2895 {
2896 printk("alloc page log limit disable!!\n");
2897 log_limit_enable = 0;
2898 }
2899 log_counter = 0;
2900
2901
2902 }
2903#endif
2904
2905 }
2906
2907 if (order >= page_alloc_dump_order_threshold) {
2908
2909 if (log_limit_enable == 0)
2910 dump_stack();
2911 }
2912
2913#ifdef CONFIG_FREEZER
2914 }
2915#endif
2916
2917#endif // __LOG_PAGE_ALLOC_ORDER__
4b4f278c 2918 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
cc9a6c87
MG
2919
2920out:
2921 /*
2922 * When updating a task's mems_allowed, it is possible to race with
2923 * parallel threads in such a way that an allocation can fail while
2924 * the mask is being updated. If a page allocation is about to fail,
2925 * check if the cpuset changed during allocation and if so, retry.
2926 */
2927 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !page))
2928 goto retry_cpuset;
2929
6a1a0d3b
GC
2930 memcg_kmem_commit_charge(page, memcg, order);
2931
11e33f6a 2932 return page;
1da177e4 2933}
d239171e 2934EXPORT_SYMBOL(__alloc_pages_nodemask);
1da177e4
LT
2935
2936/*
2937 * Common helper functions.
2938 */
920c7a5d 2939unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1da177e4 2940{
945a1113
AM
2941 struct page *page;
2942
2943 /*
2944 * __get_free_pages() returns a 32-bit address, which cannot represent
2945 * a highmem page
2946 */
2947 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2948
1da177e4
LT
2949 page = alloc_pages(gfp_mask, order);
2950 if (!page)
2951 return 0;
2952 return (unsigned long) page_address(page);
2953}
1da177e4
LT
2954EXPORT_SYMBOL(__get_free_pages);
2955
920c7a5d 2956unsigned long get_zeroed_page(gfp_t gfp_mask)
1da177e4 2957{
945a1113 2958 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
1da177e4 2959}
1da177e4
LT
2960EXPORT_SYMBOL(get_zeroed_page);
2961
920c7a5d 2962void __free_pages(struct page *page, unsigned int order)
1da177e4 2963{
b5810039 2964 if (put_page_testzero(page)) {
1da177e4 2965 if (order == 0)
fc91668e 2966 free_hot_cold_page(page, 0);
1da177e4
LT
2967 else
2968 __free_pages_ok(page, order);
2969 }
2970}
2971
2972EXPORT_SYMBOL(__free_pages);
2973
920c7a5d 2974void free_pages(unsigned long addr, unsigned int order)
1da177e4
LT
2975{
2976 if (addr != 0) {
725d704e 2977 VM_BUG_ON(!virt_addr_valid((void *)addr));
1da177e4
LT
2978 __free_pages(virt_to_page((void *)addr), order);
2979 }
2980}
2981
2982EXPORT_SYMBOL(free_pages);
2983
6a1a0d3b
GC
2984/*
2985 * __free_memcg_kmem_pages and free_memcg_kmem_pages will free
2986 * pages allocated with __GFP_KMEMCG.
2987 *
2988 * Those pages are accounted to a particular memcg, embedded in the
2989 * corresponding page_cgroup. To avoid adding a hit in the allocator to search
2990 * for that information only to find out that it is NULL for users who have no
2991 * interest in that whatsoever, we provide these functions.
2992 *
2993 * The caller knows better which flags it relies on.
2994 */
2995void __free_memcg_kmem_pages(struct page *page, unsigned int order)
2996{
2997 memcg_kmem_uncharge_pages(page, order);
6fa3eb70 2998#ifndef CONFIG_MTK_PAGERECORDER
6a1a0d3b 2999 __free_pages(page, order);
6fa3eb70
S
3000#else
3001 __free_pages_nopagedebug(page, order);
3002#endif
6a1a0d3b
GC
3003}
3004
3005void free_memcg_kmem_pages(unsigned long addr, unsigned int order)
3006{
3007 if (addr != 0) {
3008 VM_BUG_ON(!virt_addr_valid((void *)addr));
3009 __free_memcg_kmem_pages(virt_to_page((void *)addr), order);
3010 }
3011}
3012
ee85c2e1
AK
3013static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
3014{
3015 if (addr) {
3016 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3017 unsigned long used = addr + PAGE_ALIGN(size);
3018
3019 split_page(virt_to_page((void *)addr), order);
3020 while (used < alloc_end) {
3021 free_page(used);
3022 used += PAGE_SIZE;
3023 }
3024 }
3025 return (void *)addr;
3026}
3027
2be0ffe2
TT
3028/**
3029 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3030 * @size: the number of bytes to allocate
3031 * @gfp_mask: GFP flags for the allocation
3032 *
3033 * This function is similar to alloc_pages(), except that it allocates the
3034 * minimum number of pages to satisfy the request. alloc_pages() can only
3035 * allocate memory in power-of-two pages.
3036 *
3037 * This function is also limited by MAX_ORDER.
3038 *
3039 * Memory allocated by this function must be released by free_pages_exact().
3040 */
3041void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3042{
3043 unsigned int order = get_order(size);
3044 unsigned long addr;
3045
3046 addr = __get_free_pages(gfp_mask, order);
ee85c2e1 3047 return make_alloc_exact(addr, order, size);
2be0ffe2
TT
3048}
3049EXPORT_SYMBOL(alloc_pages_exact);
3050
ee85c2e1
AK
3051/**
3052 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3053 * pages on a node.
b5e6ab58 3054 * @nid: the preferred node ID where memory should be allocated
ee85c2e1
AK
3055 * @size: the number of bytes to allocate
3056 * @gfp_mask: GFP flags for the allocation
3057 *
3058 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3059 * back.
3060 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
3061 * but is not exact.
3062 */
3063void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3064{
3065 unsigned order = get_order(size);
3066 struct page *p = alloc_pages_node(nid, gfp_mask, order);
3067 if (!p)
3068 return NULL;
3069 return make_alloc_exact((unsigned long)page_address(p), order, size);
3070}
3071EXPORT_SYMBOL(alloc_pages_exact_nid);
3072
2be0ffe2
TT
3073/**
3074 * free_pages_exact - release memory allocated via alloc_pages_exact()
3075 * @virt: the value returned by alloc_pages_exact.
3076 * @size: size of allocation, same value as passed to alloc_pages_exact().
3077 *
3078 * Release the memory allocated by a previous call to alloc_pages_exact.
3079 */
3080void free_pages_exact(void *virt, size_t size)
3081{
3082 unsigned long addr = (unsigned long)virt;
3083 unsigned long end = addr + PAGE_ALIGN(size);
3084
3085 while (addr < end) {
3086 free_page(addr);
3087 addr += PAGE_SIZE;
3088 }
3089}
3090EXPORT_SYMBOL(free_pages_exact);
3091
e0fb5815
ZY
3092/**
3093 * nr_free_zone_pages - count number of pages beyond high watermark
3094 * @offset: The zone index of the highest zone
3095 *
3096 * nr_free_zone_pages() counts the number of counts pages which are beyond the
3097 * high watermark within all zones at or below a given zone index. For each
3098 * zone, the number of pages is calculated as:
3099 * present_pages - high_pages
3100 */
ebec3862 3101static unsigned long nr_free_zone_pages(int offset)
1da177e4 3102{
dd1a239f 3103 struct zoneref *z;
54a6eb5c
MG
3104 struct zone *zone;
3105
e310fd43 3106 /* Just pick one node, since fallback list is circular */
ebec3862 3107 unsigned long sum = 0;
1da177e4 3108
0e88460d 3109 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
1da177e4 3110
54a6eb5c 3111 for_each_zone_zonelist(zone, z, zonelist, offset) {
b40da049 3112 unsigned long size = zone->managed_pages;
41858966 3113 unsigned long high = high_wmark_pages(zone);
e310fd43
MB
3114 if (size > high)
3115 sum += size - high;
1da177e4
LT
3116 }
3117
3118 return sum;
3119}
3120
6fa3eb70
S
3121static unsigned long nr_unallocated_zone_pages(int offset)
3122{
3123 struct zoneref *z;
3124 struct zone *zone;
3125
3126 /* Just pick one node, since fallback list is circular */
3127 unsigned long sum = 0;
3128
3129 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3130
3131 for_each_zone_zonelist(zone, z, zonelist, offset) {
3132 unsigned long high = high_wmark_pages(zone);
3133 unsigned long left = zone_page_state(zone, NR_FREE_PAGES);
3134 if (left > high)
3135 sum += left - high;
3136 }
3137
3138 return sum;
3139}
3140
e0fb5815
ZY
3141/**
3142 * nr_free_buffer_pages - count number of pages beyond high watermark
3143 *
3144 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3145 * watermark within ZONE_DMA and ZONE_NORMAL.
1da177e4 3146 */
ebec3862 3147unsigned long nr_free_buffer_pages(void)
1da177e4 3148{
af4ca457 3149 return nr_free_zone_pages(gfp_zone(GFP_USER));
1da177e4 3150}
c2f1a551 3151EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1da177e4 3152
6fa3eb70
S
3153/*
3154 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
3155 */
3156unsigned long nr_unallocated_buffer_pages(void)
3157{
3158 return nr_unallocated_zone_pages(gfp_zone(GFP_USER));
3159}
3160EXPORT_SYMBOL_GPL(nr_unallocated_buffer_pages);
3161
e0fb5815
ZY
3162/**
3163 * nr_free_pagecache_pages - count number of pages beyond high watermark
3164 *
3165 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3166 * high watermark within all zones.
1da177e4 3167 */
ebec3862 3168unsigned long nr_free_pagecache_pages(void)
1da177e4 3169{
2a1e274a 3170 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1da177e4 3171}
08e0f6a9
CL
3172
3173static inline void show_node(struct zone *zone)
1da177e4 3174{
e5adfffc 3175 if (IS_ENABLED(CONFIG_NUMA))
25ba77c1 3176 printk("Node %d ", zone_to_nid(zone));
1da177e4 3177}
1da177e4 3178
6fa3eb70
S
3179#ifdef CONFIG_MTKPASR
3180extern unsigned long mtkpasr_show_page_reserved(void);
3181#else
3182#define mtkpasr_show_page_reserved(void) (0)
3183#endif
1da177e4
LT
3184void si_meminfo(struct sysinfo *val)
3185{
3186 val->totalram = totalram_pages;
3187 val->sharedram = 0;
6fa3eb70 3188 val->freeram = global_page_state(NR_FREE_PAGES) + mtkpasr_show_page_reserved();
1da177e4 3189 val->bufferram = nr_blockdev_pages();
1da177e4
LT
3190 val->totalhigh = totalhigh_pages;
3191 val->freehigh = nr_free_highpages();
6fa3eb70
S
3192 if (IS_ENABLED(CONFIG_HIGHMEM)) {
3193 val->freehigh += mtkpasr_show_page_reserved();
3194 }
1da177e4
LT
3195 val->mem_unit = PAGE_SIZE;
3196}
3197
3198EXPORT_SYMBOL(si_meminfo);
3199
3200#ifdef CONFIG_NUMA
3201void si_meminfo_node(struct sysinfo *val, int nid)
3202{
3203 pg_data_t *pgdat = NODE_DATA(nid);
3204
3205 val->totalram = pgdat->node_present_pages;
d23ad423 3206 val->freeram = node_page_state(nid, NR_FREE_PAGES);
98d2b0eb 3207#ifdef CONFIG_HIGHMEM
b40da049 3208 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
d23ad423
CL
3209 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3210 NR_FREE_PAGES);
98d2b0eb
CL
3211#else
3212 val->totalhigh = 0;
3213 val->freehigh = 0;
3214#endif
1da177e4
LT
3215 val->mem_unit = PAGE_SIZE;
3216}
3217#endif
3218
ddd588b5 3219/*
7bf02ea2
DR
3220 * Determine whether the node should be displayed or not, depending on whether
3221 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
ddd588b5 3222 */
7bf02ea2 3223bool skip_free_areas_node(unsigned int flags, int nid)
ddd588b5
DR
3224{
3225 bool ret = false;
cc9a6c87 3226 unsigned int cpuset_mems_cookie;
ddd588b5
DR
3227
3228 if (!(flags & SHOW_MEM_FILTER_NODES))
3229 goto out;
3230
cc9a6c87
MG
3231 do {
3232 cpuset_mems_cookie = get_mems_allowed();
3233 ret = !node_isset(nid, cpuset_current_mems_allowed);
3234 } while (!put_mems_allowed(cpuset_mems_cookie));
ddd588b5
DR
3235out:
3236 return ret;
3237}
3238
1da177e4
LT
3239#define K(x) ((x) << (PAGE_SHIFT-10))
3240
377e4f16
RV
3241static void show_migration_types(unsigned char type)
3242{
3243 static const char types[MIGRATE_TYPES] = {
3244 [MIGRATE_UNMOVABLE] = 'U',
3245 [MIGRATE_RECLAIMABLE] = 'E',
3246 [MIGRATE_MOVABLE] = 'M',
3247 [MIGRATE_RESERVE] = 'R',
3248#ifdef CONFIG_CMA
3249 [MIGRATE_CMA] = 'C',
3250#endif
194159fb 3251#ifdef CONFIG_MEMORY_ISOLATION
377e4f16 3252 [MIGRATE_ISOLATE] = 'I',
194159fb 3253#endif
377e4f16
RV
3254 };
3255 char tmp[MIGRATE_TYPES + 1];
3256 char *p = tmp;
3257 int i;
3258
3259 for (i = 0; i < MIGRATE_TYPES; i++) {
3260 if (type & (1 << i))
3261 *p++ = types[i];
3262 }
3263
3264 *p = '\0';
3265 printk("(%s) ", tmp);
3266}
3267
1da177e4
LT
3268/*
3269 * Show free area list (used inside shift_scroll-lock stuff)
3270 * We also calculate the percentage fragmentation. We do this by counting the
3271 * memory on each free list with the exception of the first item on the list.
ddd588b5
DR
3272 * Suppresses nodes that are not allowed by current's cpuset if
3273 * SHOW_MEM_FILTER_NODES is passed.
1da177e4 3274 */
7bf02ea2 3275void show_free_areas(unsigned int filter)
1da177e4 3276{
c7241913 3277 int cpu;
1da177e4
LT
3278 struct zone *zone;
3279
ee99c71c 3280 for_each_populated_zone(zone) {
7bf02ea2 3281 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3282 continue;
c7241913
JS
3283 show_node(zone);
3284 printk("%s per-cpu:\n", zone->name);
1da177e4 3285
6b482c67 3286 for_each_online_cpu(cpu) {
1da177e4
LT
3287 struct per_cpu_pageset *pageset;
3288
99dcc3e5 3289 pageset = per_cpu_ptr(zone->pageset, cpu);
1da177e4 3290
3dfa5721
CL
3291 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
3292 cpu, pageset->pcp.high,
3293 pageset->pcp.batch, pageset->pcp.count);
1da177e4
LT
3294 }
3295 }
3296
a731286d
KM
3297 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3298 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
7b854121 3299 " unevictable:%lu"
b76146ed 3300 " dirty:%lu writeback:%lu unstable:%lu\n"
3701b033 3301 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
d1ce749a
BZ
3302 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3303 " free_cma:%lu\n",
4f98a2fe 3304 global_page_state(NR_ACTIVE_ANON),
4f98a2fe 3305 global_page_state(NR_INACTIVE_ANON),
a731286d
KM
3306 global_page_state(NR_ISOLATED_ANON),
3307 global_page_state(NR_ACTIVE_FILE),
4f98a2fe 3308 global_page_state(NR_INACTIVE_FILE),
a731286d 3309 global_page_state(NR_ISOLATED_FILE),
7b854121 3310 global_page_state(NR_UNEVICTABLE),
b1e7a8fd 3311 global_page_state(NR_FILE_DIRTY),
ce866b34 3312 global_page_state(NR_WRITEBACK),
fd39fc85 3313 global_page_state(NR_UNSTABLE_NFS),
d23ad423 3314 global_page_state(NR_FREE_PAGES),
3701b033
KM
3315 global_page_state(NR_SLAB_RECLAIMABLE),
3316 global_page_state(NR_SLAB_UNRECLAIMABLE),
65ba55f5 3317 global_page_state(NR_FILE_MAPPED),
4b02108a 3318 global_page_state(NR_SHMEM),
a25700a5 3319 global_page_state(NR_PAGETABLE),
d1ce749a
BZ
3320 global_page_state(NR_BOUNCE),
3321 global_page_state(NR_FREE_CMA_PAGES));
1da177e4 3322
ee99c71c 3323 for_each_populated_zone(zone) {
1da177e4
LT
3324 int i;
3325
7bf02ea2 3326 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3327 continue;
1da177e4
LT
3328 show_node(zone);
3329 printk("%s"
3330 " free:%lukB"
3331 " min:%lukB"
3332 " low:%lukB"
3333 " high:%lukB"
4f98a2fe
RR
3334 " active_anon:%lukB"
3335 " inactive_anon:%lukB"
3336 " active_file:%lukB"
3337 " inactive_file:%lukB"
7b854121 3338 " unevictable:%lukB"
a731286d
KM
3339 " isolated(anon):%lukB"
3340 " isolated(file):%lukB"
1da177e4 3341 " present:%lukB"
9feedc9d 3342 " managed:%lukB"
4a0aa73f
KM
3343 " mlocked:%lukB"
3344 " dirty:%lukB"
3345 " writeback:%lukB"
3346 " mapped:%lukB"
4b02108a 3347 " shmem:%lukB"
4a0aa73f
KM
3348 " slab_reclaimable:%lukB"
3349 " slab_unreclaimable:%lukB"
c6a7f572 3350 " kernel_stack:%lukB"
4a0aa73f
KM
3351 " pagetables:%lukB"
3352 " unstable:%lukB"
3353 " bounce:%lukB"
d1ce749a 3354 " free_cma:%lukB"
4a0aa73f 3355 " writeback_tmp:%lukB"
1da177e4
LT
3356 " pages_scanned:%lu"
3357 " all_unreclaimable? %s"
3358 "\n",
3359 zone->name,
88f5acf8 3360 K(zone_page_state(zone, NR_FREE_PAGES)),
41858966
MG
3361 K(min_wmark_pages(zone)),
3362 K(low_wmark_pages(zone)),
3363 K(high_wmark_pages(zone)),
4f98a2fe
RR
3364 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3365 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3366 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3367 K(zone_page_state(zone, NR_INACTIVE_FILE)),
7b854121 3368 K(zone_page_state(zone, NR_UNEVICTABLE)),
a731286d
KM
3369 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3370 K(zone_page_state(zone, NR_ISOLATED_FILE)),
1da177e4 3371 K(zone->present_pages),
9feedc9d 3372 K(zone->managed_pages),
4a0aa73f
KM
3373 K(zone_page_state(zone, NR_MLOCK)),
3374 K(zone_page_state(zone, NR_FILE_DIRTY)),
3375 K(zone_page_state(zone, NR_WRITEBACK)),
3376 K(zone_page_state(zone, NR_FILE_MAPPED)),
4b02108a 3377 K(zone_page_state(zone, NR_SHMEM)),
4a0aa73f
KM
3378 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3379 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
c6a7f572
KM
3380 zone_page_state(zone, NR_KERNEL_STACK) *
3381 THREAD_SIZE / 1024,
4a0aa73f
KM
3382 K(zone_page_state(zone, NR_PAGETABLE)),
3383 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3384 K(zone_page_state(zone, NR_BOUNCE)),
d1ce749a 3385 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
4a0aa73f 3386 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
1da177e4 3387 zone->pages_scanned,
93e4a89a 3388 (zone->all_unreclaimable ? "yes" : "no")
1da177e4
LT
3389 );
3390 printk("lowmem_reserve[]:");
3391 for (i = 0; i < MAX_NR_ZONES; i++)
3392 printk(" %lu", zone->lowmem_reserve[i]);
3393 printk("\n");
3394 }
3395
ee99c71c 3396 for_each_populated_zone(zone) {
8f9de51a 3397 unsigned long nr[MAX_ORDER], flags, order, total = 0;
377e4f16 3398 unsigned char types[MAX_ORDER];
1da177e4 3399
7bf02ea2 3400 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3401 continue;
1da177e4
LT
3402 show_node(zone);
3403 printk("%s: ", zone->name);
1da177e4
LT
3404
3405 spin_lock_irqsave(&zone->lock, flags);
3406 for (order = 0; order < MAX_ORDER; order++) {
377e4f16
RV
3407 struct free_area *area = &zone->free_area[order];
3408 int type;
3409
3410 nr[order] = area->nr_free;
8f9de51a 3411 total += nr[order] << order;
377e4f16
RV
3412
3413 types[order] = 0;
3414 for (type = 0; type < MIGRATE_TYPES; type++) {
3415 if (!list_empty(&area->free_list[type]))
3416 types[order] |= 1 << type;
3417 }
1da177e4
LT
3418 }
3419 spin_unlock_irqrestore(&zone->lock, flags);
377e4f16 3420 for (order = 0; order < MAX_ORDER; order++) {
8f9de51a 3421 printk("%lu*%lukB ", nr[order], K(1UL) << order);
377e4f16
RV
3422 if (nr[order])
3423 show_migration_types(types[order]);
3424 }
1da177e4
LT
3425 printk("= %lukB\n", K(total));
3426 }
3427
949f7ec5
DR
3428 hugetlb_show_meminfo();
3429
e6f3602d
LW
3430 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3431
1da177e4
LT
3432 show_swap_cache_info();
3433}
3434
6fa3eb70
S
3435void show_free_areas_minimum(void)
3436{
3437 struct zone *zone;
3438 for_each_populated_zone(zone) {
3439 if (skip_free_areas_node(SHOW_MEM_FILTER_NODES, zone_to_nid(zone)))
3440 continue;
3441 show_node(zone);
3442 printk("%s"
3443 " free:%lukB"
3444 " min:%lukB"
3445 " low:%lukB"
3446 " high:%lukB"
3447 " active_anon:%lukB"
3448 " inactive_anon:%lukB"
3449 " active_file:%lukB"
3450 " inactive_file:%lukB"
3451 " unevictable:%lukB"
3452 " isolated(anon):%lukB"
3453 " isolated(file):%lukB"
3454 " present:%lukB"
3455 " managed:%lukB"
3456 " mlocked:%lukB"
3457 " dirty:%lukB"
3458 " writeback:%lukB"
3459 " mapped:%lukB"
3460 " shmem:%lukB"
3461 " slab_reclaimable:%lukB"
3462 " slab_unreclaimable:%lukB"
3463 " kernel_stack:%lukB"
3464 " pagetables:%lukB"
3465 " unstable:%lukB"
3466 " bounce:%lukB"
3467 " free_cma:%lukB"
3468 " writeback_tmp:%lukB"
3469 " pages_scanned:%lu"
3470 " all_unreclaimable? %s"
3471 "\n",
3472 zone->name,
3473 K(zone_page_state(zone, NR_FREE_PAGES)),
3474 K(min_wmark_pages(zone)),
3475 K(low_wmark_pages(zone)),
3476 K(high_wmark_pages(zone)),
3477 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3478 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3479 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3480 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3481 K(zone_page_state(zone, NR_UNEVICTABLE)),
3482 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3483 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3484 K(zone->present_pages),
3485 K(zone->managed_pages),
3486 K(zone_page_state(zone, NR_MLOCK)),
3487 K(zone_page_state(zone, NR_FILE_DIRTY)),
3488 K(zone_page_state(zone, NR_WRITEBACK)),
3489 K(zone_page_state(zone, NR_FILE_MAPPED)),
3490 K(zone_page_state(zone, NR_SHMEM)),
3491 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3492 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3493 zone_page_state(zone, NR_KERNEL_STACK) *
3494 THREAD_SIZE / 1024,
3495 K(zone_page_state(zone, NR_PAGETABLE)),
3496 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3497 K(zone_page_state(zone, NR_BOUNCE)),
3498 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3499 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3500 zone->pages_scanned,
3501 (zone->all_unreclaimable ? "yes" : "no")
3502 );
3503 }
3504
3505 for_each_populated_zone(zone) {
3506 unsigned long nr[MAX_ORDER], flags, order, total = 0;
3507
3508 if (skip_free_areas_node(SHOW_MEM_FILTER_NODES, zone_to_nid(zone)))
3509 continue;
3510 show_node(zone);
3511 printk("%s: ", zone->name);
3512
3513 spin_lock_irqsave(&zone->lock, flags);
3514 for (order = 0; order < MAX_ORDER; order++) {
3515 nr[order] = zone->free_area[order].nr_free;
3516 total += nr[order] << order;
3517 }
3518 spin_unlock_irqrestore(&zone->lock, flags);
3519 for (order = 0; order < MAX_ORDER; order++)
3520 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3521 printk("= %lukB\n", K(total));
3522 }
3523}
3524EXPORT_SYMBOL(show_free_areas_minimum);
3525
19770b32
MG
3526static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3527{
3528 zoneref->zone = zone;
3529 zoneref->zone_idx = zone_idx(zone);
3530}
3531
1da177e4
LT
3532/*
3533 * Builds allocation fallback zone lists.
1a93205b
CL
3534 *
3535 * Add all populated zones of a node to the zonelist.
1da177e4 3536 */
f0c0b2b8
KH
3537static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3538 int nr_zones, enum zone_type zone_type)
1da177e4 3539{
1a93205b
CL
3540 struct zone *zone;
3541
98d2b0eb 3542 BUG_ON(zone_type >= MAX_NR_ZONES);
2f6726e5 3543 zone_type++;
02a68a5e
CL
3544
3545 do {
2f6726e5 3546 zone_type--;
070f8032 3547 zone = pgdat->node_zones + zone_type;
1a93205b 3548 if (populated_zone(zone)) {
dd1a239f
MG
3549 zoneref_set_zone(zone,
3550 &zonelist->_zonerefs[nr_zones++]);
070f8032 3551 check_highest_zone(zone_type);
1da177e4 3552 }
02a68a5e 3553
2f6726e5 3554 } while (zone_type);
070f8032 3555 return nr_zones;
1da177e4
LT
3556}
3557
f0c0b2b8
KH
3558
3559/*
3560 * zonelist_order:
3561 * 0 = automatic detection of better ordering.
3562 * 1 = order by ([node] distance, -zonetype)
3563 * 2 = order by (-zonetype, [node] distance)
3564 *
3565 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3566 * the same zonelist. So only NUMA can configure this param.
3567 */
3568#define ZONELIST_ORDER_DEFAULT 0
3569#define ZONELIST_ORDER_NODE 1
3570#define ZONELIST_ORDER_ZONE 2
3571
3572/* zonelist order in the kernel.
3573 * set_zonelist_order() will set this to NODE or ZONE.
3574 */
3575static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3576static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3577
3578
1da177e4 3579#ifdef CONFIG_NUMA
f0c0b2b8
KH
3580/* The value user specified ....changed by config */
3581static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3582/* string for sysctl */
3583#define NUMA_ZONELIST_ORDER_LEN 16
3584char numa_zonelist_order[16] = "default";
3585
3586/*
3587 * interface for configure zonelist ordering.
3588 * command line option "numa_zonelist_order"
3589 * = "[dD]efault - default, automatic configuration.
3590 * = "[nN]ode - order by node locality, then by zone within node
3591 * = "[zZ]one - order by zone, then by locality within zone
3592 */
3593
3594static int __parse_numa_zonelist_order(char *s)
3595{
3596 if (*s == 'd' || *s == 'D') {
3597 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3598 } else if (*s == 'n' || *s == 'N') {
3599 user_zonelist_order = ZONELIST_ORDER_NODE;
3600 } else if (*s == 'z' || *s == 'Z') {
3601 user_zonelist_order = ZONELIST_ORDER_ZONE;
3602 } else {
3603 printk(KERN_WARNING
3604 "Ignoring invalid numa_zonelist_order value: "
3605 "%s\n", s);
3606 return -EINVAL;
3607 }
3608 return 0;
3609}
3610
3611static __init int setup_numa_zonelist_order(char *s)
3612{
ecb256f8
VL
3613 int ret;
3614
3615 if (!s)
3616 return 0;
3617
3618 ret = __parse_numa_zonelist_order(s);
3619 if (ret == 0)
3620 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3621
3622 return ret;
f0c0b2b8
KH
3623}
3624early_param("numa_zonelist_order", setup_numa_zonelist_order);
3625
3626/*
3627 * sysctl handler for numa_zonelist_order
3628 */
3629int numa_zonelist_order_handler(ctl_table *table, int write,
8d65af78 3630 void __user *buffer, size_t *length,
f0c0b2b8
KH
3631 loff_t *ppos)
3632{
3633 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3634 int ret;
443c6f14 3635 static DEFINE_MUTEX(zl_order_mutex);
f0c0b2b8 3636
443c6f14 3637 mutex_lock(&zl_order_mutex);
f0c0b2b8 3638 if (write)
443c6f14 3639 strcpy(saved_string, (char*)table->data);
8d65af78 3640 ret = proc_dostring(table, write, buffer, length, ppos);
f0c0b2b8 3641 if (ret)
443c6f14 3642 goto out;
f0c0b2b8
KH
3643 if (write) {
3644 int oldval = user_zonelist_order;
3645 if (__parse_numa_zonelist_order((char*)table->data)) {
3646 /*
3647 * bogus value. restore saved string
3648 */
3649 strncpy((char*)table->data, saved_string,
3650 NUMA_ZONELIST_ORDER_LEN);
3651 user_zonelist_order = oldval;
4eaf3f64
HL
3652 } else if (oldval != user_zonelist_order) {
3653 mutex_lock(&zonelists_mutex);
9adb62a5 3654 build_all_zonelists(NULL, NULL);
4eaf3f64
HL
3655 mutex_unlock(&zonelists_mutex);
3656 }
f0c0b2b8 3657 }
443c6f14
AK
3658out:
3659 mutex_unlock(&zl_order_mutex);
3660 return ret;
f0c0b2b8
KH
3661}
3662
3663
62bc62a8 3664#define MAX_NODE_LOAD (nr_online_nodes)
f0c0b2b8
KH
3665static int node_load[MAX_NUMNODES];
3666
1da177e4 3667/**
4dc3b16b 3668 * find_next_best_node - find the next node that should appear in a given node's fallback list
1da177e4
LT
3669 * @node: node whose fallback list we're appending
3670 * @used_node_mask: nodemask_t of already used nodes
3671 *
3672 * We use a number of factors to determine which is the next node that should
3673 * appear on a given node's fallback list. The node should not have appeared
3674 * already in @node's fallback list, and it should be the next closest node
3675 * according to the distance array (which contains arbitrary distance values
3676 * from each node to each node in the system), and should also prefer nodes
3677 * with no CPUs, since presumably they'll have very little allocation pressure
3678 * on them otherwise.
3679 * It returns -1 if no node is found.
3680 */
f0c0b2b8 3681static int find_next_best_node(int node, nodemask_t *used_node_mask)
1da177e4 3682{
4cf808eb 3683 int n, val;
1da177e4 3684 int min_val = INT_MAX;
00ef2d2f 3685 int best_node = NUMA_NO_NODE;
a70f7302 3686 const struct cpumask *tmp = cpumask_of_node(0);
1da177e4 3687
4cf808eb
LT
3688 /* Use the local node if we haven't already */
3689 if (!node_isset(node, *used_node_mask)) {
3690 node_set(node, *used_node_mask);
3691 return node;
3692 }
1da177e4 3693
4b0ef1fe 3694 for_each_node_state(n, N_MEMORY) {
1da177e4
LT
3695
3696 /* Don't want a node to appear more than once */
3697 if (node_isset(n, *used_node_mask))
3698 continue;
3699
1da177e4
LT
3700 /* Use the distance array to find the distance */
3701 val = node_distance(node, n);
3702
4cf808eb
LT
3703 /* Penalize nodes under us ("prefer the next node") */
3704 val += (n < node);
3705
1da177e4 3706 /* Give preference to headless and unused nodes */
a70f7302
RR
3707 tmp = cpumask_of_node(n);
3708 if (!cpumask_empty(tmp))
1da177e4
LT
3709 val += PENALTY_FOR_NODE_WITH_CPUS;
3710
3711 /* Slight preference for less loaded node */
3712 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3713 val += node_load[n];
3714
3715 if (val < min_val) {
3716 min_val = val;
3717 best_node = n;
3718 }
3719 }
3720
3721 if (best_node >= 0)
3722 node_set(best_node, *used_node_mask);
3723
3724 return best_node;
3725}
3726
f0c0b2b8
KH
3727
3728/*
3729 * Build zonelists ordered by node and zones within node.
3730 * This results in maximum locality--normal zone overflows into local
3731 * DMA zone, if any--but risks exhausting DMA zone.
3732 */
3733static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
1da177e4 3734{
f0c0b2b8 3735 int j;
1da177e4 3736 struct zonelist *zonelist;
f0c0b2b8 3737
54a6eb5c 3738 zonelist = &pgdat->node_zonelists[0];
dd1a239f 3739 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
54a6eb5c
MG
3740 ;
3741 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3742 MAX_NR_ZONES - 1);
dd1a239f
MG
3743 zonelist->_zonerefs[j].zone = NULL;
3744 zonelist->_zonerefs[j].zone_idx = 0;
f0c0b2b8
KH
3745}
3746
523b9458
CL
3747/*
3748 * Build gfp_thisnode zonelists
3749 */
3750static void build_thisnode_zonelists(pg_data_t *pgdat)
3751{
523b9458
CL
3752 int j;
3753 struct zonelist *zonelist;
3754
54a6eb5c
MG
3755 zonelist = &pgdat->node_zonelists[1];
3756 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
dd1a239f
MG
3757 zonelist->_zonerefs[j].zone = NULL;
3758 zonelist->_zonerefs[j].zone_idx = 0;
523b9458
CL
3759}
3760
f0c0b2b8
KH
3761/*
3762 * Build zonelists ordered by zone and nodes within zones.
3763 * This results in conserving DMA zone[s] until all Normal memory is
3764 * exhausted, but results in overflowing to remote node while memory
3765 * may still exist in local DMA zone.
3766 */
3767static int node_order[MAX_NUMNODES];
3768
3769static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3770{
f0c0b2b8
KH
3771 int pos, j, node;
3772 int zone_type; /* needs to be signed */
3773 struct zone *z;
3774 struct zonelist *zonelist;
3775
54a6eb5c
MG
3776 zonelist = &pgdat->node_zonelists[0];
3777 pos = 0;
3778 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3779 for (j = 0; j < nr_nodes; j++) {
3780 node = node_order[j];
3781 z = &NODE_DATA(node)->node_zones[zone_type];
3782 if (populated_zone(z)) {
dd1a239f
MG
3783 zoneref_set_zone(z,
3784 &zonelist->_zonerefs[pos++]);
54a6eb5c 3785 check_highest_zone(zone_type);
f0c0b2b8
KH
3786 }
3787 }
f0c0b2b8 3788 }
dd1a239f
MG
3789 zonelist->_zonerefs[pos].zone = NULL;
3790 zonelist->_zonerefs[pos].zone_idx = 0;
f0c0b2b8
KH
3791}
3792
3793static int default_zonelist_order(void)
3794{
3795 int nid, zone_type;
3796 unsigned long low_kmem_size,total_size;
3797 struct zone *z;
3798 int average_size;
3799 /*
88393161 3800 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
f0c0b2b8
KH
3801 * If they are really small and used heavily, the system can fall
3802 * into OOM very easily.
e325c90f 3803 * This function detect ZONE_DMA/DMA32 size and configures zone order.
f0c0b2b8
KH
3804 */
3805 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3806 low_kmem_size = 0;
3807 total_size = 0;
3808 for_each_online_node(nid) {
3809 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3810 z = &NODE_DATA(nid)->node_zones[zone_type];
3811 if (populated_zone(z)) {
3812 if (zone_type < ZONE_NORMAL)
3813 low_kmem_size += z->present_pages;
3814 total_size += z->present_pages;
e325c90f
DR
3815 } else if (zone_type == ZONE_NORMAL) {
3816 /*
3817 * If any node has only lowmem, then node order
3818 * is preferred to allow kernel allocations
3819 * locally; otherwise, they can easily infringe
3820 * on other nodes when there is an abundance of
3821 * lowmem available to allocate from.
3822 */
3823 return ZONELIST_ORDER_NODE;
f0c0b2b8
KH
3824 }
3825 }
3826 }
3827 if (!low_kmem_size || /* there are no DMA area. */
3828 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3829 return ZONELIST_ORDER_NODE;
3830 /*
3831 * look into each node's config.
3832 * If there is a node whose DMA/DMA32 memory is very big area on
3833 * local memory, NODE_ORDER may be suitable.
3834 */
37b07e41 3835 average_size = total_size /
4b0ef1fe 3836 (nodes_weight(node_states[N_MEMORY]) + 1);
f0c0b2b8
KH
3837 for_each_online_node(nid) {
3838 low_kmem_size = 0;
3839 total_size = 0;
3840 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3841 z = &NODE_DATA(nid)->node_zones[zone_type];
3842 if (populated_zone(z)) {
3843 if (zone_type < ZONE_NORMAL)
3844 low_kmem_size += z->present_pages;
3845 total_size += z->present_pages;
3846 }
3847 }
3848 if (low_kmem_size &&
3849 total_size > average_size && /* ignore small node */
3850 low_kmem_size > total_size * 70/100)
3851 return ZONELIST_ORDER_NODE;
3852 }
3853 return ZONELIST_ORDER_ZONE;
3854}
3855
3856static void set_zonelist_order(void)
3857{
3858 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3859 current_zonelist_order = default_zonelist_order();
3860 else
3861 current_zonelist_order = user_zonelist_order;
3862}
3863
3864static void build_zonelists(pg_data_t *pgdat)
3865{
3866 int j, node, load;
3867 enum zone_type i;
1da177e4 3868 nodemask_t used_mask;
f0c0b2b8
KH
3869 int local_node, prev_node;
3870 struct zonelist *zonelist;
3871 int order = current_zonelist_order;
1da177e4
LT
3872
3873 /* initialize zonelists */
523b9458 3874 for (i = 0; i < MAX_ZONELISTS; i++) {
1da177e4 3875 zonelist = pgdat->node_zonelists + i;
dd1a239f
MG
3876 zonelist->_zonerefs[0].zone = NULL;
3877 zonelist->_zonerefs[0].zone_idx = 0;
1da177e4
LT
3878 }
3879
3880 /* NUMA-aware ordering of nodes */
3881 local_node = pgdat->node_id;
62bc62a8 3882 load = nr_online_nodes;
1da177e4
LT
3883 prev_node = local_node;
3884 nodes_clear(used_mask);
f0c0b2b8 3885
f0c0b2b8
KH
3886 memset(node_order, 0, sizeof(node_order));
3887 j = 0;
3888
1da177e4
LT
3889 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3890 /*
3891 * We don't want to pressure a particular node.
3892 * So adding penalty to the first node in same
3893 * distance group to make it round-robin.
3894 */
957f822a
DR
3895 if (node_distance(local_node, node) !=
3896 node_distance(local_node, prev_node))
f0c0b2b8
KH
3897 node_load[node] = load;
3898
1da177e4
LT
3899 prev_node = node;
3900 load--;
f0c0b2b8
KH
3901 if (order == ZONELIST_ORDER_NODE)
3902 build_zonelists_in_node_order(pgdat, node);
3903 else
3904 node_order[j++] = node; /* remember order */
3905 }
1da177e4 3906
f0c0b2b8
KH
3907 if (order == ZONELIST_ORDER_ZONE) {
3908 /* calculate node order -- i.e., DMA last! */
3909 build_zonelists_in_zone_order(pgdat, j);
1da177e4 3910 }
523b9458
CL
3911
3912 build_thisnode_zonelists(pgdat);
1da177e4
LT
3913}
3914
9276b1bc 3915/* Construct the zonelist performance cache - see further mmzone.h */
f0c0b2b8 3916static void build_zonelist_cache(pg_data_t *pgdat)
9276b1bc 3917{
54a6eb5c
MG
3918 struct zonelist *zonelist;
3919 struct zonelist_cache *zlc;
dd1a239f 3920 struct zoneref *z;
9276b1bc 3921
54a6eb5c
MG
3922 zonelist = &pgdat->node_zonelists[0];
3923 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3924 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
dd1a239f
MG
3925 for (z = zonelist->_zonerefs; z->zone; z++)
3926 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
9276b1bc
PJ
3927}
3928
7aac7898
LS
3929#ifdef CONFIG_HAVE_MEMORYLESS_NODES
3930/*
3931 * Return node id of node used for "local" allocations.
3932 * I.e., first node id of first zone in arg node's generic zonelist.
3933 * Used for initializing percpu 'numa_mem', which is used primarily
3934 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3935 */
3936int local_memory_node(int node)
3937{
3938 struct zone *zone;
3939
3940 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3941 gfp_zone(GFP_KERNEL),
3942 NULL,
3943 &zone);
3944 return zone->node;
3945}
3946#endif
f0c0b2b8 3947
1da177e4
LT
3948#else /* CONFIG_NUMA */
3949
f0c0b2b8
KH
3950static void set_zonelist_order(void)
3951{
3952 current_zonelist_order = ZONELIST_ORDER_ZONE;
3953}
3954
3955static void build_zonelists(pg_data_t *pgdat)
1da177e4 3956{
19655d34 3957 int node, local_node;
54a6eb5c
MG
3958 enum zone_type j;
3959 struct zonelist *zonelist;
1da177e4
LT
3960
3961 local_node = pgdat->node_id;
1da177e4 3962
54a6eb5c
MG
3963 zonelist = &pgdat->node_zonelists[0];
3964 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
1da177e4 3965
54a6eb5c
MG
3966 /*
3967 * Now we build the zonelist so that it contains the zones
3968 * of all the other nodes.
3969 * We don't want to pressure a particular node, so when
3970 * building the zones for node N, we make sure that the
3971 * zones coming right after the local ones are those from
3972 * node N+1 (modulo N)
3973 */
3974 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3975 if (!node_online(node))
3976 continue;
3977 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3978 MAX_NR_ZONES - 1);
1da177e4 3979 }
54a6eb5c
MG
3980 for (node = 0; node < local_node; node++) {
3981 if (!node_online(node))
3982 continue;
3983 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3984 MAX_NR_ZONES - 1);
3985 }
3986
dd1a239f
MG
3987 zonelist->_zonerefs[j].zone = NULL;
3988 zonelist->_zonerefs[j].zone_idx = 0;
1da177e4
LT
3989}
3990
9276b1bc 3991/* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
f0c0b2b8 3992static void build_zonelist_cache(pg_data_t *pgdat)
9276b1bc 3993{
54a6eb5c 3994 pgdat->node_zonelists[0].zlcache_ptr = NULL;
9276b1bc
PJ
3995}
3996
1da177e4
LT
3997#endif /* CONFIG_NUMA */
3998
99dcc3e5
CL
3999/*
4000 * Boot pageset table. One per cpu which is going to be used for all
4001 * zones and all nodes. The parameters will be set in such a way
4002 * that an item put on a list will immediately be handed over to
4003 * the buddy list. This is safe since pageset manipulation is done
4004 * with interrupts disabled.
4005 *
4006 * The boot_pagesets must be kept even after bootup is complete for
4007 * unused processors and/or zones. They do play a role for bootstrapping
4008 * hotplugged processors.
4009 *
4010 * zoneinfo_show() and maybe other functions do
4011 * not check if the processor is online before following the pageset pointer.
4012 * Other parts of the kernel may not check if the zone is available.
4013 */
4014static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4015static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
1f522509 4016static void setup_zone_pageset(struct zone *zone);
99dcc3e5 4017
4eaf3f64
HL
4018/*
4019 * Global mutex to protect against size modification of zonelists
4020 * as well as to serialize pageset setup for the new populated zone.
4021 */
4022DEFINE_MUTEX(zonelists_mutex);
4023
9b1a4d38 4024/* return values int ....just for stop_machine() */
4ed7e022 4025static int __build_all_zonelists(void *data)
1da177e4 4026{
6811378e 4027 int nid;
99dcc3e5 4028 int cpu;
9adb62a5 4029 pg_data_t *self = data;
9276b1bc 4030
7f9cfb31
BL
4031#ifdef CONFIG_NUMA
4032 memset(node_load, 0, sizeof(node_load));
4033#endif
9adb62a5
JL
4034
4035 if (self && !node_online(self->node_id)) {
4036 build_zonelists(self);
4037 build_zonelist_cache(self);
4038 }
4039
9276b1bc 4040 for_each_online_node(nid) {
7ea1530a
CL
4041 pg_data_t *pgdat = NODE_DATA(nid);
4042
4043 build_zonelists(pgdat);
4044 build_zonelist_cache(pgdat);
9276b1bc 4045 }
99dcc3e5
CL
4046
4047 /*
4048 * Initialize the boot_pagesets that are going to be used
4049 * for bootstrapping processors. The real pagesets for
4050 * each zone will be allocated later when the per cpu
4051 * allocator is available.
4052 *
4053 * boot_pagesets are used also for bootstrapping offline
4054 * cpus if the system is already booted because the pagesets
4055 * are needed to initialize allocators on a specific cpu too.
4056 * F.e. the percpu allocator needs the page allocator which
4057 * needs the percpu allocator in order to allocate its pagesets
4058 * (a chicken-egg dilemma).
4059 */
7aac7898 4060 for_each_possible_cpu(cpu) {
99dcc3e5
CL
4061 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4062
7aac7898
LS
4063#ifdef CONFIG_HAVE_MEMORYLESS_NODES
4064 /*
4065 * We now know the "local memory node" for each node--
4066 * i.e., the node of the first zone in the generic zonelist.
4067 * Set up numa_mem percpu variable for on-line cpus. During
4068 * boot, only the boot cpu should be on-line; we'll init the
4069 * secondary cpus' numa_mem as they come on-line. During
4070 * node/memory hotplug, we'll fixup all on-line cpus.
4071 */
4072 if (cpu_online(cpu))
4073 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4074#endif
4075 }
4076
6811378e
YG
4077 return 0;
4078}
4079
4eaf3f64
HL
4080/*
4081 * Called with zonelists_mutex held always
4082 * unless system_state == SYSTEM_BOOTING.
4083 */
9adb62a5 4084void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
6811378e 4085{
f0c0b2b8
KH
4086 set_zonelist_order();
4087
6811378e 4088 if (system_state == SYSTEM_BOOTING) {
423b41d7 4089 __build_all_zonelists(NULL);
68ad8df4 4090 mminit_verify_zonelist();
6811378e
YG
4091 cpuset_init_current_mems_allowed();
4092 } else {
183ff22b 4093 /* we have to stop all cpus to guarantee there is no user
6811378e 4094 of zonelist */
e9959f0f 4095#ifdef CONFIG_MEMORY_HOTPLUG
9adb62a5
JL
4096 if (zone)
4097 setup_zone_pageset(zone);
e9959f0f 4098#endif
9adb62a5 4099 stop_machine(__build_all_zonelists, pgdat, NULL);
6811378e
YG
4100 /* cpuset refresh routine should be here */
4101 }
bd1e22b8 4102 vm_total_pages = nr_free_pagecache_pages();
9ef9acb0
MG
4103 /*
4104 * Disable grouping by mobility if the number of pages in the
4105 * system is too low to allow the mechanism to work. It would be
4106 * more accurate, but expensive to check per-zone. This check is
4107 * made on memory-hotadd so a system can start with mobility
4108 * disabled and enable it later
4109 */
d9c23400 4110 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
9ef9acb0
MG
4111 page_group_by_mobility_disabled = 1;
4112 else
4113 page_group_by_mobility_disabled = 0;
4114
4115 printk("Built %i zonelists in %s order, mobility grouping %s. "
4116 "Total pages: %ld\n",
62bc62a8 4117 nr_online_nodes,
f0c0b2b8 4118 zonelist_order_name[current_zonelist_order],
9ef9acb0 4119 page_group_by_mobility_disabled ? "off" : "on",
f0c0b2b8
KH
4120 vm_total_pages);
4121#ifdef CONFIG_NUMA
4122 printk("Policy zone: %s\n", zone_names[policy_zone]);
4123#endif
1da177e4
LT
4124}
4125
4126/*
4127 * Helper functions to size the waitqueue hash table.
4128 * Essentially these want to choose hash table sizes sufficiently
4129 * large so that collisions trying to wait on pages are rare.
4130 * But in fact, the number of active page waitqueues on typical
4131 * systems is ridiculously low, less than 200. So this is even
4132 * conservative, even though it seems large.
4133 *
4134 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4135 * waitqueues, i.e. the size of the waitq table given the number of pages.
4136 */
4137#define PAGES_PER_WAITQUEUE 256
4138
cca448fe 4139#ifndef CONFIG_MEMORY_HOTPLUG
02b694de 4140static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
1da177e4
LT
4141{
4142 unsigned long size = 1;
4143
4144 pages /= PAGES_PER_WAITQUEUE;
4145
4146 while (size < pages)
4147 size <<= 1;
4148
4149 /*
4150 * Once we have dozens or even hundreds of threads sleeping
4151 * on IO we've got bigger problems than wait queue collision.
4152 * Limit the size of the wait table to a reasonable size.
4153 */
4154 size = min(size, 4096UL);
4155
4156 return max(size, 4UL);
4157}
cca448fe
YG
4158#else
4159/*
4160 * A zone's size might be changed by hot-add, so it is not possible to determine
4161 * a suitable size for its wait_table. So we use the maximum size now.
4162 *
4163 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
4164 *
4165 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
4166 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4167 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
4168 *
4169 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4170 * or more by the traditional way. (See above). It equals:
4171 *
4172 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
4173 * ia64(16K page size) : = ( 8G + 4M)byte.
4174 * powerpc (64K page size) : = (32G +16M)byte.
4175 */
4176static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4177{
4178 return 4096UL;
4179}
4180#endif
1da177e4
LT
4181
4182/*
4183 * This is an integer logarithm so that shifts can be used later
4184 * to extract the more random high bits from the multiplicative
4185 * hash function before the remainder is taken.
4186 */
4187static inline unsigned long wait_table_bits(unsigned long size)
4188{
4189 return ffz(~size);
4190}
4191
4192#define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
4193
6d3163ce
AH
4194/*
4195 * Check if a pageblock contains reserved pages
4196 */
4197static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
4198{
4199 unsigned long pfn;
4200
4201 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4202 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
4203 return 1;
4204 }
4205 return 0;
4206}
4207
56fd56b8 4208/*
d9c23400 4209 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
41858966
MG
4210 * of blocks reserved is based on min_wmark_pages(zone). The memory within
4211 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
56fd56b8
MG
4212 * higher will lead to a bigger reserve which will get freed as contiguous
4213 * blocks as reclaim kicks in
4214 */
4215static void setup_zone_migrate_reserve(struct zone *zone)
4216{
6d3163ce 4217 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
56fd56b8 4218 struct page *page;
78986a67
MG
4219 unsigned long block_migratetype;
4220 int reserve;
56fd56b8 4221
d0215638
MH
4222 /*
4223 * Get the start pfn, end pfn and the number of blocks to reserve
4224 * We have to be careful to be aligned to pageblock_nr_pages to
4225 * make sure that we always check pfn_valid for the first page in
4226 * the block.
4227 */
56fd56b8 4228 start_pfn = zone->zone_start_pfn;
108bcc96 4229 end_pfn = zone_end_pfn(zone);
d0215638 4230 start_pfn = roundup(start_pfn, pageblock_nr_pages);
41858966 4231 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
d9c23400 4232 pageblock_order;
56fd56b8 4233
78986a67
MG
4234 /*
4235 * Reserve blocks are generally in place to help high-order atomic
4236 * allocations that are short-lived. A min_free_kbytes value that
4237 * would result in more than 2 reserve blocks for atomic allocations
4238 * is assumed to be in place to help anti-fragmentation for the
4239 * future allocation of hugepages at runtime.
4240 */
4241 reserve = min(2, reserve);
4242
d9c23400 4243 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
56fd56b8
MG
4244 if (!pfn_valid(pfn))
4245 continue;
4246 page = pfn_to_page(pfn);
4247
344c790e
AL
4248 /* Watch out for overlapping nodes */
4249 if (page_to_nid(page) != zone_to_nid(zone))
4250 continue;
4251
56fd56b8
MG
4252 block_migratetype = get_pageblock_migratetype(page);
4253
938929f1
MG
4254 /* Only test what is necessary when the reserves are not met */
4255 if (reserve > 0) {
4256 /*
4257 * Blocks with reserved pages will never free, skip
4258 * them.
4259 */
4260 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
4261 if (pageblock_is_reserved(pfn, block_end_pfn))
4262 continue;
56fd56b8 4263
938929f1
MG
4264 /* If this block is reserved, account for it */
4265 if (block_migratetype == MIGRATE_RESERVE) {
4266 reserve--;
4267 continue;
4268 }
4269
4270 /* Suitable for reserving if this block is movable */
4271 if (block_migratetype == MIGRATE_MOVABLE) {
4272 set_pageblock_migratetype(page,
4273 MIGRATE_RESERVE);
4274 move_freepages_block(zone, page,
4275 MIGRATE_RESERVE);
4276 reserve--;
4277 continue;
4278 }
56fd56b8
MG
4279 }
4280
4281 /*
4282 * If the reserve is met and this is a previous reserved block,
4283 * take it back
4284 */
4285 if (block_migratetype == MIGRATE_RESERVE) {
4286 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4287 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4288 }
4289 }
4290}
ac0e5b7a 4291
1da177e4
LT
4292/*
4293 * Initially all pages are reserved - free ones are freed
4294 * up by free_all_bootmem() once the early boot process is
4295 * done. Non-atomic initialization, single-pass.
4296 */
c09b4240 4297void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
a2f3aa02 4298 unsigned long start_pfn, enum memmap_context context)
1da177e4 4299{
1da177e4 4300 struct page *page;
29751f69
AW
4301 unsigned long end_pfn = start_pfn + size;
4302 unsigned long pfn;
86051ca5 4303 struct zone *z;
1da177e4 4304
22b31eec
HD
4305 if (highest_memmap_pfn < end_pfn - 1)
4306 highest_memmap_pfn = end_pfn - 1;
4307
86051ca5 4308 z = &NODE_DATA(nid)->node_zones[zone];
cbe8dd4a 4309 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
a2f3aa02
DH
4310 /*
4311 * There can be holes in boot-time mem_map[]s
4312 * handed to this function. They do not
4313 * exist on hotplugged memory.
4314 */
4315 if (context == MEMMAP_EARLY) {
4316 if (!early_pfn_valid(pfn))
4317 continue;
4318 if (!early_pfn_in_nid(pfn, nid))
4319 continue;
4320 }
d41dee36
AW
4321 page = pfn_to_page(pfn);
4322 set_page_links(page, zone, nid, pfn);
708614e6 4323 mminit_verify_page_links(page, zone, nid, pfn);
7835e98b 4324 init_page_count(page);
22b751c3
MG
4325 page_mapcount_reset(page);
4326 page_nid_reset_last(page);
1da177e4 4327 SetPageReserved(page);
b2a0ac88
MG
4328 /*
4329 * Mark the block movable so that blocks are reserved for
4330 * movable at startup. This will force kernel allocations
4331 * to reserve their blocks rather than leaking throughout
4332 * the address space during boot when many long-lived
56fd56b8
MG
4333 * kernel allocations are made. Later some blocks near
4334 * the start are marked MIGRATE_RESERVE by
4335 * setup_zone_migrate_reserve()
86051ca5
KH
4336 *
4337 * bitmap is created for zone's valid pfn range. but memmap
4338 * can be created for invalid pages (for alignment)
4339 * check here not to call set_pageblock_migratetype() against
4340 * pfn out of zone.
b2a0ac88 4341 */
86051ca5 4342 if ((z->zone_start_pfn <= pfn)
108bcc96 4343 && (pfn < zone_end_pfn(z))
86051ca5 4344 && !(pfn & (pageblock_nr_pages - 1)))
56fd56b8 4345 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
b2a0ac88 4346
1da177e4
LT
4347 INIT_LIST_HEAD(&page->lru);
4348#ifdef WANT_PAGE_VIRTUAL
4349 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
4350 if (!is_highmem_idx(zone))
3212c6be 4351 set_page_address(page, __va(pfn << PAGE_SHIFT));
1da177e4 4352#endif
1da177e4
LT
4353 }
4354}
4355
1e548deb 4356static void __meminit zone_init_free_lists(struct zone *zone)
1da177e4 4357{
b2a0ac88
MG
4358 int order, t;
4359 for_each_migratetype_order(order, t) {
4360 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
1da177e4
LT
4361 zone->free_area[order].nr_free = 0;
4362 }
4363}
4364
4365#ifndef __HAVE_ARCH_MEMMAP_INIT
4366#define memmap_init(size, nid, zone, start_pfn) \
a2f3aa02 4367 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
1da177e4
LT
4368#endif
4369
4ed7e022 4370static int __meminit zone_batchsize(struct zone *zone)
e7c8d5c9 4371{
3a6be87f 4372#ifdef CONFIG_MMU
e7c8d5c9
CL
4373 int batch;
4374
4375 /*
4376 * The per-cpu-pages pools are set to around 1000th of the
ba56e91c 4377 * size of the zone. But no more than 1/2 of a meg.
e7c8d5c9
CL
4378 *
4379 * OK, so we don't know how big the cache is. So guess.
4380 */
b40da049 4381 batch = zone->managed_pages / 1024;
ba56e91c
SR
4382 if (batch * PAGE_SIZE > 512 * 1024)
4383 batch = (512 * 1024) / PAGE_SIZE;
e7c8d5c9
CL
4384 batch /= 4; /* We effectively *= 4 below */
4385 if (batch < 1)
4386 batch = 1;
4387
4388 /*
0ceaacc9
NP
4389 * Clamp the batch to a 2^n - 1 value. Having a power
4390 * of 2 value was found to be more likely to have
4391 * suboptimal cache aliasing properties in some cases.
e7c8d5c9 4392 *
0ceaacc9
NP
4393 * For example if 2 tasks are alternately allocating
4394 * batches of pages, one task can end up with a lot
4395 * of pages of one half of the possible page colors
4396 * and the other with pages of the other colors.
e7c8d5c9 4397 */
9155203a 4398 batch = rounddown_pow_of_two(batch + batch/2) - 1;
ba56e91c 4399
e7c8d5c9 4400 return batch;
3a6be87f
DH
4401
4402#else
4403 /* The deferral and batching of frees should be suppressed under NOMMU
4404 * conditions.
4405 *
4406 * The problem is that NOMMU needs to be able to allocate large chunks
4407 * of contiguous memory as there's no hardware page translation to
4408 * assemble apparent contiguous memory from discontiguous pages.
4409 *
4410 * Queueing large contiguous runs of pages for batching, however,
4411 * causes the pages to actually be freed in smaller chunks. As there
4412 * can be a significant delay between the individual batches being
4413 * recycled, this leads to the once large chunks of space being
4414 * fragmented and becoming unavailable for high-order allocations.
4415 */
4416 return 0;
4417#endif
e7c8d5c9
CL
4418}
4419
b69a7288 4420static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2caaad41
CL
4421{
4422 struct per_cpu_pages *pcp;
5f8dcc21 4423 int migratetype;
2caaad41 4424
1c6fe946
MD
4425 memset(p, 0, sizeof(*p));
4426
3dfa5721 4427 pcp = &p->pcp;
2caaad41 4428 pcp->count = 0;
2caaad41
CL
4429 pcp->high = 6 * batch;
4430 pcp->batch = max(1UL, 1 * batch);
5f8dcc21
MG
4431 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4432 INIT_LIST_HEAD(&pcp->lists[migratetype]);
2caaad41
CL
4433}
4434
8ad4b1fb
RS
4435/*
4436 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
4437 * to the value high for the pageset p.
4438 */
4439
4440static void setup_pagelist_highmark(struct per_cpu_pageset *p,
4441 unsigned long high)
4442{
4443 struct per_cpu_pages *pcp;
4444
3dfa5721 4445 pcp = &p->pcp;
8ad4b1fb
RS
4446 pcp->high = high;
4447 pcp->batch = max(1UL, high/4);
4448 if ((high/4) > (PAGE_SHIFT * 8))
4449 pcp->batch = PAGE_SHIFT * 8;
4450}
4451
4ed7e022 4452static void __meminit setup_zone_pageset(struct zone *zone)
319774e2
WF
4453{
4454 int cpu;
4455
4456 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4457
4458 for_each_possible_cpu(cpu) {
4459 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4460
4461 setup_pageset(pcp, zone_batchsize(zone));
4462
4463 if (percpu_pagelist_fraction)
4464 setup_pagelist_highmark(pcp,
b40da049 4465 (zone->managed_pages /
319774e2
WF
4466 percpu_pagelist_fraction));
4467 }
4468}
4469
2caaad41 4470/*
99dcc3e5
CL
4471 * Allocate per cpu pagesets and initialize them.
4472 * Before this call only boot pagesets were available.
e7c8d5c9 4473 */
99dcc3e5 4474void __init setup_per_cpu_pageset(void)
e7c8d5c9 4475{
99dcc3e5 4476 struct zone *zone;
e7c8d5c9 4477
319774e2
WF
4478 for_each_populated_zone(zone)
4479 setup_zone_pageset(zone);
e7c8d5c9
CL
4480}
4481
577a32f6 4482static noinline __init_refok
cca448fe 4483int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
ed8ece2e
DH
4484{
4485 int i;
4486 struct pglist_data *pgdat = zone->zone_pgdat;
cca448fe 4487 size_t alloc_size;
ed8ece2e
DH
4488
4489 /*
4490 * The per-page waitqueue mechanism uses hashed waitqueues
4491 * per zone.
4492 */
02b694de
YG
4493 zone->wait_table_hash_nr_entries =
4494 wait_table_hash_nr_entries(zone_size_pages);
4495 zone->wait_table_bits =
4496 wait_table_bits(zone->wait_table_hash_nr_entries);
cca448fe
YG
4497 alloc_size = zone->wait_table_hash_nr_entries
4498 * sizeof(wait_queue_head_t);
4499
cd94b9db 4500 if (!slab_is_available()) {
cca448fe 4501 zone->wait_table = (wait_queue_head_t *)
8f389a99 4502 alloc_bootmem_node_nopanic(pgdat, alloc_size);
cca448fe
YG
4503 } else {
4504 /*
4505 * This case means that a zone whose size was 0 gets new memory
4506 * via memory hot-add.
4507 * But it may be the case that a new node was hot-added. In
4508 * this case vmalloc() will not be able to use this new node's
4509 * memory - this wait_table must be initialized to use this new
4510 * node itself as well.
4511 * To use this new node's memory, further consideration will be
4512 * necessary.
4513 */
8691f3a7 4514 zone->wait_table = vmalloc(alloc_size);
cca448fe
YG
4515 }
4516 if (!zone->wait_table)
4517 return -ENOMEM;
ed8ece2e 4518
02b694de 4519 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
ed8ece2e 4520 init_waitqueue_head(zone->wait_table + i);
cca448fe
YG
4521
4522 return 0;
ed8ece2e
DH
4523}
4524
c09b4240 4525static __meminit void zone_pcp_init(struct zone *zone)
ed8ece2e 4526{
99dcc3e5
CL
4527 /*
4528 * per cpu subsystem is not up at this point. The following code
4529 * relies on the ability of the linker to provide the
4530 * offset of a (static) per cpu variable into the per cpu area.
4531 */
4532 zone->pageset = &boot_pageset;
ed8ece2e 4533
f5335c0f 4534 if (zone->present_pages)
99dcc3e5
CL
4535 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4536 zone->name, zone->present_pages,
4537 zone_batchsize(zone));
ed8ece2e
DH
4538}
4539
4ed7e022 4540int __meminit init_currently_empty_zone(struct zone *zone,
718127cc 4541 unsigned long zone_start_pfn,
a2f3aa02
DH
4542 unsigned long size,
4543 enum memmap_context context)
ed8ece2e
DH
4544{
4545 struct pglist_data *pgdat = zone->zone_pgdat;
cca448fe
YG
4546 int ret;
4547 ret = zone_wait_table_init(zone, size);
4548 if (ret)
4549 return ret;
ed8ece2e
DH
4550 pgdat->nr_zones = zone_idx(zone) + 1;
4551
ed8ece2e
DH
4552 zone->zone_start_pfn = zone_start_pfn;
4553
708614e6
MG
4554 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4555 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4556 pgdat->node_id,
4557 (unsigned long)zone_idx(zone),
4558 zone_start_pfn, (zone_start_pfn + size));
4559
1e548deb 4560 zone_init_free_lists(zone);
718127cc
YG
4561
4562 return 0;
ed8ece2e
DH
4563}
4564
0ee332c1 4565#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
c713216d
MG
4566#ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4567/*
4568 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4569 * Architectures may implement their own version but if add_active_range()
4570 * was used and there are no special requirements, this is a convenient
4571 * alternative
4572 */
f2dbcfa7 4573int __meminit __early_pfn_to_nid(unsigned long pfn)
c713216d 4574{
c13291a5
TH
4575 unsigned long start_pfn, end_pfn;
4576 int i, nid;
7c243c71
RA
4577 /*
4578 * NOTE: The following SMP-unsafe globals are only used early in boot
4579 * when the kernel is running single-threaded.
4580 */
4581 static unsigned long __meminitdata last_start_pfn, last_end_pfn;
4582 static int __meminitdata last_nid;
4583
4584 if (last_start_pfn <= pfn && pfn < last_end_pfn)
4585 return last_nid;
c713216d 4586
c13291a5 4587 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
7c243c71
RA
4588 if (start_pfn <= pfn && pfn < end_pfn) {
4589 last_start_pfn = start_pfn;
4590 last_end_pfn = end_pfn;
4591 last_nid = nid;
c13291a5 4592 return nid;
7c243c71 4593 }
cc2559bc
KH
4594 /* This is a memory hole */
4595 return -1;
c713216d
MG
4596}
4597#endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4598
f2dbcfa7
KH
4599int __meminit early_pfn_to_nid(unsigned long pfn)
4600{
cc2559bc
KH
4601 int nid;
4602
4603 nid = __early_pfn_to_nid(pfn);
4604 if (nid >= 0)
4605 return nid;
4606 /* just returns 0 */
4607 return 0;
f2dbcfa7
KH
4608}
4609
cc2559bc
KH
4610#ifdef CONFIG_NODES_SPAN_OTHER_NODES
4611bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4612{
4613 int nid;
4614
4615 nid = __early_pfn_to_nid(pfn);
4616 if (nid >= 0 && nid != node)
4617 return false;
4618 return true;
4619}
4620#endif
f2dbcfa7 4621
c713216d
MG
4622/**
4623 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
88ca3b94
RD
4624 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4625 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
c713216d
MG
4626 *
4627 * If an architecture guarantees that all ranges registered with
4628 * add_active_ranges() contain no holes and may be freed, this
4629 * this function may be used instead of calling free_bootmem() manually.
4630 */
c13291a5 4631void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
cc289894 4632{
c13291a5
TH
4633 unsigned long start_pfn, end_pfn;
4634 int i, this_nid;
edbe7d23 4635
c13291a5
TH
4636 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4637 start_pfn = min(start_pfn, max_low_pfn);
4638 end_pfn = min(end_pfn, max_low_pfn);
edbe7d23 4639
c13291a5
TH
4640 if (start_pfn < end_pfn)
4641 free_bootmem_node(NODE_DATA(this_nid),
4642 PFN_PHYS(start_pfn),
4643 (end_pfn - start_pfn) << PAGE_SHIFT);
edbe7d23 4644 }
edbe7d23 4645}
edbe7d23 4646
c713216d
MG
4647/**
4648 * sparse_memory_present_with_active_regions - Call memory_present for each active range
88ca3b94 4649 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
c713216d
MG
4650 *
4651 * If an architecture guarantees that all ranges registered with
4652 * add_active_ranges() contain no holes and may be freed, this
88ca3b94 4653 * function may be used instead of calling memory_present() manually.
c713216d
MG
4654 */
4655void __init sparse_memory_present_with_active_regions(int nid)
4656{
c13291a5
TH
4657 unsigned long start_pfn, end_pfn;
4658 int i, this_nid;
c713216d 4659
c13291a5
TH
4660 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4661 memory_present(this_nid, start_pfn, end_pfn);
c713216d
MG
4662}
4663
4664/**
4665 * get_pfn_range_for_nid - Return the start and end page frames for a node
88ca3b94
RD
4666 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4667 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4668 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
c713216d
MG
4669 *
4670 * It returns the start and end page frame of a node based on information
4671 * provided by an arch calling add_active_range(). If called for a node
4672 * with no available memory, a warning is printed and the start and end
88ca3b94 4673 * PFNs will be 0.
c713216d 4674 */
a3142c8e 4675void __meminit get_pfn_range_for_nid(unsigned int nid,
c713216d
MG
4676 unsigned long *start_pfn, unsigned long *end_pfn)
4677{
c13291a5 4678 unsigned long this_start_pfn, this_end_pfn;
c713216d 4679 int i;
c13291a5 4680
c713216d
MG
4681 *start_pfn = -1UL;
4682 *end_pfn = 0;
4683
c13291a5
TH
4684 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4685 *start_pfn = min(*start_pfn, this_start_pfn);
4686 *end_pfn = max(*end_pfn, this_end_pfn);
c713216d
MG
4687 }
4688
633c0666 4689 if (*start_pfn == -1UL)
c713216d 4690 *start_pfn = 0;
c713216d
MG
4691}
4692
2a1e274a
MG
4693/*
4694 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4695 * assumption is made that zones within a node are ordered in monotonic
4696 * increasing memory addresses so that the "highest" populated zone is used
4697 */
b69a7288 4698static void __init find_usable_zone_for_movable(void)
2a1e274a
MG
4699{
4700 int zone_index;
4701 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4702 if (zone_index == ZONE_MOVABLE)
4703 continue;
4704
4705 if (arch_zone_highest_possible_pfn[zone_index] >
4706 arch_zone_lowest_possible_pfn[zone_index])
4707 break;
4708 }
4709
4710 VM_BUG_ON(zone_index == -1);
4711 movable_zone = zone_index;
4712}
4713
4714/*
4715 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
25985edc 4716 * because it is sized independent of architecture. Unlike the other zones,
2a1e274a
MG
4717 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4718 * in each node depending on the size of each node and how evenly kernelcore
4719 * is distributed. This helper function adjusts the zone ranges
4720 * provided by the architecture for a given node by using the end of the
4721 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4722 * zones within a node are in order of monotonic increases memory addresses
4723 */
b69a7288 4724static void __meminit adjust_zone_range_for_zone_movable(int nid,
2a1e274a
MG
4725 unsigned long zone_type,
4726 unsigned long node_start_pfn,
4727 unsigned long node_end_pfn,
4728 unsigned long *zone_start_pfn,
4729 unsigned long *zone_end_pfn)
4730{
4731 /* Only adjust if ZONE_MOVABLE is on this node */
4732 if (zone_movable_pfn[nid]) {
4733 /* Size ZONE_MOVABLE */
4734 if (zone_type == ZONE_MOVABLE) {
4735 *zone_start_pfn = zone_movable_pfn[nid];
4736 *zone_end_pfn = min(node_end_pfn,
4737 arch_zone_highest_possible_pfn[movable_zone]);
4738
4739 /* Adjust for ZONE_MOVABLE starting within this range */
4740 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4741 *zone_end_pfn > zone_movable_pfn[nid]) {
4742 *zone_end_pfn = zone_movable_pfn[nid];
4743
4744 /* Check if this whole range is within ZONE_MOVABLE */
4745 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4746 *zone_start_pfn = *zone_end_pfn;
4747 }
4748}
4749
c713216d
MG
4750/*
4751 * Return the number of pages a zone spans in a node, including holes
4752 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4753 */
6ea6e688 4754static unsigned long __meminit zone_spanned_pages_in_node(int nid,
c713216d
MG
4755 unsigned long zone_type,
4756 unsigned long *ignored)
4757{
4758 unsigned long node_start_pfn, node_end_pfn;
4759 unsigned long zone_start_pfn, zone_end_pfn;
4760
4761 /* Get the start and end of the node and zone */
4762 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4763 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4764 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
2a1e274a
MG
4765 adjust_zone_range_for_zone_movable(nid, zone_type,
4766 node_start_pfn, node_end_pfn,
4767 &zone_start_pfn, &zone_end_pfn);
c713216d
MG
4768
4769 /* Check that this node has pages within the zone's required range */
4770 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4771 return 0;
4772
4773 /* Move the zone boundaries inside the node if necessary */
4774 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4775 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4776
4777 /* Return the spanned pages */
4778 return zone_end_pfn - zone_start_pfn;
4779}
4780
4781/*
4782 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
88ca3b94 4783 * then all holes in the requested range will be accounted for.
c713216d 4784 */
32996250 4785unsigned long __meminit __absent_pages_in_range(int nid,
c713216d
MG
4786 unsigned long range_start_pfn,
4787 unsigned long range_end_pfn)
4788{
96e907d1
TH
4789 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4790 unsigned long start_pfn, end_pfn;
4791 int i;
c713216d 4792
96e907d1
TH
4793 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4794 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4795 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4796 nr_absent -= end_pfn - start_pfn;
c713216d 4797 }
96e907d1 4798 return nr_absent;
c713216d
MG
4799}
4800
4801/**
4802 * absent_pages_in_range - Return number of page frames in holes within a range
4803 * @start_pfn: The start PFN to start searching for holes
4804 * @end_pfn: The end PFN to stop searching for holes
4805 *
88ca3b94 4806 * It returns the number of pages frames in memory holes within a range.
c713216d
MG
4807 */
4808unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4809 unsigned long end_pfn)
4810{
4811 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4812}
4813
4814/* Return the number of page frames in holes in a zone on a node */
6ea6e688 4815static unsigned long __meminit zone_absent_pages_in_node(int nid,
c713216d
MG
4816 unsigned long zone_type,
4817 unsigned long *ignored)
4818{
96e907d1
TH
4819 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4820 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
9c7cd687
MG
4821 unsigned long node_start_pfn, node_end_pfn;
4822 unsigned long zone_start_pfn, zone_end_pfn;
4823
4824 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
96e907d1
TH
4825 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4826 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
9c7cd687 4827
2a1e274a
MG
4828 adjust_zone_range_for_zone_movable(nid, zone_type,
4829 node_start_pfn, node_end_pfn,
4830 &zone_start_pfn, &zone_end_pfn);
9c7cd687 4831 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
c713216d 4832}
0e0b864e 4833
0ee332c1 4834#else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6ea6e688 4835static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
c713216d
MG
4836 unsigned long zone_type,
4837 unsigned long *zones_size)
4838{
4839 return zones_size[zone_type];
4840}
4841
6ea6e688 4842static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
c713216d
MG
4843 unsigned long zone_type,
4844 unsigned long *zholes_size)
4845{
4846 if (!zholes_size)
4847 return 0;
4848
4849 return zholes_size[zone_type];
4850}
20e6926d 4851
0ee332c1 4852#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 4853
a3142c8e 4854static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
c713216d
MG
4855 unsigned long *zones_size, unsigned long *zholes_size)
4856{
4857 unsigned long realtotalpages, totalpages = 0;
4858 enum zone_type i;
4859
4860 for (i = 0; i < MAX_NR_ZONES; i++)
4861 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4862 zones_size);
4863 pgdat->node_spanned_pages = totalpages;
4864
4865 realtotalpages = totalpages;
4866 for (i = 0; i < MAX_NR_ZONES; i++)
4867 realtotalpages -=
4868 zone_absent_pages_in_node(pgdat->node_id, i,
4869 zholes_size);
4870 pgdat->node_present_pages = realtotalpages;
4871 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4872 realtotalpages);
4873}
4874
835c134e
MG
4875#ifndef CONFIG_SPARSEMEM
4876/*
4877 * Calculate the size of the zone->blockflags rounded to an unsigned long
d9c23400
MG
4878 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4879 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
835c134e
MG
4880 * round what is now in bits to nearest long in bits, then return it in
4881 * bytes.
4882 */
7c45512d 4883static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
835c134e
MG
4884{
4885 unsigned long usemapsize;
4886
7c45512d 4887 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
d9c23400
MG
4888 usemapsize = roundup(zonesize, pageblock_nr_pages);
4889 usemapsize = usemapsize >> pageblock_order;
835c134e
MG
4890 usemapsize *= NR_PAGEBLOCK_BITS;
4891 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4892
4893 return usemapsize / 8;
4894}
4895
4896static void __init setup_usemap(struct pglist_data *pgdat,
7c45512d
LT
4897 struct zone *zone,
4898 unsigned long zone_start_pfn,
4899 unsigned long zonesize)
835c134e 4900{
7c45512d 4901 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
835c134e 4902 zone->pageblock_flags = NULL;
58a01a45 4903 if (usemapsize)
8f389a99
YL
4904 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4905 usemapsize);
835c134e
MG
4906}
4907#else
7c45512d
LT
4908static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4909 unsigned long zone_start_pfn, unsigned long zonesize) {}
835c134e
MG
4910#endif /* CONFIG_SPARSEMEM */
4911
d9c23400 4912#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
ba72cb8c 4913
d9c23400 4914/* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
ca57df79 4915void __init set_pageblock_order(void)
d9c23400 4916{
955c1cd7
AM
4917 unsigned int order;
4918
d9c23400
MG
4919 /* Check that pageblock_nr_pages has not already been setup */
4920 if (pageblock_order)
4921 return;
4922
955c1cd7
AM
4923 if (HPAGE_SHIFT > PAGE_SHIFT)
4924 order = HUGETLB_PAGE_ORDER;
4925 else
4926 order = MAX_ORDER - 1;
4927
d9c23400
MG
4928 /*
4929 * Assume the largest contiguous order of interest is a huge page.
955c1cd7
AM
4930 * This value may be variable depending on boot parameters on IA64 and
4931 * powerpc.
d9c23400
MG
4932 */
4933 pageblock_order = order;
4934}
4935#else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4936
ba72cb8c
MG
4937/*
4938 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
955c1cd7
AM
4939 * is unused as pageblock_order is set at compile-time. See
4940 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4941 * the kernel config
ba72cb8c 4942 */
ca57df79 4943void __init set_pageblock_order(void)
ba72cb8c 4944{
ba72cb8c 4945}
d9c23400
MG
4946
4947#endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4948
01cefaef
JL
4949static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
4950 unsigned long present_pages)
4951{
4952 unsigned long pages = spanned_pages;
4953
4954 /*
4955 * Provide a more accurate estimation if there are holes within
4956 * the zone and SPARSEMEM is in use. If there are holes within the
4957 * zone, each populated memory region may cost us one or two extra
4958 * memmap pages due to alignment because memmap pages for each
4959 * populated regions may not naturally algined on page boundary.
4960 * So the (present_pages >> 4) heuristic is a tradeoff for that.
4961 */
4962 if (spanned_pages > present_pages + (present_pages >> 4) &&
4963 IS_ENABLED(CONFIG_SPARSEMEM))
4964 pages = present_pages;
4965
4966 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
4967}
4968
6fa3eb70
S
4969#ifdef CONFIG_MTKPASR
4970extern void init_mtkpasr_range(struct zone *zone);
4971#else
4972#define init_mtkpasr_range(zone) do {} while (0)
4973#endif
4974
1da177e4
LT
4975/*
4976 * Set up the zone data structures:
4977 * - mark all pages reserved
4978 * - mark all memory queues empty
4979 * - clear the memory bitmaps
6527af5d
MK
4980 *
4981 * NOTE: pgdat should get zeroed by caller.
1da177e4 4982 */
b5a0e011 4983static void __paginginit free_area_init_core(struct pglist_data *pgdat,
1da177e4
LT
4984 unsigned long *zones_size, unsigned long *zholes_size)
4985{
2f1b6248 4986 enum zone_type j;
ed8ece2e 4987 int nid = pgdat->node_id;
1da177e4 4988 unsigned long zone_start_pfn = pgdat->node_start_pfn;
718127cc 4989 int ret;
1da177e4 4990
208d54e5 4991 pgdat_resize_init(pgdat);
8177a420
AA
4992#ifdef CONFIG_NUMA_BALANCING
4993 spin_lock_init(&pgdat->numabalancing_migrate_lock);
4994 pgdat->numabalancing_migrate_nr_pages = 0;
4995 pgdat->numabalancing_migrate_next_window = jiffies;
4996#endif
1da177e4 4997 init_waitqueue_head(&pgdat->kswapd_wait);
5515061d 4998 init_waitqueue_head(&pgdat->pfmemalloc_wait);
52d4b9ac 4999 pgdat_page_cgroup_init(pgdat);
5f63b720 5000
1da177e4
LT
5001 for (j = 0; j < MAX_NR_ZONES; j++) {
5002 struct zone *zone = pgdat->node_zones + j;
9feedc9d 5003 unsigned long size, realsize, freesize, memmap_pages;
1da177e4 5004
c713216d 5005 size = zone_spanned_pages_in_node(nid, j, zones_size);
9feedc9d 5006 realsize = freesize = size - zone_absent_pages_in_node(nid, j,
c713216d 5007 zholes_size);
1da177e4 5008
0e0b864e 5009 /*
9feedc9d 5010 * Adjust freesize so that it accounts for how much memory
0e0b864e
MG
5011 * is used by this zone for memmap. This affects the watermark
5012 * and per-cpu initialisations
5013 */
01cefaef 5014 memmap_pages = calc_memmap_size(size, realsize);
9feedc9d
JL
5015 if (freesize >= memmap_pages) {
5016 freesize -= memmap_pages;
5594c8c8
YL
5017 if (memmap_pages)
5018 printk(KERN_DEBUG
5019 " %s zone: %lu pages used for memmap\n",
5020 zone_names[j], memmap_pages);
0e0b864e
MG
5021 } else
5022 printk(KERN_WARNING
9feedc9d
JL
5023 " %s zone: %lu pages exceeds freesize %lu\n",
5024 zone_names[j], memmap_pages, freesize);
0e0b864e 5025
6267276f 5026 /* Account for reserved pages */
9feedc9d
JL
5027 if (j == 0 && freesize > dma_reserve) {
5028 freesize -= dma_reserve;
d903ef9f 5029 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
6267276f 5030 zone_names[0], dma_reserve);
0e0b864e
MG
5031 }
5032
98d2b0eb 5033 if (!is_highmem_idx(j))
9feedc9d 5034 nr_kernel_pages += freesize;
01cefaef
JL
5035 /* Charge for highmem memmap if there are enough kernel pages */
5036 else if (nr_kernel_pages > memmap_pages * 2)
5037 nr_kernel_pages -= memmap_pages;
9feedc9d 5038 nr_all_pages += freesize;
1da177e4
LT
5039
5040 zone->spanned_pages = size;
306f2e9e 5041 zone->present_pages = realsize;
9feedc9d
JL
5042 /*
5043 * Set an approximate value for lowmem here, it will be adjusted
5044 * when the bootmem allocator frees pages into the buddy system.
5045 * And all highmem pages will be managed by the buddy system.
5046 */
5047 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
9614634f 5048#ifdef CONFIG_NUMA
d5f541ed 5049 zone->node = nid;
9feedc9d 5050 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
9614634f 5051 / 100;
9feedc9d 5052 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
9614634f 5053#endif
1da177e4
LT
5054 zone->name = zone_names[j];
5055 spin_lock_init(&zone->lock);
5056 spin_lock_init(&zone->lru_lock);
bdc8cb98 5057 zone_seqlock_init(zone);
1da177e4 5058 zone->zone_pgdat = pgdat;
1da177e4 5059
ed8ece2e 5060 zone_pcp_init(zone);
bea8c150 5061 lruvec_init(&zone->lruvec);
1da177e4
LT
5062 if (!size)
5063 continue;
5064
955c1cd7 5065 set_pageblock_order();
7c45512d 5066 setup_usemap(pgdat, zone, zone_start_pfn, size);
a2f3aa02
DH
5067 ret = init_currently_empty_zone(zone, zone_start_pfn,
5068 size, MEMMAP_EARLY);
718127cc 5069 BUG_ON(ret);
76cdd58e 5070 memmap_init(size, nid, j, zone_start_pfn);
1da177e4 5071 zone_start_pfn += size;
1da177e4 5072 }
6fa3eb70
S
5073
5074 /* Initialize the imposed range of active PASR: only to create a range in HIGHMEM zone! */
5075 init_mtkpasr_range(pgdat->node_zones);
1da177e4
LT
5076}
5077
577a32f6 5078static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
1da177e4 5079{
1da177e4
LT
5080 /* Skip empty nodes */
5081 if (!pgdat->node_spanned_pages)
5082 return;
5083
d41dee36 5084#ifdef CONFIG_FLAT_NODE_MEM_MAP
1da177e4
LT
5085 /* ia64 gets its own node_mem_map, before this, without bootmem */
5086 if (!pgdat->node_mem_map) {
e984bb43 5087 unsigned long size, start, end;
d41dee36
AW
5088 struct page *map;
5089
e984bb43
BP
5090 /*
5091 * The zone's endpoints aren't required to be MAX_ORDER
5092 * aligned but the node_mem_map endpoints must be in order
5093 * for the buddy allocator to function correctly.
5094 */
5095 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
108bcc96 5096 end = pgdat_end_pfn(pgdat);
e984bb43
BP
5097 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5098 size = (end - start) * sizeof(struct page);
6f167ec7
DH
5099 map = alloc_remap(pgdat->node_id, size);
5100 if (!map)
8f389a99 5101 map = alloc_bootmem_node_nopanic(pgdat, size);
e984bb43 5102 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
1da177e4 5103 }
12d810c1 5104#ifndef CONFIG_NEED_MULTIPLE_NODES
1da177e4
LT
5105 /*
5106 * With no DISCONTIG, the global mem_map is just set as node 0's
5107 */
c713216d 5108 if (pgdat == NODE_DATA(0)) {
1da177e4 5109 mem_map = NODE_DATA(0)->node_mem_map;
0ee332c1 5110#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
c713216d 5111 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
467bc461 5112 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
0ee332c1 5113#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 5114 }
1da177e4 5115#endif
d41dee36 5116#endif /* CONFIG_FLAT_NODE_MEM_MAP */
1da177e4
LT
5117}
5118
9109fb7b
JW
5119void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5120 unsigned long node_start_pfn, unsigned long *zholes_size)
1da177e4 5121{
9109fb7b
JW
5122 pg_data_t *pgdat = NODE_DATA(nid);
5123
88fdf75d 5124 /* pg_data_t should be reset to zero when it's allocated */
8783b6e2 5125 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
88fdf75d 5126
1da177e4
LT
5127 pgdat->node_id = nid;
5128 pgdat->node_start_pfn = node_start_pfn;
957f822a 5129 init_zone_allows_reclaim(nid);
c713216d 5130 calculate_node_totalpages(pgdat, zones_size, zholes_size);
1da177e4
LT
5131
5132 alloc_node_mem_map(pgdat);
e8c27ac9
YL
5133#ifdef CONFIG_FLAT_NODE_MEM_MAP
5134 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5135 nid, (unsigned long)pgdat,
5136 (unsigned long)pgdat->node_mem_map);
5137#endif
1da177e4
LT
5138
5139 free_area_init_core(pgdat, zones_size, zholes_size);
5140}
5141
0ee332c1 5142#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
418508c1
MS
5143
5144#if MAX_NUMNODES > 1
5145/*
5146 * Figure out the number of possible node ids.
5147 */
f9872caf 5148void __init setup_nr_node_ids(void)
418508c1
MS
5149{
5150 unsigned int node;
5151 unsigned int highest = 0;
5152
5153 for_each_node_mask(node, node_possible_map)
5154 highest = node;
5155 nr_node_ids = highest + 1;
5156}
418508c1
MS
5157#endif
5158
1e01979c
TH
5159/**
5160 * node_map_pfn_alignment - determine the maximum internode alignment
5161 *
5162 * This function should be called after node map is populated and sorted.
5163 * It calculates the maximum power of two alignment which can distinguish
5164 * all the nodes.
5165 *
5166 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5167 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5168 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5169 * shifted, 1GiB is enough and this function will indicate so.
5170 *
5171 * This is used to test whether pfn -> nid mapping of the chosen memory
5172 * model has fine enough granularity to avoid incorrect mapping for the
5173 * populated node map.
5174 *
5175 * Returns the determined alignment in pfn's. 0 if there is no alignment
5176 * requirement (single node).
5177 */
5178unsigned long __init node_map_pfn_alignment(void)
5179{
5180 unsigned long accl_mask = 0, last_end = 0;
c13291a5 5181 unsigned long start, end, mask;
1e01979c 5182 int last_nid = -1;
c13291a5 5183 int i, nid;
1e01979c 5184
c13291a5 5185 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
1e01979c
TH
5186 if (!start || last_nid < 0 || last_nid == nid) {
5187 last_nid = nid;
5188 last_end = end;
5189 continue;
5190 }
5191
5192 /*
5193 * Start with a mask granular enough to pin-point to the
5194 * start pfn and tick off bits one-by-one until it becomes
5195 * too coarse to separate the current node from the last.
5196 */
5197 mask = ~((1 << __ffs(start)) - 1);
5198 while (mask && last_end <= (start & (mask << 1)))
5199 mask <<= 1;
5200
5201 /* accumulate all internode masks */
5202 accl_mask |= mask;
5203 }
5204
5205 /* convert mask to number of pages */
5206 return ~accl_mask + 1;
5207}
5208
a6af2bc3 5209/* Find the lowest pfn for a node */
b69a7288 5210static unsigned long __init find_min_pfn_for_node(int nid)
c713216d 5211{
a6af2bc3 5212 unsigned long min_pfn = ULONG_MAX;
c13291a5
TH
5213 unsigned long start_pfn;
5214 int i;
1abbfb41 5215
c13291a5
TH
5216 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5217 min_pfn = min(min_pfn, start_pfn);
c713216d 5218
a6af2bc3
MG
5219 if (min_pfn == ULONG_MAX) {
5220 printk(KERN_WARNING
2bc0d261 5221 "Could not find start_pfn for node %d\n", nid);
a6af2bc3
MG
5222 return 0;
5223 }
5224
5225 return min_pfn;
c713216d
MG
5226}
5227
5228/**
5229 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5230 *
5231 * It returns the minimum PFN based on information provided via
88ca3b94 5232 * add_active_range().
c713216d
MG
5233 */
5234unsigned long __init find_min_pfn_with_active_regions(void)
5235{
5236 return find_min_pfn_for_node(MAX_NUMNODES);
5237}
5238
37b07e41
LS
5239/*
5240 * early_calculate_totalpages()
5241 * Sum pages in active regions for movable zone.
4b0ef1fe 5242 * Populate N_MEMORY for calculating usable_nodes.
37b07e41 5243 */
484f51f8 5244static unsigned long __init early_calculate_totalpages(void)
7e63efef 5245{
7e63efef 5246 unsigned long totalpages = 0;
c13291a5
TH
5247 unsigned long start_pfn, end_pfn;
5248 int i, nid;
5249
5250 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5251 unsigned long pages = end_pfn - start_pfn;
7e63efef 5252
37b07e41
LS
5253 totalpages += pages;
5254 if (pages)
4b0ef1fe 5255 node_set_state(nid, N_MEMORY);
37b07e41
LS
5256 }
5257 return totalpages;
7e63efef
MG
5258}
5259
2a1e274a
MG
5260/*
5261 * Find the PFN the Movable zone begins in each node. Kernel memory
5262 * is spread evenly between nodes as long as the nodes have enough
5263 * memory. When they don't, some nodes will have more kernelcore than
5264 * others
5265 */
b224ef85 5266static void __init find_zone_movable_pfns_for_nodes(void)
2a1e274a
MG
5267{
5268 int i, nid;
5269 unsigned long usable_startpfn;
5270 unsigned long kernelcore_node, kernelcore_remaining;
66918dcd 5271 /* save the state before borrow the nodemask */
4b0ef1fe 5272 nodemask_t saved_node_state = node_states[N_MEMORY];
37b07e41 5273 unsigned long totalpages = early_calculate_totalpages();
4b0ef1fe 5274 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
2a1e274a 5275
7e63efef
MG
5276 /*
5277 * If movablecore was specified, calculate what size of
5278 * kernelcore that corresponds so that memory usable for
5279 * any allocation type is evenly spread. If both kernelcore
5280 * and movablecore are specified, then the value of kernelcore
5281 * will be used for required_kernelcore if it's greater than
5282 * what movablecore would have allowed.
5283 */
5284 if (required_movablecore) {
7e63efef
MG
5285 unsigned long corepages;
5286
5287 /*
5288 * Round-up so that ZONE_MOVABLE is at least as large as what
5289 * was requested by the user
5290 */
5291 required_movablecore =
5292 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5293 corepages = totalpages - required_movablecore;
5294
5295 required_kernelcore = max(required_kernelcore, corepages);
5296 }
5297
20e6926d
YL
5298 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
5299 if (!required_kernelcore)
66918dcd 5300 goto out;
2a1e274a
MG
5301
5302 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
20e6926d 5303 find_usable_zone_for_movable();
2a1e274a
MG
5304 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5305
5306restart:
5307 /* Spread kernelcore memory as evenly as possible throughout nodes */
5308 kernelcore_node = required_kernelcore / usable_nodes;
4b0ef1fe 5309 for_each_node_state(nid, N_MEMORY) {
c13291a5
TH
5310 unsigned long start_pfn, end_pfn;
5311
2a1e274a
MG
5312 /*
5313 * Recalculate kernelcore_node if the division per node
5314 * now exceeds what is necessary to satisfy the requested
5315 * amount of memory for the kernel
5316 */
5317 if (required_kernelcore < kernelcore_node)
5318 kernelcore_node = required_kernelcore / usable_nodes;
5319
5320 /*
5321 * As the map is walked, we track how much memory is usable
5322 * by the kernel using kernelcore_remaining. When it is
5323 * 0, the rest of the node is usable by ZONE_MOVABLE
5324 */
5325 kernelcore_remaining = kernelcore_node;
5326
5327 /* Go through each range of PFNs within this node */
c13291a5 5328 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
2a1e274a
MG
5329 unsigned long size_pages;
5330
c13291a5 5331 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
2a1e274a
MG
5332 if (start_pfn >= end_pfn)
5333 continue;
5334
5335 /* Account for what is only usable for kernelcore */
5336 if (start_pfn < usable_startpfn) {
5337 unsigned long kernel_pages;
5338 kernel_pages = min(end_pfn, usable_startpfn)
5339 - start_pfn;
5340
5341 kernelcore_remaining -= min(kernel_pages,
5342 kernelcore_remaining);
5343 required_kernelcore -= min(kernel_pages,
5344 required_kernelcore);
5345
5346 /* Continue if range is now fully accounted */
5347 if (end_pfn <= usable_startpfn) {
5348
5349 /*
5350 * Push zone_movable_pfn to the end so
5351 * that if we have to rebalance
5352 * kernelcore across nodes, we will
5353 * not double account here
5354 */
5355 zone_movable_pfn[nid] = end_pfn;
5356 continue;
5357 }
5358 start_pfn = usable_startpfn;
5359 }
5360
5361 /*
5362 * The usable PFN range for ZONE_MOVABLE is from
5363 * start_pfn->end_pfn. Calculate size_pages as the
5364 * number of pages used as kernelcore
5365 */
5366 size_pages = end_pfn - start_pfn;
5367 if (size_pages > kernelcore_remaining)
5368 size_pages = kernelcore_remaining;
5369 zone_movable_pfn[nid] = start_pfn + size_pages;
5370
5371 /*
5372 * Some kernelcore has been met, update counts and
5373 * break if the kernelcore for this node has been
5374 * satisified
5375 */
5376 required_kernelcore -= min(required_kernelcore,
5377 size_pages);
5378 kernelcore_remaining -= size_pages;
5379 if (!kernelcore_remaining)
5380 break;
5381 }
5382 }
5383
5384 /*
5385 * If there is still required_kernelcore, we do another pass with one
5386 * less node in the count. This will push zone_movable_pfn[nid] further
5387 * along on the nodes that still have memory until kernelcore is
5388 * satisified
5389 */
5390 usable_nodes--;
5391 if (usable_nodes && required_kernelcore > usable_nodes)
5392 goto restart;
5393
5394 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5395 for (nid = 0; nid < MAX_NUMNODES; nid++)
5396 zone_movable_pfn[nid] =
5397 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
66918dcd 5398
20e6926d 5399out:
66918dcd 5400 /* restore the node_state */
4b0ef1fe 5401 node_states[N_MEMORY] = saved_node_state;
2a1e274a
MG
5402}
5403
4b0ef1fe
LJ
5404/* Any regular or high memory on that node ? */
5405static void check_for_memory(pg_data_t *pgdat, int nid)
37b07e41 5406{
37b07e41
LS
5407 enum zone_type zone_type;
5408
4b0ef1fe
LJ
5409 if (N_MEMORY == N_NORMAL_MEMORY)
5410 return;
5411
5412 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
37b07e41 5413 struct zone *zone = &pgdat->node_zones[zone_type];
d0048b0e 5414 if (zone->present_pages) {
4b0ef1fe
LJ
5415 node_set_state(nid, N_HIGH_MEMORY);
5416 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5417 zone_type <= ZONE_NORMAL)
5418 node_set_state(nid, N_NORMAL_MEMORY);
d0048b0e
BL
5419 break;
5420 }
37b07e41 5421 }
37b07e41
LS
5422}
5423
c713216d
MG
5424/**
5425 * free_area_init_nodes - Initialise all pg_data_t and zone data
88ca3b94 5426 * @max_zone_pfn: an array of max PFNs for each zone
c713216d
MG
5427 *
5428 * This will call free_area_init_node() for each active node in the system.
5429 * Using the page ranges provided by add_active_range(), the size of each
5430 * zone in each node and their holes is calculated. If the maximum PFN
5431 * between two adjacent zones match, it is assumed that the zone is empty.
5432 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5433 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5434 * starts where the previous one ended. For example, ZONE_DMA32 starts
5435 * at arch_max_dma_pfn.
5436 */
5437void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5438{
c13291a5
TH
5439 unsigned long start_pfn, end_pfn;
5440 int i, nid;
a6af2bc3 5441
c713216d
MG
5442 /* Record where the zone boundaries are */
5443 memset(arch_zone_lowest_possible_pfn, 0,
5444 sizeof(arch_zone_lowest_possible_pfn));
5445 memset(arch_zone_highest_possible_pfn, 0,
5446 sizeof(arch_zone_highest_possible_pfn));
5447 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
5448 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
5449 for (i = 1; i < MAX_NR_ZONES; i++) {
2a1e274a
MG
5450 if (i == ZONE_MOVABLE)
5451 continue;
c713216d
MG
5452 arch_zone_lowest_possible_pfn[i] =
5453 arch_zone_highest_possible_pfn[i-1];
5454 arch_zone_highest_possible_pfn[i] =
5455 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
5456 }
2a1e274a
MG
5457 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5458 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5459
5460 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5461 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
b224ef85 5462 find_zone_movable_pfns_for_nodes();
c713216d 5463
c713216d 5464 /* Print out the zone ranges */
a62e2f4f 5465 printk("Zone ranges:\n");
2a1e274a
MG
5466 for (i = 0; i < MAX_NR_ZONES; i++) {
5467 if (i == ZONE_MOVABLE)
5468 continue;
155cbfc8 5469 printk(KERN_CONT " %-8s ", zone_names[i]);
72f0ba02
DR
5470 if (arch_zone_lowest_possible_pfn[i] ==
5471 arch_zone_highest_possible_pfn[i])
155cbfc8 5472 printk(KERN_CONT "empty\n");
72f0ba02 5473 else
a62e2f4f
BH
5474 printk(KERN_CONT "[mem %0#10lx-%0#10lx]\n",
5475 arch_zone_lowest_possible_pfn[i] << PAGE_SHIFT,
5476 (arch_zone_highest_possible_pfn[i]
5477 << PAGE_SHIFT) - 1);
2a1e274a
MG
5478 }
5479
5480 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
a62e2f4f 5481 printk("Movable zone start for each node\n");
2a1e274a
MG
5482 for (i = 0; i < MAX_NUMNODES; i++) {
5483 if (zone_movable_pfn[i])
a62e2f4f
BH
5484 printk(" Node %d: %#010lx\n", i,
5485 zone_movable_pfn[i] << PAGE_SHIFT);
2a1e274a 5486 }
c713216d 5487
f2d52fe5 5488 /* Print out the early node map */
a62e2f4f 5489 printk("Early memory node ranges\n");
c13291a5 5490 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
a62e2f4f
BH
5491 printk(" node %3d: [mem %#010lx-%#010lx]\n", nid,
5492 start_pfn << PAGE_SHIFT, (end_pfn << PAGE_SHIFT) - 1);
c713216d
MG
5493
5494 /* Initialise every node */
708614e6 5495 mminit_verify_pageflags_layout();
8ef82866 5496 setup_nr_node_ids();
c713216d
MG
5497 for_each_online_node(nid) {
5498 pg_data_t *pgdat = NODE_DATA(nid);
9109fb7b 5499 free_area_init_node(nid, NULL,
c713216d 5500 find_min_pfn_for_node(nid), NULL);
37b07e41
LS
5501
5502 /* Any memory on that node */
5503 if (pgdat->node_present_pages)
4b0ef1fe
LJ
5504 node_set_state(nid, N_MEMORY);
5505 check_for_memory(pgdat, nid);
c713216d
MG
5506 }
5507}
2a1e274a 5508
7e63efef 5509static int __init cmdline_parse_core(char *p, unsigned long *core)
2a1e274a
MG
5510{
5511 unsigned long long coremem;
5512 if (!p)
5513 return -EINVAL;
5514
5515 coremem = memparse(p, &p);
7e63efef 5516 *core = coremem >> PAGE_SHIFT;
2a1e274a 5517
7e63efef 5518 /* Paranoid check that UL is enough for the coremem value */
2a1e274a
MG
5519 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5520
5521 return 0;
5522}
ed7ed365 5523
7e63efef
MG
5524/*
5525 * kernelcore=size sets the amount of memory for use for allocations that
5526 * cannot be reclaimed or migrated.
5527 */
5528static int __init cmdline_parse_kernelcore(char *p)
5529{
5530 return cmdline_parse_core(p, &required_kernelcore);
5531}
5532
5533/*
5534 * movablecore=size sets the amount of memory for use for allocations that
5535 * can be reclaimed or migrated.
5536 */
5537static int __init cmdline_parse_movablecore(char *p)
5538{
5539 return cmdline_parse_core(p, &required_movablecore);
5540}
5541
ed7ed365 5542early_param("kernelcore", cmdline_parse_kernelcore);
7e63efef 5543early_param("movablecore", cmdline_parse_movablecore);
ed7ed365 5544
0ee332c1 5545#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 5546
69afade7
JL
5547unsigned long free_reserved_area(unsigned long start, unsigned long end,
5548 int poison, char *s)
5549{
5550 unsigned long pages, pos;
5551
5552 pos = start = PAGE_ALIGN(start);
5553 end &= PAGE_MASK;
5554 for (pages = 0; pos < end; pos += PAGE_SIZE, pages++) {
5555 if (poison)
5556 memset((void *)pos, poison, PAGE_SIZE);
bb3ec6b0 5557 free_reserved_page(virt_to_page((void *)pos));
69afade7
JL
5558 }
5559
5560 if (pages && s)
5561 pr_info("Freeing %s memory: %ldK (%lx - %lx)\n",
5562 s, pages << (PAGE_SHIFT - 10), start, end);
5563
5564 return pages;
5565}
5566
cfa11e08
JL
5567#ifdef CONFIG_HIGHMEM
5568void free_highmem_page(struct page *page)
5569{
5570 __free_reserved_page(page);
5571 totalram_pages++;
5572 totalhigh_pages++;
5573}
5574#endif
5575
0e0b864e 5576/**
88ca3b94
RD
5577 * set_dma_reserve - set the specified number of pages reserved in the first zone
5578 * @new_dma_reserve: The number of pages to mark reserved
0e0b864e
MG
5579 *
5580 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5581 * In the DMA zone, a significant percentage may be consumed by kernel image
5582 * and other unfreeable allocations which can skew the watermarks badly. This
88ca3b94
RD
5583 * function may optionally be used to account for unfreeable pages in the
5584 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5585 * smaller per-cpu batchsize.
0e0b864e
MG
5586 */
5587void __init set_dma_reserve(unsigned long new_dma_reserve)
5588{
5589 dma_reserve = new_dma_reserve;
5590}
5591
1da177e4
LT
5592void __init free_area_init(unsigned long *zones_size)
5593{
9109fb7b 5594 free_area_init_node(0, zones_size,
1da177e4
LT
5595 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5596}
1da177e4 5597
1da177e4
LT
5598static int page_alloc_cpu_notify(struct notifier_block *self,
5599 unsigned long action, void *hcpu)
5600{
5601 int cpu = (unsigned long)hcpu;
1da177e4 5602
8bb78442 5603 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
f0cb3c76 5604 lru_add_drain_cpu(cpu);
9f8f2172
CL
5605 drain_pages(cpu);
5606
5607 /*
5608 * Spill the event counters of the dead processor
5609 * into the current processors event counters.
5610 * This artificially elevates the count of the current
5611 * processor.
5612 */
f8891e5e 5613 vm_events_fold_cpu(cpu);
9f8f2172
CL
5614
5615 /*
5616 * Zero the differential counters of the dead processor
5617 * so that the vm statistics are consistent.
5618 *
5619 * This is only okay since the processor is dead and cannot
5620 * race with what we are doing.
5621 */
2244b95a 5622 refresh_cpu_vm_stats(cpu);
1da177e4
LT
5623 }
5624 return NOTIFY_OK;
5625}
1da177e4
LT
5626
5627void __init page_alloc_init(void)
5628{
5629 hotcpu_notifier(page_alloc_cpu_notify, 0);
5630}
5631
cb45b0e9
HA
5632/*
5633 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5634 * or min_free_kbytes changes.
5635 */
5636static void calculate_totalreserve_pages(void)
5637{
5638 struct pglist_data *pgdat;
5639 unsigned long reserve_pages = 0;
2f6726e5 5640 enum zone_type i, j;
cb45b0e9
HA
5641
5642 for_each_online_pgdat(pgdat) {
5643 for (i = 0; i < MAX_NR_ZONES; i++) {
5644 struct zone *zone = pgdat->node_zones + i;
5645 unsigned long max = 0;
5646
5647 /* Find valid and maximum lowmem_reserve in the zone */
5648 for (j = i; j < MAX_NR_ZONES; j++) {
5649 if (zone->lowmem_reserve[j] > max)
5650 max = zone->lowmem_reserve[j];
5651 }
5652
41858966
MG
5653 /* we treat the high watermark as reserved pages. */
5654 max += high_wmark_pages(zone);
cb45b0e9 5655
b40da049
JL
5656 if (max > zone->managed_pages)
5657 max = zone->managed_pages;
cb45b0e9 5658 reserve_pages += max;
ab8fabd4
JW
5659 /*
5660 * Lowmem reserves are not available to
5661 * GFP_HIGHUSER page cache allocations and
5662 * kswapd tries to balance zones to their high
5663 * watermark. As a result, neither should be
5664 * regarded as dirtyable memory, to prevent a
5665 * situation where reclaim has to clean pages
5666 * in order to balance the zones.
5667 */
5668 zone->dirty_balance_reserve = max;
cb45b0e9
HA
5669 }
5670 }
ab8fabd4 5671 dirty_balance_reserve = reserve_pages;
cb45b0e9
HA
5672 totalreserve_pages = reserve_pages;
5673}
5674
1da177e4
LT
5675/*
5676 * setup_per_zone_lowmem_reserve - called whenever
5677 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5678 * has a correct pages reserved value, so an adequate number of
5679 * pages are left in the zone after a successful __alloc_pages().
5680 */
5681static void setup_per_zone_lowmem_reserve(void)
5682{
5683 struct pglist_data *pgdat;
2f6726e5 5684 enum zone_type j, idx;
1da177e4 5685
ec936fc5 5686 for_each_online_pgdat(pgdat) {
1da177e4
LT
5687 for (j = 0; j < MAX_NR_ZONES; j++) {
5688 struct zone *zone = pgdat->node_zones + j;
b40da049 5689 unsigned long managed_pages = zone->managed_pages;
1da177e4
LT
5690
5691 zone->lowmem_reserve[j] = 0;
5692
2f6726e5
CL
5693 idx = j;
5694 while (idx) {
1da177e4
LT
5695 struct zone *lower_zone;
5696
2f6726e5
CL
5697 idx--;
5698
1da177e4
LT
5699 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5700 sysctl_lowmem_reserve_ratio[idx] = 1;
5701
5702 lower_zone = pgdat->node_zones + idx;
b40da049 5703 lower_zone->lowmem_reserve[j] = managed_pages /
1da177e4 5704 sysctl_lowmem_reserve_ratio[idx];
b40da049 5705 managed_pages += lower_zone->managed_pages;
1da177e4
LT
5706 }
5707 }
5708 }
cb45b0e9
HA
5709
5710 /* update totalreserve_pages */
5711 calculate_totalreserve_pages();
1da177e4
LT
5712}
5713
cfd3da1e 5714static void __setup_per_zone_wmarks(void)
1da177e4
LT
5715{
5716 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6fa3eb70 5717 unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
1da177e4
LT
5718 unsigned long lowmem_pages = 0;
5719 struct zone *zone;
5720 unsigned long flags;
5721
5722 /* Calculate total number of !ZONE_HIGHMEM pages */
5723 for_each_zone(zone) {
5724 if (!is_highmem(zone))
b40da049 5725 lowmem_pages += zone->managed_pages;
1da177e4
LT
5726 }
5727
5728 for_each_zone(zone) {
6fa3eb70 5729 u64 min, low;
ac924c60 5730
1125b4e3 5731 spin_lock_irqsave(&zone->lock, flags);
6fa3eb70
S
5732 min = (u64)pages_min * zone->managed_pages;
5733 do_div(min, lowmem_pages);
5734 low = (u64)pages_low * zone->managed_pages;
5735 do_div(low, vm_total_pages);
5736
1da177e4
LT
5737 if (is_highmem(zone)) {
5738 /*
669ed175
NP
5739 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5740 * need highmem pages, so cap pages_min to a small
5741 * value here.
5742 *
41858966 5743 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
669ed175
NP
5744 * deltas controls asynch page reclaim, and so should
5745 * not be capped for highmem.
1da177e4 5746 */
90ae8d67 5747 unsigned long min_pages;
1da177e4 5748
b40da049 5749 min_pages = zone->managed_pages / 1024;
90ae8d67 5750 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
41858966 5751 zone->watermark[WMARK_MIN] = min_pages;
1da177e4 5752 } else {
669ed175
NP
5753 /*
5754 * If it's a lowmem zone, reserve a number of pages
1da177e4
LT
5755 * proportionate to the zone's size.
5756 */
6fa3eb70 5757 zone->watermark[WMARK_MIN] = min;
1da177e4
LT
5758 }
5759
6fa3eb70
S
5760 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) +
5761 low + (min >> 2);
5762 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) +
5763 low + (min >> 1);
49f223a9 5764
56fd56b8 5765 setup_zone_migrate_reserve(zone);
1125b4e3 5766 spin_unlock_irqrestore(&zone->lock, flags);
1da177e4 5767 }
cb45b0e9
HA
5768
5769 /* update totalreserve_pages */
5770 calculate_totalreserve_pages();
1da177e4
LT
5771}
5772
cfd3da1e
MG
5773/**
5774 * setup_per_zone_wmarks - called when min_free_kbytes changes
5775 * or when memory is hot-{added|removed}
5776 *
5777 * Ensures that the watermark[min,low,high] values for each zone are set
5778 * correctly with respect to min_free_kbytes.
5779 */
5780void setup_per_zone_wmarks(void)
5781{
5782 mutex_lock(&zonelists_mutex);
5783 __setup_per_zone_wmarks();
5784 mutex_unlock(&zonelists_mutex);
5785}
5786
55a4462a 5787/*
556adecb
RR
5788 * The inactive anon list should be small enough that the VM never has to
5789 * do too much work, but large enough that each inactive page has a chance
5790 * to be referenced again before it is swapped out.
5791 *
5792 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5793 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5794 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5795 * the anonymous pages are kept on the inactive list.
5796 *
5797 * total target max
5798 * memory ratio inactive anon
5799 * -------------------------------------
5800 * 10MB 1 5MB
5801 * 100MB 1 50MB
5802 * 1GB 3 250MB
5803 * 10GB 10 0.9GB
5804 * 100GB 31 3GB
5805 * 1TB 101 10GB
5806 * 10TB 320 32GB
5807 */
1b79acc9 5808static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
556adecb 5809{
96cb4df5 5810 unsigned int gb, ratio;
556adecb 5811
96cb4df5 5812 /* Zone size in gigabytes */
b40da049 5813 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
96cb4df5 5814 if (gb)
556adecb 5815 ratio = int_sqrt(10 * gb);
96cb4df5
MK
5816 else
5817 ratio = 1;
556adecb 5818
96cb4df5
MK
5819 zone->inactive_ratio = ratio;
5820}
556adecb 5821
839a4fcc 5822static void __meminit setup_per_zone_inactive_ratio(void)
96cb4df5
MK
5823{
5824 struct zone *zone;
5825
5826 for_each_zone(zone)
5827 calculate_zone_inactive_ratio(zone);
556adecb
RR
5828}
5829
1da177e4
LT
5830/*
5831 * Initialise min_free_kbytes.
5832 *
5833 * For small machines we want it small (128k min). For large machines
5834 * we want it large (64MB max). But it is not linear, because network
5835 * bandwidth does not increase linearly with machine size. We use
5836 *
5837 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5838 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5839 *
5840 * which yields
5841 *
5842 * 16MB: 512k
5843 * 32MB: 724k
5844 * 64MB: 1024k
5845 * 128MB: 1448k
5846 * 256MB: 2048k
5847 * 512MB: 2896k
5848 * 1024MB: 4096k
5849 * 2048MB: 5792k
5850 * 4096MB: 8192k
5851 * 8192MB: 11584k
5852 * 16384MB: 16384k
5853 */
1b79acc9 5854int __meminit init_per_zone_wmark_min(void)
1da177e4
LT
5855{
5856 unsigned long lowmem_kbytes;
5857
5858 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5859
5860 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5861 if (min_free_kbytes < 128)
5862 min_free_kbytes = 128;
5863 if (min_free_kbytes > 65536)
5864 min_free_kbytes = 65536;
bc75d33f 5865 setup_per_zone_wmarks();
a6cccdc3 5866 refresh_zone_stat_thresholds();
1da177e4 5867 setup_per_zone_lowmem_reserve();
556adecb 5868 setup_per_zone_inactive_ratio();
1da177e4
LT
5869 return 0;
5870}
bc75d33f 5871module_init(init_per_zone_wmark_min)
1da177e4
LT
5872
5873/*
5874 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5875 * that we can call two helper functions whenever min_free_kbytes
6fa3eb70 5876 * or extra_free_kbytes changes.
1da177e4
LT
5877 */
5878int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
8d65af78 5879 void __user *buffer, size_t *length, loff_t *ppos)
1da177e4 5880{
8d65af78 5881 proc_dointvec(table, write, buffer, length, ppos);
3b1d92c5 5882 if (write)
bc75d33f 5883 setup_per_zone_wmarks();
1da177e4
LT
5884 return 0;
5885}
5886
9614634f
CL
5887#ifdef CONFIG_NUMA
5888int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5889 void __user *buffer, size_t *length, loff_t *ppos)
9614634f
CL
5890{
5891 struct zone *zone;
5892 int rc;
5893
8d65af78 5894 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
9614634f
CL
5895 if (rc)
5896 return rc;
5897
5898 for_each_zone(zone)
b40da049 5899 zone->min_unmapped_pages = (zone->managed_pages *
9614634f
CL
5900 sysctl_min_unmapped_ratio) / 100;
5901 return 0;
5902}
0ff38490
CL
5903
5904int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5905 void __user *buffer, size_t *length, loff_t *ppos)
0ff38490
CL
5906{
5907 struct zone *zone;
5908 int rc;
5909
8d65af78 5910 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
0ff38490
CL
5911 if (rc)
5912 return rc;
5913
5914 for_each_zone(zone)
b40da049 5915 zone->min_slab_pages = (zone->managed_pages *
0ff38490
CL
5916 sysctl_min_slab_ratio) / 100;
5917 return 0;
5918}
9614634f
CL
5919#endif
5920
1da177e4
LT
5921/*
5922 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5923 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5924 * whenever sysctl_lowmem_reserve_ratio changes.
5925 *
5926 * The reserve ratio obviously has absolutely no relation with the
41858966 5927 * minimum watermarks. The lowmem reserve ratio can only make sense
1da177e4
LT
5928 * if in function of the boot time zone sizes.
5929 */
5930int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5931 void __user *buffer, size_t *length, loff_t *ppos)
1da177e4 5932{
8d65af78 5933 proc_dointvec_minmax(table, write, buffer, length, ppos);
1da177e4
LT
5934 setup_per_zone_lowmem_reserve();
5935 return 0;
5936}
5937
8ad4b1fb
RS
5938/*
5939 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5940 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
5941 * can have before it gets flushed back to buddy allocator.
5942 */
5943
5944int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
8d65af78 5945 void __user *buffer, size_t *length, loff_t *ppos)
8ad4b1fb
RS
5946{
5947 struct zone *zone;
5948 unsigned int cpu;
5949 int ret;
5950
8d65af78 5951 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
93278814 5952 if (!write || (ret < 0))
8ad4b1fb 5953 return ret;
364df0eb 5954 for_each_populated_zone(zone) {
99dcc3e5 5955 for_each_possible_cpu(cpu) {
8ad4b1fb 5956 unsigned long high;
b40da049 5957 high = zone->managed_pages / percpu_pagelist_fraction;
99dcc3e5
CL
5958 setup_pagelist_highmark(
5959 per_cpu_ptr(zone->pageset, cpu), high);
8ad4b1fb
RS
5960 }
5961 }
5962 return 0;
5963}
5964
f034b5d4 5965int hashdist = HASHDIST_DEFAULT;
1da177e4
LT
5966
5967#ifdef CONFIG_NUMA
5968static int __init set_hashdist(char *str)
5969{
5970 if (!str)
5971 return 0;
5972 hashdist = simple_strtoul(str, &str, 0);
5973 return 1;
5974}
5975__setup("hashdist=", set_hashdist);
5976#endif
5977
5978/*
5979 * allocate a large system hash table from bootmem
5980 * - it is assumed that the hash table must contain an exact power-of-2
5981 * quantity of entries
5982 * - limit is the number of hash buckets, not the total allocation size
5983 */
5984void *__init alloc_large_system_hash(const char *tablename,
5985 unsigned long bucketsize,
5986 unsigned long numentries,
5987 int scale,
5988 int flags,
5989 unsigned int *_hash_shift,
5990 unsigned int *_hash_mask,
31fe62b9
TB
5991 unsigned long low_limit,
5992 unsigned long high_limit)
1da177e4 5993{
31fe62b9 5994 unsigned long long max = high_limit;
1da177e4
LT
5995 unsigned long log2qty, size;
5996 void *table = NULL;
5997
5998 /* allow the kernel cmdline to have a say */
5999 if (!numentries) {
6000 /* round applicable memory size up to nearest megabyte */
04903664 6001 numentries = nr_kernel_pages;
1da177e4
LT
6002 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
6003 numentries >>= 20 - PAGE_SHIFT;
6004 numentries <<= 20 - PAGE_SHIFT;
6005
6006 /* limit to 1 bucket per 2^scale bytes of low memory */
6007 if (scale > PAGE_SHIFT)
6008 numentries >>= (scale - PAGE_SHIFT);
6009 else
6010 numentries <<= (PAGE_SHIFT - scale);
9ab37b8f
PM
6011
6012 /* Make sure we've got at least a 0-order allocation.. */
2c85f51d
JB
6013 if (unlikely(flags & HASH_SMALL)) {
6014 /* Makes no sense without HASH_EARLY */
6015 WARN_ON(!(flags & HASH_EARLY));
6016 if (!(numentries >> *_hash_shift)) {
6017 numentries = 1UL << *_hash_shift;
6018 BUG_ON(!numentries);
6019 }
6020 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
9ab37b8f 6021 numentries = PAGE_SIZE / bucketsize;
1da177e4 6022 }
6e692ed3 6023 numentries = roundup_pow_of_two(numentries);
1da177e4
LT
6024
6025 /* limit allocation size to 1/16 total memory by default */
6026 if (max == 0) {
6027 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6028 do_div(max, bucketsize);
6029 }
074b8517 6030 max = min(max, 0x80000000ULL);
1da177e4 6031
31fe62b9
TB
6032 if (numentries < low_limit)
6033 numentries = low_limit;
1da177e4
LT
6034 if (numentries > max)
6035 numentries = max;
6036
f0d1b0b3 6037 log2qty = ilog2(numentries);
1da177e4
LT
6038
6039 do {
6040 size = bucketsize << log2qty;
6041 if (flags & HASH_EARLY)
74768ed8 6042 table = alloc_bootmem_nopanic(size);
1da177e4
LT
6043 else if (hashdist)
6044 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6045 else {
1037b83b
ED
6046 /*
6047 * If bucketsize is not a power-of-two, we may free
a1dd268c
MG
6048 * some pages at the end of hash table which
6049 * alloc_pages_exact() automatically does
1037b83b 6050 */
264ef8a9 6051 if (get_order(size) < MAX_ORDER) {
a1dd268c 6052 table = alloc_pages_exact(size, GFP_ATOMIC);
264ef8a9
CM
6053 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6054 }
1da177e4
LT
6055 }
6056 } while (!table && size > PAGE_SIZE && --log2qty);
6057
6058 if (!table)
6059 panic("Failed to allocate %s hash table\n", tablename);
6060
f241e660 6061 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
1da177e4 6062 tablename,
f241e660 6063 (1UL << log2qty),
f0d1b0b3 6064 ilog2(size) - PAGE_SHIFT,
1da177e4
LT
6065 size);
6066
6067 if (_hash_shift)
6068 *_hash_shift = log2qty;
6069 if (_hash_mask)
6070 *_hash_mask = (1 << log2qty) - 1;
6071
6072 return table;
6073}
a117e66e 6074
835c134e
MG
6075/* Return a pointer to the bitmap storing bits affecting a block of pages */
6076static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6077 unsigned long pfn)
6078{
6079#ifdef CONFIG_SPARSEMEM
6080 return __pfn_to_section(pfn)->pageblock_flags;
6081#else
6082 return zone->pageblock_flags;
6083#endif /* CONFIG_SPARSEMEM */
6084}
6085
6086static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6087{
6088#ifdef CONFIG_SPARSEMEM
6089 pfn &= (PAGES_PER_SECTION-1);
d9c23400 6090 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
835c134e 6091#else
c060f943 6092 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
d9c23400 6093 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
835c134e
MG
6094#endif /* CONFIG_SPARSEMEM */
6095}
6096
6097/**
d9c23400 6098 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
835c134e
MG
6099 * @page: The page within the block of interest
6100 * @start_bitidx: The first bit of interest to retrieve
6101 * @end_bitidx: The last bit of interest
6102 * returns pageblock_bits flags
6103 */
6104unsigned long get_pageblock_flags_group(struct page *page,
6105 int start_bitidx, int end_bitidx)
6106{
6107 struct zone *zone;
6108 unsigned long *bitmap;
6109 unsigned long pfn, bitidx;
6110 unsigned long flags = 0;
6111 unsigned long value = 1;
6112
6113 zone = page_zone(page);
6114 pfn = page_to_pfn(page);
6115 bitmap = get_pageblock_bitmap(zone, pfn);
6116 bitidx = pfn_to_bitidx(zone, pfn);
6117
6118 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
6119 if (test_bit(bitidx + start_bitidx, bitmap))
6120 flags |= value;
6220ec78 6121
835c134e
MG
6122 return flags;
6123}
6124
6125/**
d9c23400 6126 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
835c134e
MG
6127 * @page: The page within the block of interest
6128 * @start_bitidx: The first bit of interest
6129 * @end_bitidx: The last bit of interest
6130 * @flags: The flags to set
6131 */
6132void set_pageblock_flags_group(struct page *page, unsigned long flags,
6133 int start_bitidx, int end_bitidx)
6134{
6135 struct zone *zone;
6136 unsigned long *bitmap;
6137 unsigned long pfn, bitidx;
6138 unsigned long value = 1;
6139
6140 zone = page_zone(page);
6141 pfn = page_to_pfn(page);
6142 bitmap = get_pageblock_bitmap(zone, pfn);
6143 bitidx = pfn_to_bitidx(zone, pfn);
108bcc96 6144 VM_BUG_ON(!zone_spans_pfn(zone, pfn));
835c134e
MG
6145
6146 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
6147 if (flags & value)
6148 __set_bit(bitidx + start_bitidx, bitmap);
6149 else
6150 __clear_bit(bitidx + start_bitidx, bitmap);
6151}
a5d76b54
KH
6152
6153/*
80934513
MK
6154 * This function checks whether pageblock includes unmovable pages or not.
6155 * If @count is not zero, it is okay to include less @count unmovable pages
6156 *
6157 * PageLRU check wihtout isolation or lru_lock could race so that
6158 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6159 * expect this function should be exact.
a5d76b54 6160 */
b023f468
WC
6161bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6162 bool skip_hwpoisoned_pages)
49ac8255
KH
6163{
6164 unsigned long pfn, iter, found;
47118af0
MN
6165 int mt;
6166
49ac8255
KH
6167 /*
6168 * For avoiding noise data, lru_add_drain_all() should be called
80934513 6169 * If ZONE_MOVABLE, the zone never contains unmovable pages
49ac8255
KH
6170 */
6171 if (zone_idx(zone) == ZONE_MOVABLE)
80934513 6172 return false;
47118af0
MN
6173 mt = get_pageblock_migratetype(page);
6174 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
80934513 6175 return false;
49ac8255
KH
6176
6177 pfn = page_to_pfn(page);
6178 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6179 unsigned long check = pfn + iter;
6180
29723fcc 6181 if (!pfn_valid_within(check))
49ac8255 6182 continue;
29723fcc 6183
49ac8255 6184 page = pfn_to_page(check);
97d255c8
MK
6185 /*
6186 * We can't use page_count without pin a page
6187 * because another CPU can free compound page.
6188 * This check already skips compound tails of THP
6189 * because their page->_count is zero at all time.
6190 */
6191 if (!atomic_read(&page->_count)) {
49ac8255
KH
6192 if (PageBuddy(page))
6193 iter += (1 << page_order(page)) - 1;
6194 continue;
6195 }
97d255c8 6196
b023f468
WC
6197 /*
6198 * The HWPoisoned page may be not in buddy system, and
6199 * page_count() is not 0.
6200 */
6201 if (skip_hwpoisoned_pages && PageHWPoison(page))
6202 continue;
6203
49ac8255
KH
6204 if (!PageLRU(page))
6205 found++;
6206 /*
6207 * If there are RECLAIMABLE pages, we need to check it.
6208 * But now, memory offline itself doesn't call shrink_slab()
6209 * and it still to be fixed.
6210 */
6211 /*
6212 * If the page is not RAM, page_count()should be 0.
6213 * we don't need more check. This is an _used_ not-movable page.
6214 *
6215 * The problematic thing here is PG_reserved pages. PG_reserved
6216 * is set to both of a memory hole page and a _used_ kernel
6217 * page at boot.
6218 */
6219 if (found > count)
80934513 6220 return true;
49ac8255 6221 }
80934513 6222 return false;
49ac8255
KH
6223}
6224
6225bool is_pageblock_removable_nolock(struct page *page)
6226{
656a0706
MH
6227 struct zone *zone;
6228 unsigned long pfn;
687875fb
MH
6229
6230 /*
6231 * We have to be careful here because we are iterating over memory
6232 * sections which are not zone aware so we might end up outside of
6233 * the zone but still within the section.
656a0706
MH
6234 * We have to take care about the node as well. If the node is offline
6235 * its NODE_DATA will be NULL - see page_zone.
687875fb 6236 */
656a0706
MH
6237 if (!node_online(page_to_nid(page)))
6238 return false;
6239
6240 zone = page_zone(page);
6241 pfn = page_to_pfn(page);
108bcc96 6242 if (!zone_spans_pfn(zone, pfn))
687875fb
MH
6243 return false;
6244
b023f468 6245 return !has_unmovable_pages(zone, page, 0, true);
a5d76b54 6246}
0c0e6195 6247
041d3a8c
MN
6248#ifdef CONFIG_CMA
6249
6250static unsigned long pfn_max_align_down(unsigned long pfn)
6251{
6252 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6253 pageblock_nr_pages) - 1);
6254}
6255
6256static unsigned long pfn_max_align_up(unsigned long pfn)
6257{
6258 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6259 pageblock_nr_pages));
6260}
6261
041d3a8c 6262/* [start, end) must belong to a single zone. */
bb13ffeb
MG
6263static int __alloc_contig_migrate_range(struct compact_control *cc,
6264 unsigned long start, unsigned long end)
041d3a8c
MN
6265{
6266 /* This function is based on compact_zone() from compaction.c. */
beb51eaa 6267 unsigned long nr_reclaimed;
041d3a8c
MN
6268 unsigned long pfn = start;
6269 unsigned int tries = 0;
6270 int ret = 0;
6271
be49a6e1 6272 migrate_prep();
041d3a8c 6273
bb13ffeb 6274 while (pfn < end || !list_empty(&cc->migratepages)) {
041d3a8c
MN
6275 if (fatal_signal_pending(current)) {
6276 ret = -EINTR;
6277 break;
6278 }
6279
bb13ffeb
MG
6280 if (list_empty(&cc->migratepages)) {
6281 cc->nr_migratepages = 0;
6282 pfn = isolate_migratepages_range(cc->zone, cc,
e46a2879 6283 pfn, end, true);
041d3a8c
MN
6284 if (!pfn) {
6285 ret = -EINTR;
6286 break;
6287 }
6288 tries = 0;
6289 } else if (++tries == 5) {
6290 ret = ret < 0 ? ret : -EBUSY;
6291 break;
6292 }
6293
beb51eaa
MK
6294 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6295 &cc->migratepages);
6296 cc->nr_migratepages -= nr_reclaimed;
02c6de8d 6297
9c620e2b
HD
6298 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6299 0, MIGRATE_SYNC, MR_CMA);
041d3a8c 6300 }
2a6f5124
SP
6301 if (ret < 0) {
6302 putback_movable_pages(&cc->migratepages);
6303 return ret;
6304 }
6305 return 0;
041d3a8c
MN
6306}
6307
6308/**
6309 * alloc_contig_range() -- tries to allocate given range of pages
6310 * @start: start PFN to allocate
6311 * @end: one-past-the-last PFN to allocate
0815f3d8
MN
6312 * @migratetype: migratetype of the underlaying pageblocks (either
6313 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6314 * in range must have the same migratetype and it must
6315 * be either of the two.
041d3a8c
MN
6316 *
6317 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6318 * aligned, however it's the caller's responsibility to guarantee that
6319 * we are the only thread that changes migrate type of pageblocks the
6320 * pages fall in.
6321 *
6322 * The PFN range must belong to a single zone.
6323 *
6324 * Returns zero on success or negative error code. On success all
6325 * pages which PFN is in [start, end) are allocated for the caller and
6326 * need to be freed with free_contig_range().
6327 */
0815f3d8
MN
6328int alloc_contig_range(unsigned long start, unsigned long end,
6329 unsigned migratetype)
041d3a8c 6330{
041d3a8c
MN
6331 unsigned long outer_start, outer_end;
6332 int ret = 0, order;
6333
bb13ffeb
MG
6334 struct compact_control cc = {
6335 .nr_migratepages = 0,
6336 .order = -1,
6337 .zone = page_zone(pfn_to_page(start)),
6338 .sync = true,
6339 .ignore_skip_hint = true,
6340 };
6341 INIT_LIST_HEAD(&cc.migratepages);
6342
041d3a8c
MN
6343 /*
6344 * What we do here is we mark all pageblocks in range as
6345 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6346 * have different sizes, and due to the way page allocator
6347 * work, we align the range to biggest of the two pages so
6348 * that page allocator won't try to merge buddies from
6349 * different pageblocks and change MIGRATE_ISOLATE to some
6350 * other migration type.
6351 *
6352 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6353 * migrate the pages from an unaligned range (ie. pages that
6354 * we are interested in). This will put all the pages in
6355 * range back to page allocator as MIGRATE_ISOLATE.
6356 *
6357 * When this is done, we take the pages in range from page
6358 * allocator removing them from the buddy system. This way
6359 * page allocator will never consider using them.
6360 *
6361 * This lets us mark the pageblocks back as
6362 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6363 * aligned range but not in the unaligned, original range are
6364 * put back to page allocator so that buddy can use them.
6365 */
6366
6367 ret = start_isolate_page_range(pfn_max_align_down(start),
b023f468
WC
6368 pfn_max_align_up(end), migratetype,
6369 false);
041d3a8c 6370 if (ret)
86a595f9 6371 return ret;
041d3a8c 6372
bb13ffeb 6373 ret = __alloc_contig_migrate_range(&cc, start, end);
041d3a8c
MN
6374 if (ret)
6375 goto done;
6376
6377 /*
6378 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6379 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6380 * more, all pages in [start, end) are free in page allocator.
6381 * What we are going to do is to allocate all pages from
6382 * [start, end) (that is remove them from page allocator).
6383 *
6384 * The only problem is that pages at the beginning and at the
6385 * end of interesting range may be not aligned with pages that
6386 * page allocator holds, ie. they can be part of higher order
6387 * pages. Because of this, we reserve the bigger range and
6388 * once this is done free the pages we are not interested in.
6389 *
6390 * We don't have to hold zone->lock here because the pages are
6391 * isolated thus they won't get removed from buddy.
6392 */
6393
6394 lru_add_drain_all();
6395 drain_all_pages();
6396
6397 order = 0;
6398 outer_start = start;
6399 while (!PageBuddy(pfn_to_page(outer_start))) {
6400 if (++order >= MAX_ORDER) {
6401 ret = -EBUSY;
6402 goto done;
6403 }
6404 outer_start &= ~0UL << order;
6405 }
6406
6407 /* Make sure the range is really isolated. */
b023f468 6408 if (test_pages_isolated(outer_start, end, false)) {
041d3a8c
MN
6409 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6410 outer_start, end);
6411 ret = -EBUSY;
6412 goto done;
6413 }
6414
49f223a9
MS
6415
6416 /* Grab isolated pages from freelists. */
bb13ffeb 6417 outer_end = isolate_freepages_range(&cc, outer_start, end);
041d3a8c
MN
6418 if (!outer_end) {
6419 ret = -EBUSY;
6420 goto done;
6421 }
6422
6423 /* Free head and tail (if any) */
6424 if (start != outer_start)
6425 free_contig_range(outer_start, start - outer_start);
6426 if (end != outer_end)
6427 free_contig_range(end, outer_end - end);
6428
6429done:
6430 undo_isolate_page_range(pfn_max_align_down(start),
0815f3d8 6431 pfn_max_align_up(end), migratetype);
041d3a8c
MN
6432 return ret;
6433}
6434
6435void free_contig_range(unsigned long pfn, unsigned nr_pages)
6436{
bcc2b02f
MS
6437 unsigned int count = 0;
6438
6439 for (; nr_pages--; pfn++) {
6440 struct page *page = pfn_to_page(pfn);
6441
6442 count += page_count(page) != 1;
6443 __free_page(page);
6444 }
6445 WARN(count != 0, "%d pages are still in use!\n", count);
041d3a8c
MN
6446}
6447#endif
6448
4ed7e022
JL
6449#ifdef CONFIG_MEMORY_HOTPLUG
6450static int __meminit __zone_pcp_update(void *data)
6451{
6452 struct zone *zone = data;
6453 int cpu;
6454 unsigned long batch = zone_batchsize(zone), flags;
6455
6456 for_each_possible_cpu(cpu) {
6457 struct per_cpu_pageset *pset;
6458 struct per_cpu_pages *pcp;
6459
6460 pset = per_cpu_ptr(zone->pageset, cpu);
6461 pcp = &pset->pcp;
6462
6463 local_irq_save(flags);
6464 if (pcp->count > 0)
6465 free_pcppages_bulk(zone, pcp->count, pcp);
5a883813 6466 drain_zonestat(zone, pset);
4ed7e022
JL
6467 setup_pageset(pset, batch);
6468 local_irq_restore(flags);
6469 }
6470 return 0;
6471}
6472
6473void __meminit zone_pcp_update(struct zone *zone)
6474{
6475 stop_machine(__zone_pcp_update, zone, NULL);
6476}
6477#endif
6478
340175b7
JL
6479void zone_pcp_reset(struct zone *zone)
6480{
6481 unsigned long flags;
5a883813
MK
6482 int cpu;
6483 struct per_cpu_pageset *pset;
340175b7
JL
6484
6485 /* avoid races with drain_pages() */
6486 local_irq_save(flags);
6487 if (zone->pageset != &boot_pageset) {
5a883813
MK
6488 for_each_online_cpu(cpu) {
6489 pset = per_cpu_ptr(zone->pageset, cpu);
6490 drain_zonestat(zone, pset);
6491 }
340175b7
JL
6492 free_percpu(zone->pageset);
6493 zone->pageset = &boot_pageset;
6494 }
6495 local_irq_restore(flags);
6496}
6497
6dcd73d7 6498#ifdef CONFIG_MEMORY_HOTREMOVE
0c0e6195
KH
6499/*
6500 * All pages in the range must be isolated before calling this.
6501 */
6502void
6503__offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6504{
6505 struct page *page;
6506 struct zone *zone;
6507 int order, i;
6508 unsigned long pfn;
6509 unsigned long flags;
6510 /* find the first valid pfn */
6511 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6512 if (pfn_valid(pfn))
6513 break;
6514 if (pfn == end_pfn)
6515 return;
6516 zone = page_zone(pfn_to_page(pfn));
6517 spin_lock_irqsave(&zone->lock, flags);
6518 pfn = start_pfn;
6519 while (pfn < end_pfn) {
6520 if (!pfn_valid(pfn)) {
6521 pfn++;
6522 continue;
6523 }
6524 page = pfn_to_page(pfn);
b023f468
WC
6525 /*
6526 * The HWPoisoned page may be not in buddy system, and
6527 * page_count() is not 0.
6528 */
6529 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6530 pfn++;
6531 SetPageReserved(page);
6532 continue;
6533 }
6534
0c0e6195
KH
6535 BUG_ON(page_count(page));
6536 BUG_ON(!PageBuddy(page));
6537 order = page_order(page);
6538#ifdef CONFIG_DEBUG_VM
6539 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6540 pfn, 1 << order, end_pfn);
6541#endif
6542 list_del(&page->lru);
6543 rmv_page_order(page);
6544 zone->free_area[order].nr_free--;
76422578
WL
6545#ifdef CONFIG_HIGHMEM
6546 if (PageHighMem(page))
6547 totalhigh_pages -= 1 << order;
6548#endif
0c0e6195
KH
6549 for (i = 0; i < (1 << order); i++)
6550 SetPageReserved((page+i));
6551 pfn += (1 << order);
6552 }
6553 spin_unlock_irqrestore(&zone->lock, flags);
6554}
6555#endif
8d22ba1b
WF
6556
6557#ifdef CONFIG_MEMORY_FAILURE
6558bool is_free_buddy_page(struct page *page)
6559{
6560 struct zone *zone = page_zone(page);
6561 unsigned long pfn = page_to_pfn(page);
6562 unsigned long flags;
6563 int order;
6564
6565 spin_lock_irqsave(&zone->lock, flags);
6566 for (order = 0; order < MAX_ORDER; order++) {
6567 struct page *page_head = page - (pfn & ((1 << order) - 1));
6568
6569 if (PageBuddy(page_head) && page_order(page_head) >= order)
6570 break;
6571 }
6572 spin_unlock_irqrestore(&zone->lock, flags);
6573
6574 return order < MAX_ORDER;
6575}
6576#endif
718a3821 6577
51300cef 6578static const struct trace_print_flags pageflag_names[] = {
718a3821
WF
6579 {1UL << PG_locked, "locked" },
6580 {1UL << PG_error, "error" },
6581 {1UL << PG_referenced, "referenced" },
6582 {1UL << PG_uptodate, "uptodate" },
6583 {1UL << PG_dirty, "dirty" },
6584 {1UL << PG_lru, "lru" },
6585 {1UL << PG_active, "active" },
6586 {1UL << PG_slab, "slab" },
6587 {1UL << PG_owner_priv_1, "owner_priv_1" },
6588 {1UL << PG_arch_1, "arch_1" },
6589 {1UL << PG_reserved, "reserved" },
6590 {1UL << PG_private, "private" },
6591 {1UL << PG_private_2, "private_2" },
6592 {1UL << PG_writeback, "writeback" },
6593#ifdef CONFIG_PAGEFLAGS_EXTENDED
6594 {1UL << PG_head, "head" },
6595 {1UL << PG_tail, "tail" },
6596#else
6597 {1UL << PG_compound, "compound" },
6598#endif
6599 {1UL << PG_swapcache, "swapcache" },
6600 {1UL << PG_mappedtodisk, "mappedtodisk" },
6601 {1UL << PG_reclaim, "reclaim" },
718a3821
WF
6602 {1UL << PG_swapbacked, "swapbacked" },
6603 {1UL << PG_unevictable, "unevictable" },
6604#ifdef CONFIG_MMU
6605 {1UL << PG_mlocked, "mlocked" },
6606#endif
6607#ifdef CONFIG_ARCH_USES_PG_UNCACHED
6608 {1UL << PG_uncached, "uncached" },
6609#endif
6610#ifdef CONFIG_MEMORY_FAILURE
6611 {1UL << PG_hwpoison, "hwpoison" },
be9cd873
GS
6612#endif
6613#ifdef CONFIG_TRANSPARENT_HUGEPAGE
6614 {1UL << PG_compound_lock, "compound_lock" },
718a3821 6615#endif
718a3821
WF
6616};
6617
6618static void dump_page_flags(unsigned long flags)
6619{
6620 const char *delim = "";
6621 unsigned long mask;
6622 int i;
6623
51300cef 6624 BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS);
acc50c11 6625
718a3821
WF
6626 printk(KERN_ALERT "page flags: %#lx(", flags);
6627
6628 /* remove zone id */
6629 flags &= (1UL << NR_PAGEFLAGS) - 1;
6630
51300cef 6631 for (i = 0; i < ARRAY_SIZE(pageflag_names) && flags; i++) {
718a3821
WF
6632
6633 mask = pageflag_names[i].mask;
6634 if ((flags & mask) != mask)
6635 continue;
6636
6637 flags &= ~mask;
6638 printk("%s%s", delim, pageflag_names[i].name);
6639 delim = "|";
6640 }
6641
6642 /* check for left over flags */
6643 if (flags)
6644 printk("%s%#lx", delim, flags);
6645
6646 printk(")\n");
6647}
6648
6649void dump_page(struct page *page)
6650{
6651 printk(KERN_ALERT
6652 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
4e9f64c4 6653 page, atomic_read(&page->_count), page_mapcount(page),
718a3821
WF
6654 page->mapping, page->index);
6655 dump_page_flags(page->flags);
f212ad7c 6656 mem_cgroup_print_bad_page(page);
718a3821 6657}
6fa3eb70
S
6658
6659#ifdef CONFIG_MTKPASR
6660/* Find free pages - Caller must acquire zone->lock */
6661int pasr_find_free_page(struct page *page, struct list_head *freelist)
6662{
6663 struct zone *z = page_zone(page);
6664 unsigned int order;
6665 int free_count, i;
6666
6667 /* Remove page from free list */
6668 order = page_order(page);
6669 list_del(&page->lru);
6670 z->free_area[order].nr_free--;
6671 rmv_page_order(page);
6672 __mod_zone_page_state(z, NR_FREE_PAGES, -(1UL << order));
6673
6674 /* Split into individual pages */
6675 set_page_refcounted(page);
6676 split_page(page, order);
6677
6678 /* Add to freelist */
6679 free_count = 1 << order;
6680 for (i = 0; i < free_count; i++) {
6681 list_add(&page->lru, freelist);
6682 page++;
6683 }
6684
6685 return free_count;
6686}
6687EXPORT_SYMBOL(pasr_find_free_page);
6688
6689/* Given an offset and return corresponding valid, inuse page */
6690struct page *pasr_acquire_inuse_page(enum zone_type ztype, unsigned long which_pfn)
6691{
6692 struct page *page;
6693
6694 /* Check & Return inuse page */
6695 if (pfn_valid(which_pfn)) {
6696 page = pfn_to_page(which_pfn);
6697 if (page_count(page) != 0) {
6698 return page;
6699 }
6700 }
6701
6702 return NULL;
6703}
6704EXPORT_SYMBOL(pasr_acquire_inuse_page);
6705
6706/* Compute maximum safe order for page allocation */
6707int pasr_compute_safe_order(void)
6708{
6709 struct zone *z = &NODE_DATA(0)->node_zones[ZONE_NORMAL];
6710 int order;
6711 unsigned long watermark = low_wmark_pages(z);
6712 long free_pages = zone_page_state(z, NR_FREE_PAGES);
6713
6714 /* Start from order:1 to make system more robust */
6715 for (order = 1; order < MAX_ORDER; ++order) {
6716 if (!__zone_watermark_ok(z, order, (watermark + (1 << order)), 0, 0, free_pages)) {
6717 return (order - 2);
6718 }
6719 }
6720
6721 return (MAX_ORDER - 1);
6722}
6723EXPORT_SYMBOL(pasr_compute_safe_order);
6724#endif /* CONFIG_MTKPASR */