Merge tag 'v3.10.108' 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
e033782a
MH
2194 /*
2195 * PM-freezer should be notified that there might be an OOM killer on
2196 * its way to kill and wake somebody up. This is too early and we might
2197 * end up not killing anything but false positives are acceptable.
2198 * See freeze_processes.
2199 */
2200 note_oom_kill();
2201
11e33f6a
MG
2202 /*
2203 * Go through the zonelist yet one more time, keep very high watermark
2204 * here, this is only to catch a parallel oom killing, we must fail if
2205 * we're still under heavy pressure.
2206 */
2207 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2208 order, zonelist, high_zoneidx,
5117f45d 2209 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
3dd28266 2210 preferred_zone, migratetype);
7fb1d9fc 2211 if (page)
11e33f6a
MG
2212 goto out;
2213
4365a567
KH
2214 if (!(gfp_mask & __GFP_NOFAIL)) {
2215 /* The OOM killer will not help higher order allocs */
2216 if (order > PAGE_ALLOC_COSTLY_ORDER)
2217 goto out;
03668b3c
DR
2218 /* The OOM killer does not needlessly kill tasks for lowmem */
2219 if (high_zoneidx < ZONE_NORMAL)
2220 goto out;
4365a567
KH
2221 /*
2222 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2223 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2224 * The caller should handle page allocation failure by itself if
2225 * it specifies __GFP_THISNODE.
2226 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2227 */
2228 if (gfp_mask & __GFP_THISNODE)
2229 goto out;
2230 }
11e33f6a 2231 /* Exhausted what can be done so it's blamo time */
08ab9b10 2232 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
11e33f6a
MG
2233
2234out:
2235 clear_zonelist_oom(zonelist, gfp_mask);
2236 return page;
2237}
2238
56de7263
MG
2239#ifdef CONFIG_COMPACTION
2240/* Try memory compaction for high-order allocations before reclaim */
2241static struct page *
2242__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2243 struct zonelist *zonelist, enum zone_type high_zoneidx,
2244 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
66199712 2245 int migratetype, bool sync_migration,
c67fe375 2246 bool *contended_compaction, bool *deferred_compaction,
66199712 2247 unsigned long *did_some_progress)
56de7263 2248{
66199712 2249 if (!order)
56de7263
MG
2250 return NULL;
2251
aff62249 2252 if (compaction_deferred(preferred_zone, order)) {
66199712
MG
2253 *deferred_compaction = true;
2254 return NULL;
2255 }
2256
c06b1fca 2257 current->flags |= PF_MEMALLOC;
56de7263 2258 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
c67fe375 2259 nodemask, sync_migration,
8fb74b9f 2260 contended_compaction);
c06b1fca 2261 current->flags &= ~PF_MEMALLOC;
56de7263 2262
1fb3f8ca 2263 if (*did_some_progress != COMPACT_SKIPPED) {
8fb74b9f
MG
2264 struct page *page;
2265
56de7263
MG
2266 /* Page migration frees to the PCP lists but we want merging */
2267 drain_pages(get_cpu());
2268 put_cpu();
2269
2270 page = get_page_from_freelist(gfp_mask, nodemask,
2271 order, zonelist, high_zoneidx,
cfd19c5a
MG
2272 alloc_flags & ~ALLOC_NO_WATERMARKS,
2273 preferred_zone, migratetype);
56de7263 2274 if (page) {
62997027 2275 preferred_zone->compact_blockskip_flush = false;
4f92e258
MG
2276 preferred_zone->compact_considered = 0;
2277 preferred_zone->compact_defer_shift = 0;
aff62249
RR
2278 if (order >= preferred_zone->compact_order_failed)
2279 preferred_zone->compact_order_failed = order + 1;
56de7263
MG
2280 count_vm_event(COMPACTSUCCESS);
2281 return page;
2282 }
2283
2284 /*
2285 * It's bad if compaction run occurs and fails.
2286 * The most likely reason is that pages exist,
2287 * but not enough to satisfy watermarks.
2288 */
2289 count_vm_event(COMPACTFAIL);
66199712
MG
2290
2291 /*
2292 * As async compaction considers a subset of pageblocks, only
2293 * defer if the failure was a sync compaction failure.
2294 */
2295 if (sync_migration)
aff62249 2296 defer_compaction(preferred_zone, order);
56de7263
MG
2297
2298 cond_resched();
2299 }
2300
2301 return NULL;
2302}
2303#else
2304static inline struct page *
2305__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2306 struct zonelist *zonelist, enum zone_type high_zoneidx,
2307 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
66199712 2308 int migratetype, bool sync_migration,
c67fe375 2309 bool *contended_compaction, bool *deferred_compaction,
66199712 2310 unsigned long *did_some_progress)
56de7263
MG
2311{
2312 return NULL;
2313}
2314#endif /* CONFIG_COMPACTION */
2315
bba90710
MS
2316/* Perform direct synchronous page reclaim */
2317static int
2318__perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2319 nodemask_t *nodemask)
11e33f6a 2320{
11e33f6a 2321 struct reclaim_state reclaim_state;
bba90710 2322 int progress;
11e33f6a
MG
2323
2324 cond_resched();
2325
2326 /* We now go into synchronous reclaim */
2327 cpuset_memory_pressure_bump();
c06b1fca 2328 current->flags |= PF_MEMALLOC;
11e33f6a
MG
2329 lockdep_set_current_reclaim_state(gfp_mask);
2330 reclaim_state.reclaimed_slab = 0;
c06b1fca 2331 current->reclaim_state = &reclaim_state;
11e33f6a 2332
bba90710 2333 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
11e33f6a 2334
c06b1fca 2335 current->reclaim_state = NULL;
11e33f6a 2336 lockdep_clear_current_reclaim_state();
c06b1fca 2337 current->flags &= ~PF_MEMALLOC;
11e33f6a
MG
2338
2339 cond_resched();
2340
bba90710
MS
2341 return progress;
2342}
2343
2344/* The really slow allocator path where we enter direct reclaim */
2345static inline struct page *
2346__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2347 struct zonelist *zonelist, enum zone_type high_zoneidx,
2348 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2349 int migratetype, unsigned long *did_some_progress)
2350{
2351 struct page *page = NULL;
2352 bool drained = false;
2353
2354 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2355 nodemask);
9ee493ce
MG
2356 if (unlikely(!(*did_some_progress)))
2357 return NULL;
11e33f6a 2358
76d3fbf8 2359 /* After successful reclaim, reconsider all zones for allocation */
e5adfffc 2360 if (IS_ENABLED(CONFIG_NUMA))
76d3fbf8
MG
2361 zlc_clear_zones_full(zonelist);
2362
9ee493ce
MG
2363retry:
2364 page = get_page_from_freelist(gfp_mask, nodemask, order,
5117f45d 2365 zonelist, high_zoneidx,
cfd19c5a
MG
2366 alloc_flags & ~ALLOC_NO_WATERMARKS,
2367 preferred_zone, migratetype);
9ee493ce
MG
2368
2369 /*
2370 * If an allocation failed after direct reclaim, it could be because
2371 * pages are pinned on the per-cpu lists. Drain them and try again
2372 */
2373 if (!page && !drained) {
2374 drain_all_pages();
2375 drained = true;
2376 goto retry;
2377 }
2378
11e33f6a
MG
2379 return page;
2380}
2381
1da177e4 2382/*
11e33f6a
MG
2383 * This is called in the allocator slow-path if the allocation request is of
2384 * sufficient urgency to ignore watermarks and take other desperate measures
1da177e4 2385 */
11e33f6a
MG
2386static inline struct page *
2387__alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2388 struct zonelist *zonelist, enum zone_type high_zoneidx,
3dd28266
MG
2389 nodemask_t *nodemask, struct zone *preferred_zone,
2390 int migratetype)
11e33f6a
MG
2391{
2392 struct page *page;
2393
2394 do {
2395 page = get_page_from_freelist(gfp_mask, nodemask, order,
5117f45d 2396 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
3dd28266 2397 preferred_zone, migratetype);
11e33f6a
MG
2398
2399 if (!page && gfp_mask & __GFP_NOFAIL)
0e093d99 2400 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
11e33f6a
MG
2401 } while (!page && (gfp_mask & __GFP_NOFAIL));
2402
2403 return page;
2404}
2405
2406static inline
2407void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
99504748
MG
2408 enum zone_type high_zoneidx,
2409 enum zone_type classzone_idx)
1da177e4 2410{
dd1a239f
MG
2411 struct zoneref *z;
2412 struct zone *zone;
1da177e4 2413
11e33f6a 2414 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
99504748 2415 wakeup_kswapd(zone, order, classzone_idx);
11e33f6a 2416}
cf40bd16 2417
341ce06f
PZ
2418static inline int
2419gfp_to_alloc_flags(gfp_t gfp_mask)
2420{
341ce06f 2421 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
1144d70b 2422 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
1da177e4 2423
a56f57ff 2424 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
e6223a3b 2425 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
933e312e 2426
341ce06f
PZ
2427 /*
2428 * The caller may dip into page reserves a bit more if the caller
2429 * cannot run direct reclaim, or if the caller has realtime scheduling
2430 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1144d70b 2431 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
341ce06f 2432 */
e6223a3b 2433 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
1da177e4 2434
1144d70b 2435 if (atomic) {
5c3240d9 2436 /*
1144d70b
DR
2437 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2438 * if it can't schedule.
5c3240d9 2439 */
1144d70b 2440 if (!(gfp_mask & __GFP_NOMEMALLOC))
5c3240d9 2441 alloc_flags |= ALLOC_HARDER;
523b9458 2442 /*
1144d70b
DR
2443 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2444 * comment for __cpuset_node_allowed_softwall().
523b9458 2445 */
341ce06f 2446 alloc_flags &= ~ALLOC_CPUSET;
c06b1fca 2447 } else if (unlikely(rt_task(current)) && !in_interrupt())
341ce06f
PZ
2448 alloc_flags |= ALLOC_HARDER;
2449
b37f1dd0
MG
2450 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2451 if (gfp_mask & __GFP_MEMALLOC)
2452 alloc_flags |= ALLOC_NO_WATERMARKS;
907aed48
MG
2453 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2454 alloc_flags |= ALLOC_NO_WATERMARKS;
2455 else if (!in_interrupt() &&
2456 ((current->flags & PF_MEMALLOC) ||
2457 unlikely(test_thread_flag(TIF_MEMDIE))))
341ce06f 2458 alloc_flags |= ALLOC_NO_WATERMARKS;
1da177e4 2459 }
d95ea5d1
BZ
2460#ifdef CONFIG_CMA
2461 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2462 alloc_flags |= ALLOC_CMA;
2463#endif
341ce06f
PZ
2464 return alloc_flags;
2465}
2466
072bb0aa
MG
2467bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2468{
b37f1dd0 2469 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
072bb0aa
MG
2470}
2471
6fa3eb70
S
2472/* Add for kswapd need too much CPU ANR issue */
2473#ifdef CONFIG_MT_ENG_BUILD
2474static uint32_t wakeup_kswapd_count = 0;
2475static unsigned long print_wakeup_kswapd_timeout = 0;
2476
2477static uint32_t wakeup_kswapd_dump_log_order = 1;
2478static uint32_t wakeup_kswapd_dump_bt_order = 1000;
2479
2480module_param_named(dump_log_order, wakeup_kswapd_dump_log_order, uint, S_IRUGO | S_IWUSR);
2481module_param_named(dump_bt_order, wakeup_kswapd_dump_bt_order, uint, S_IRUGO | S_IWUSR);
2482#endif
2483
11e33f6a
MG
2484static inline struct page *
2485__alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2486 struct zonelist *zonelist, enum zone_type high_zoneidx,
3dd28266
MG
2487 nodemask_t *nodemask, struct zone *preferred_zone,
2488 int migratetype)
11e33f6a
MG
2489{
2490 const gfp_t wait = gfp_mask & __GFP_WAIT;
2491 struct page *page = NULL;
2492 int alloc_flags;
2493 unsigned long pages_reclaimed = 0;
2494 unsigned long did_some_progress;
77f1fe6b 2495 bool sync_migration = false;
66199712 2496 bool deferred_compaction = false;
c67fe375 2497 bool contended_compaction = false;
1da177e4 2498
72807a74
MG
2499 /*
2500 * In the slowpath, we sanity check order to avoid ever trying to
2501 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2502 * be using allocators in order of preference for an area that is
2503 * too large.
2504 */
1fc28b70
MG
2505 if (order >= MAX_ORDER) {
2506 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
72807a74 2507 return NULL;
1fc28b70 2508 }
1da177e4 2509
952f3b51
CL
2510 /*
2511 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2512 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2513 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2514 * using a larger set of nodes after it has established that the
2515 * allowed per node queues are empty and that nodes are
2516 * over allocated.
2517 */
e5adfffc
KS
2518 if (IS_ENABLED(CONFIG_NUMA) &&
2519 (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
952f3b51
CL
2520 goto nopage;
2521
cc4a6851 2522restart:
6fa3eb70
S
2523 if (!(gfp_mask & __GFP_NO_KSWAPD)) {
2524 #ifdef CONFIG_MT_ENG_BUILD
2525 int print_debug_info = 0;
2526 wakeup_kswapd_count++;
2527
2528 if (time_after_eq(jiffies, print_wakeup_kswapd_timeout)) {
2529 print_debug_info = 1;
2530 print_wakeup_kswapd_timeout = jiffies+HZ;
2531 }
2532 if(print_debug_info) {
2533 if(order >= wakeup_kswapd_dump_log_order) {
2534 pr_debug("[WAKEUP_KSWAPD]%s wakeup kswapd, order:%d, mode:0x%x, trigger_count:%d\n",
2535 current->comm, order, gfp_mask, wakeup_kswapd_count);
2536 }
2537
2538 if(order >= wakeup_kswapd_dump_bt_order) {
2539 pr_debug("[WAKEUP_KSWAPD]dump_stack\n");
2540 dump_stack();
2541 }
2542 wakeup_kswapd_count = 0;/*reset*/
2543 }
2544 #endif
caf49191
LT
2545 wake_all_kswapd(order, zonelist, high_zoneidx,
2546 zone_idx(preferred_zone));
6fa3eb70 2547 }
9bf2229f 2548 /*
7fb1d9fc
RS
2549 * OK, we're below the kswapd watermark and have kicked background
2550 * reclaim. Now things get more complex, so set up alloc_flags according
2551 * to how we want to proceed.
9bf2229f 2552 */
341ce06f 2553 alloc_flags = gfp_to_alloc_flags(gfp_mask);
1da177e4 2554
f33261d7
DR
2555 /*
2556 * Find the true preferred zone if the allocation is unconstrained by
2557 * cpusets.
2558 */
2559 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask)
2560 first_zones_zonelist(zonelist, high_zoneidx, NULL,
2561 &preferred_zone);
2562
cfa54a0f 2563rebalance:
341ce06f 2564 /* This is the last chance, in general, before the goto nopage. */
19770b32 2565 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
341ce06f
PZ
2566 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2567 preferred_zone, migratetype);
7fb1d9fc
RS
2568 if (page)
2569 goto got_pg;
1da177e4 2570
11e33f6a 2571 /* Allocate without watermarks if the context allows */
341ce06f 2572 if (alloc_flags & ALLOC_NO_WATERMARKS) {
183f6371
MG
2573 /*
2574 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
2575 * the allocation is high priority and these type of
2576 * allocations are system rather than user orientated
2577 */
2578 zonelist = node_zonelist(numa_node_id(), gfp_mask);
2579
341ce06f
PZ
2580 page = __alloc_pages_high_priority(gfp_mask, order,
2581 zonelist, high_zoneidx, nodemask,
2582 preferred_zone, migratetype);
cfd19c5a 2583 if (page) {
341ce06f 2584 goto got_pg;
cfd19c5a 2585 }
1da177e4
LT
2586 }
2587
2588 /* Atomic allocations - we can't balance anything */
2589 if (!wait)
2590 goto nopage;
2591
341ce06f 2592 /* Avoid recursion of direct reclaim */
c06b1fca 2593 if (current->flags & PF_MEMALLOC)
341ce06f
PZ
2594 goto nopage;
2595
6583bb64
DR
2596 /* Avoid allocations with no watermarks from looping endlessly */
2597 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2598 goto nopage;
2599
77f1fe6b
MG
2600 /*
2601 * Try direct compaction. The first pass is asynchronous. Subsequent
2602 * attempts after direct reclaim are synchronous
2603 */
56de7263
MG
2604 page = __alloc_pages_direct_compact(gfp_mask, order,
2605 zonelist, high_zoneidx,
2606 nodemask,
2607 alloc_flags, preferred_zone,
66199712 2608 migratetype, sync_migration,
c67fe375 2609 &contended_compaction,
66199712
MG
2610 &deferred_compaction,
2611 &did_some_progress);
56de7263
MG
2612 if (page)
2613 goto got_pg;
c6a140bf 2614 sync_migration = true;
56de7263 2615
31f8d42d
LT
2616 /*
2617 * If compaction is deferred for high-order allocations, it is because
2618 * sync compaction recently failed. In this is the case and the caller
2619 * requested a movable allocation that does not heavily disrupt the
2620 * system then fail the allocation instead of entering direct reclaim.
2621 */
2622 if ((deferred_compaction || contended_compaction) &&
caf49191 2623 (gfp_mask & __GFP_NO_KSWAPD))
31f8d42d 2624 goto nopage;
66199712 2625
11e33f6a
MG
2626 /* Try direct reclaim and then allocating */
2627 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2628 zonelist, high_zoneidx,
2629 nodemask,
5117f45d 2630 alloc_flags, preferred_zone,
3dd28266 2631 migratetype, &did_some_progress);
11e33f6a
MG
2632 if (page)
2633 goto got_pg;
1da177e4 2634
e33c3b5e 2635 /*
11e33f6a
MG
2636 * If we failed to make any progress reclaiming, then we are
2637 * running out of options and have to consider going OOM
e33c3b5e 2638 */
11e33f6a
MG
2639 if (!did_some_progress) {
2640 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
7f33d49a
RW
2641 if (oom_killer_disabled)
2642 goto nopage;
29fd66d2
DR
2643 /* Coredumps can quickly deplete all memory reserves */
2644 if ((current->flags & PF_DUMPCORE) &&
2645 !(gfp_mask & __GFP_NOFAIL))
2646 goto nopage;
11e33f6a
MG
2647 page = __alloc_pages_may_oom(gfp_mask, order,
2648 zonelist, high_zoneidx,
3dd28266
MG
2649 nodemask, preferred_zone,
2650 migratetype);
11e33f6a
MG
2651 if (page)
2652 goto got_pg;
1da177e4 2653
03668b3c
DR
2654 if (!(gfp_mask & __GFP_NOFAIL)) {
2655 /*
2656 * The oom killer is not called for high-order
2657 * allocations that may fail, so if no progress
2658 * is being made, there are no other options and
2659 * retrying is unlikely to help.
2660 */
2661 if (order > PAGE_ALLOC_COSTLY_ORDER)
2662 goto nopage;
2663 /*
2664 * The oom killer is not called for lowmem
2665 * allocations to prevent needlessly killing
2666 * innocent tasks.
2667 */
2668 if (high_zoneidx < ZONE_NORMAL)
2669 goto nopage;
2670 }
e2c55dc8 2671
ff0ceb9d
DR
2672 goto restart;
2673 }
1da177e4
LT
2674 }
2675
11e33f6a 2676 /* Check if we should retry the allocation */
a41f24ea 2677 pages_reclaimed += did_some_progress;
f90ac398
MG
2678 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2679 pages_reclaimed)) {
11e33f6a 2680 /* Wait for some write requests to complete then retry */
0e093d99 2681 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
1da177e4 2682 goto rebalance;
3e7d3449
MG
2683 } else {
2684 /*
2685 * High-order allocations do not necessarily loop after
2686 * direct reclaim and reclaim/compaction depends on compaction
2687 * being called after reclaim so call directly if necessary
2688 */
2689 page = __alloc_pages_direct_compact(gfp_mask, order,
2690 zonelist, high_zoneidx,
2691 nodemask,
2692 alloc_flags, preferred_zone,
66199712 2693 migratetype, sync_migration,
c67fe375 2694 &contended_compaction,
66199712
MG
2695 &deferred_compaction,
2696 &did_some_progress);
3e7d3449
MG
2697 if (page)
2698 goto got_pg;
1da177e4
LT
2699 }
2700
2701nopage:
a238ab5b 2702 warn_alloc_failed(gfp_mask, order, NULL);
b1eeab67 2703 return page;
1da177e4 2704got_pg:
b1eeab67
VN
2705 if (kmemcheck_enabled)
2706 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
11e33f6a 2707
072bb0aa 2708 return page;
1da177e4 2709}
11e33f6a 2710
6fa3eb70
S
2711#ifdef CONFIG_MTKPASR
2712extern void try_to_release_mtkpasr_page(int x);
2713#else
2714#define try_to_release_mtkpasr_page(x) do {} while (0)
2715#endif
2716
2717#ifdef CONFIG_MT_ENG_BUILD
2718
2719#define __LOG_PAGE_ALLOC_ORDER__
2720#define __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2721#endif
2722
2723#ifdef __LOG_PAGE_ALLOC_ORDER__
2724
2725#define LOG_PAGE_LIMIT_NUM 10
2726#define LOG_PAGE_LIMIT_TIME 1000
2727
2728//static int page_alloc_order_log[11] = {0};
2729//static int page_alloc_order_log_size = 11;
2730static int page_alloc_dump_order_threshold = 4;
2731static int page_alloc_log_order_threshold = 3;
2732static u8 log_counter = 0;
2733static unsigned long log_time_c0 = 0;
2734static u8 log_limit_enable = 0;
2735
2736//module_param_array_named(order_log, page_alloc_order_log, int, &page_alloc_order_log_size,
2737// S_IRUGO);
2738//Jack remove page_alloc_order_log array for non-used
2739module_param_named(dump_order_threshold, page_alloc_dump_order_threshold, int, S_IRUGO | S_IWUSR);
2740module_param_named(log_order_threshold, page_alloc_log_order_threshold, int, S_IRUGO | S_IWUSR);
2741#endif // __LOG_PAGE_ALLOC_ORDER__
2742
11e33f6a
MG
2743/*
2744 * This is the 'heart' of the zoned buddy allocator.
2745 */
2746struct page *
2747__alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2748 struct zonelist *zonelist, nodemask_t *nodemask)
2749{
2750 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
5117f45d 2751 struct zone *preferred_zone;
cc9a6c87 2752 struct page *page = NULL;
3dd28266 2753 int migratetype = allocflags_to_migratetype(gfp_mask);
cc9a6c87 2754 unsigned int cpuset_mems_cookie;
d95ea5d1 2755 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET;
6a1a0d3b 2756 struct mem_cgroup *memcg = NULL;
11e33f6a 2757
dcce284a
BH
2758 gfp_mask &= gfp_allowed_mask;
2759
11e33f6a
MG
2760 lockdep_trace_alloc(gfp_mask);
2761
2762 might_sleep_if(gfp_mask & __GFP_WAIT);
2763
2764 if (should_fail_alloc_page(gfp_mask, order))
2765 return NULL;
2766
2767 /*
2768 * Check the zones suitable for the gfp_mask contain at least one
2769 * valid zone. It's possible to have an empty zonelist as a result
2770 * of GFP_THISNODE and a memoryless node
2771 */
2772 if (unlikely(!zonelist->_zonerefs->zone))
2773 return NULL;
2774
6a1a0d3b
GC
2775 /*
2776 * Will only have any effect when __GFP_KMEMCG is set. This is
2777 * verified in the (always inline) callee
2778 */
2779 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2780 return NULL;
2781
cc9a6c87
MG
2782retry_cpuset:
2783 cpuset_mems_cookie = get_mems_allowed();
2784
5117f45d 2785 /* The preferred zone is used for statistics later */
f33261d7
DR
2786 first_zones_zonelist(zonelist, high_zoneidx,
2787 nodemask ? : &cpuset_current_mems_allowed,
2788 &preferred_zone);
cc9a6c87
MG
2789 if (!preferred_zone)
2790 goto out;
5117f45d 2791
d95ea5d1
BZ
2792#ifdef CONFIG_CMA
2793 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2794 alloc_flags |= ALLOC_CMA;
2795#endif
6fa3eb70
S
2796
2797#ifdef CONFIG_MTKPASR
2798 /* Speed up allocation for MIGRATE_MOVABLE */
2799#ifdef CONFIG_HIGHMEM
2800 if (high_zoneidx >= ZONE_HIGHMEM) {
2801#endif
2802 if (migratetype == MIGRATE_MOVABLE) {
2803 migratetype = preferred_mt;
2804 }
2805#ifdef CONFIG_HIGHMEM
2806 }
2807#endif
2808#endif
2809
5117f45d 2810 /* First allocation attempt */
11e33f6a 2811 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
d95ea5d1 2812 zonelist, high_zoneidx, alloc_flags,
3dd28266 2813 preferred_zone, migratetype);
21caf2fc
ML
2814 if (unlikely(!page)) {
2815 /*
2816 * Runtime PM, block IO and its error handling path
2817 * can deadlock because I/O on the device might not
2818 * complete.
2819 */
2820 gfp_mask = memalloc_noio_flags(gfp_mask);
6fa3eb70
S
2821 if (gfp_mask & __GFP_SLOWHIGHMEM) {
2822 // setup highmem flag for slowhighmem
2823 gfp_mask |= __GFP_HIGHMEM;
2824 high_zoneidx = gfp_zone(gfp_mask);
2825 first_zones_zonelist(zonelist, high_zoneidx,
2826 nodemask ? : &cpuset_current_mems_allowed,
2827 &preferred_zone);
2828 if (!preferred_zone)
2829 goto out;
2830 }
2831
2832 /* Check whether we should release PASR reserved page */
2833 if (gfp_mask & __GFP_NOMTKPASR) {
2834 /* Do nothing, just go ahead */
2835 } else {
2836#ifdef CONFIG_HIGHMEM
2837 if (high_zoneidx >= ZONE_HIGHMEM) {
2838#endif
2839 try_to_release_mtkpasr_page(order);
2840 migratetype = preferred_mt;
2841#ifdef CONFIG_HIGHMEM
2842 }
2843#endif
2844 }
2845
11e33f6a 2846 page = __alloc_pages_slowpath(gfp_mask, order,
5117f45d 2847 zonelist, high_zoneidx, nodemask,
3dd28266 2848 preferred_zone, migratetype);
21caf2fc 2849 }
11e33f6a 2850
6fa3eb70
S
2851
2852#ifdef __LOG_PAGE_ALLOC_ORDER__
2853
2854#ifdef CONFIG_FREEZER //Added skip debug log in IPOH
2855 if (unlikely(!atomic_read(&system_freezing_cnt)))
2856 {
2857#endif
2858
2859 //page_alloc_order_log[order] += 1;
2860 // Enable the log in system server when boot completes
2861 if (order >= page_alloc_log_order_threshold) {
2862
2863
2864 if (log_counter == 0)
2865 {
2866 log_time_c0 = jiffies;
2867 }
2868 if (log_limit_enable == 0)
2869 {
2870 //printk("caller api is %p \r\n",__builtin_return_address(0));
2871 //printk_ratelimit()
2872#ifdef __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2873 printk("alloc large continuous pages, order: %d, gfp_mask = 0x%x, printk_ratelimit() = %d\n", order,gfp_mask,printk_ratelimit());
2874#else
2875 if (printk_ratelimit())
2876 printk("alloc large continuous pages, order: %d, gfp_mask = 0x%x, printk_ratelimit() = %d\n", order,gfp_mask,printk_ratelimit());
2877 //else
2878 // printk("alloc large cprintk_ratelimit() = 0 !!\n");
2879#endif
2880
2881 //printk("log_time_c0 = %d ms, jiffies = %d ms ",jiffies_to_msecs(log_time_c0),jiffies_to_msecs(jiffies));
2882 //printk("jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0) = %d ms",jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0));
2883
2884 }
2885#ifdef __LOG_PAGE_ALLOC_ORDER_COUNT_LIMIT__
2886
2887 if (jiffies_to_msecs(jiffies) - jiffies_to_msecs(log_time_c0) < LOG_PAGE_LIMIT_TIME)
2888 {
2889 log_counter++;
2890 if (log_limit_enable == 0)
2891 {
2892 if (log_counter > LOG_PAGE_LIMIT_NUM)
2893 {
2894 log_limit_enable = 1;
2895 printk("alloc page log limit enable, log_counter = %d!!\n",log_counter);
2896 }
2897 }
2898
2899 }
2900 else
2901 {
2902 if (log_limit_enable != 0)
2903 {
2904 printk("alloc page log limit disable!!\n");
2905 log_limit_enable = 0;
2906 }
2907 log_counter = 0;
2908
2909
2910 }
2911#endif
2912
2913 }
2914
2915 if (order >= page_alloc_dump_order_threshold) {
2916
2917 if (log_limit_enable == 0)
2918 dump_stack();
2919 }
2920
2921#ifdef CONFIG_FREEZER
2922 }
2923#endif
2924
2925#endif // __LOG_PAGE_ALLOC_ORDER__
4b4f278c 2926 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
cc9a6c87
MG
2927
2928out:
2929 /*
2930 * When updating a task's mems_allowed, it is possible to race with
2931 * parallel threads in such a way that an allocation can fail while
2932 * the mask is being updated. If a page allocation is about to fail,
2933 * check if the cpuset changed during allocation and if so, retry.
2934 */
2935 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !page))
2936 goto retry_cpuset;
2937
6a1a0d3b
GC
2938 memcg_kmem_commit_charge(page, memcg, order);
2939
11e33f6a 2940 return page;
1da177e4 2941}
d239171e 2942EXPORT_SYMBOL(__alloc_pages_nodemask);
1da177e4
LT
2943
2944/*
2945 * Common helper functions.
2946 */
920c7a5d 2947unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1da177e4 2948{
945a1113
AM
2949 struct page *page;
2950
2951 /*
2952 * __get_free_pages() returns a 32-bit address, which cannot represent
2953 * a highmem page
2954 */
2955 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2956
1da177e4
LT
2957 page = alloc_pages(gfp_mask, order);
2958 if (!page)
2959 return 0;
2960 return (unsigned long) page_address(page);
2961}
1da177e4
LT
2962EXPORT_SYMBOL(__get_free_pages);
2963
920c7a5d 2964unsigned long get_zeroed_page(gfp_t gfp_mask)
1da177e4 2965{
945a1113 2966 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
1da177e4 2967}
1da177e4
LT
2968EXPORT_SYMBOL(get_zeroed_page);
2969
920c7a5d 2970void __free_pages(struct page *page, unsigned int order)
1da177e4 2971{
b5810039 2972 if (put_page_testzero(page)) {
1da177e4 2973 if (order == 0)
fc91668e 2974 free_hot_cold_page(page, 0);
1da177e4
LT
2975 else
2976 __free_pages_ok(page, order);
2977 }
2978}
2979
2980EXPORT_SYMBOL(__free_pages);
2981
920c7a5d 2982void free_pages(unsigned long addr, unsigned int order)
1da177e4
LT
2983{
2984 if (addr != 0) {
725d704e 2985 VM_BUG_ON(!virt_addr_valid((void *)addr));
1da177e4
LT
2986 __free_pages(virt_to_page((void *)addr), order);
2987 }
2988}
2989
2990EXPORT_SYMBOL(free_pages);
2991
6a1a0d3b
GC
2992/*
2993 * __free_memcg_kmem_pages and free_memcg_kmem_pages will free
2994 * pages allocated with __GFP_KMEMCG.
2995 *
2996 * Those pages are accounted to a particular memcg, embedded in the
2997 * corresponding page_cgroup. To avoid adding a hit in the allocator to search
2998 * for that information only to find out that it is NULL for users who have no
2999 * interest in that whatsoever, we provide these functions.
3000 *
3001 * The caller knows better which flags it relies on.
3002 */
3003void __free_memcg_kmem_pages(struct page *page, unsigned int order)
3004{
3005 memcg_kmem_uncharge_pages(page, order);
6fa3eb70 3006#ifndef CONFIG_MTK_PAGERECORDER
6a1a0d3b 3007 __free_pages(page, order);
6fa3eb70
S
3008#else
3009 __free_pages_nopagedebug(page, order);
3010#endif
6a1a0d3b
GC
3011}
3012
3013void free_memcg_kmem_pages(unsigned long addr, unsigned int order)
3014{
3015 if (addr != 0) {
3016 VM_BUG_ON(!virt_addr_valid((void *)addr));
3017 __free_memcg_kmem_pages(virt_to_page((void *)addr), order);
3018 }
3019}
3020
ee85c2e1
AK
3021static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
3022{
3023 if (addr) {
3024 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3025 unsigned long used = addr + PAGE_ALIGN(size);
3026
3027 split_page(virt_to_page((void *)addr), order);
3028 while (used < alloc_end) {
3029 free_page(used);
3030 used += PAGE_SIZE;
3031 }
3032 }
3033 return (void *)addr;
3034}
3035
2be0ffe2
TT
3036/**
3037 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3038 * @size: the number of bytes to allocate
3039 * @gfp_mask: GFP flags for the allocation
3040 *
3041 * This function is similar to alloc_pages(), except that it allocates the
3042 * minimum number of pages to satisfy the request. alloc_pages() can only
3043 * allocate memory in power-of-two pages.
3044 *
3045 * This function is also limited by MAX_ORDER.
3046 *
3047 * Memory allocated by this function must be released by free_pages_exact().
3048 */
3049void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3050{
3051 unsigned int order = get_order(size);
3052 unsigned long addr;
3053
3054 addr = __get_free_pages(gfp_mask, order);
ee85c2e1 3055 return make_alloc_exact(addr, order, size);
2be0ffe2
TT
3056}
3057EXPORT_SYMBOL(alloc_pages_exact);
3058
ee85c2e1
AK
3059/**
3060 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3061 * pages on a node.
b5e6ab58 3062 * @nid: the preferred node ID where memory should be allocated
ee85c2e1
AK
3063 * @size: the number of bytes to allocate
3064 * @gfp_mask: GFP flags for the allocation
3065 *
3066 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3067 * back.
3068 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
3069 * but is not exact.
3070 */
3071void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3072{
3073 unsigned order = get_order(size);
3074 struct page *p = alloc_pages_node(nid, gfp_mask, order);
3075 if (!p)
3076 return NULL;
3077 return make_alloc_exact((unsigned long)page_address(p), order, size);
3078}
3079EXPORT_SYMBOL(alloc_pages_exact_nid);
3080
2be0ffe2
TT
3081/**
3082 * free_pages_exact - release memory allocated via alloc_pages_exact()
3083 * @virt: the value returned by alloc_pages_exact.
3084 * @size: size of allocation, same value as passed to alloc_pages_exact().
3085 *
3086 * Release the memory allocated by a previous call to alloc_pages_exact.
3087 */
3088void free_pages_exact(void *virt, size_t size)
3089{
3090 unsigned long addr = (unsigned long)virt;
3091 unsigned long end = addr + PAGE_ALIGN(size);
3092
3093 while (addr < end) {
3094 free_page(addr);
3095 addr += PAGE_SIZE;
3096 }
3097}
3098EXPORT_SYMBOL(free_pages_exact);
3099
e0fb5815
ZY
3100/**
3101 * nr_free_zone_pages - count number of pages beyond high watermark
3102 * @offset: The zone index of the highest zone
3103 *
3104 * nr_free_zone_pages() counts the number of counts pages which are beyond the
3105 * high watermark within all zones at or below a given zone index. For each
3106 * zone, the number of pages is calculated as:
3107 * present_pages - high_pages
3108 */
ebec3862 3109static unsigned long nr_free_zone_pages(int offset)
1da177e4 3110{
dd1a239f 3111 struct zoneref *z;
54a6eb5c
MG
3112 struct zone *zone;
3113
e310fd43 3114 /* Just pick one node, since fallback list is circular */
ebec3862 3115 unsigned long sum = 0;
1da177e4 3116
0e88460d 3117 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
1da177e4 3118
54a6eb5c 3119 for_each_zone_zonelist(zone, z, zonelist, offset) {
b40da049 3120 unsigned long size = zone->managed_pages;
41858966 3121 unsigned long high = high_wmark_pages(zone);
e310fd43
MB
3122 if (size > high)
3123 sum += size - high;
1da177e4
LT
3124 }
3125
3126 return sum;
3127}
3128
6fa3eb70
S
3129static unsigned long nr_unallocated_zone_pages(int offset)
3130{
3131 struct zoneref *z;
3132 struct zone *zone;
3133
3134 /* Just pick one node, since fallback list is circular */
3135 unsigned long sum = 0;
3136
3137 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3138
3139 for_each_zone_zonelist(zone, z, zonelist, offset) {
3140 unsigned long high = high_wmark_pages(zone);
3141 unsigned long left = zone_page_state(zone, NR_FREE_PAGES);
3142 if (left > high)
3143 sum += left - high;
3144 }
3145
3146 return sum;
3147}
3148
e0fb5815
ZY
3149/**
3150 * nr_free_buffer_pages - count number of pages beyond high watermark
3151 *
3152 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3153 * watermark within ZONE_DMA and ZONE_NORMAL.
1da177e4 3154 */
ebec3862 3155unsigned long nr_free_buffer_pages(void)
1da177e4 3156{
af4ca457 3157 return nr_free_zone_pages(gfp_zone(GFP_USER));
1da177e4 3158}
c2f1a551 3159EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1da177e4 3160
6fa3eb70
S
3161/*
3162 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
3163 */
3164unsigned long nr_unallocated_buffer_pages(void)
3165{
3166 return nr_unallocated_zone_pages(gfp_zone(GFP_USER));
3167}
3168EXPORT_SYMBOL_GPL(nr_unallocated_buffer_pages);
3169
e0fb5815
ZY
3170/**
3171 * nr_free_pagecache_pages - count number of pages beyond high watermark
3172 *
3173 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3174 * high watermark within all zones.
1da177e4 3175 */
ebec3862 3176unsigned long nr_free_pagecache_pages(void)
1da177e4 3177{
2a1e274a 3178 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1da177e4 3179}
08e0f6a9
CL
3180
3181static inline void show_node(struct zone *zone)
1da177e4 3182{
e5adfffc 3183 if (IS_ENABLED(CONFIG_NUMA))
25ba77c1 3184 printk("Node %d ", zone_to_nid(zone));
1da177e4 3185}
1da177e4 3186
6fa3eb70
S
3187#ifdef CONFIG_MTKPASR
3188extern unsigned long mtkpasr_show_page_reserved(void);
3189#else
3190#define mtkpasr_show_page_reserved(void) (0)
3191#endif
1da177e4
LT
3192void si_meminfo(struct sysinfo *val)
3193{
3194 val->totalram = totalram_pages;
3195 val->sharedram = 0;
6fa3eb70 3196 val->freeram = global_page_state(NR_FREE_PAGES) + mtkpasr_show_page_reserved();
1da177e4 3197 val->bufferram = nr_blockdev_pages();
1da177e4
LT
3198 val->totalhigh = totalhigh_pages;
3199 val->freehigh = nr_free_highpages();
6fa3eb70
S
3200 if (IS_ENABLED(CONFIG_HIGHMEM)) {
3201 val->freehigh += mtkpasr_show_page_reserved();
3202 }
1da177e4
LT
3203 val->mem_unit = PAGE_SIZE;
3204}
3205
3206EXPORT_SYMBOL(si_meminfo);
3207
3208#ifdef CONFIG_NUMA
3209void si_meminfo_node(struct sysinfo *val, int nid)
3210{
3211 pg_data_t *pgdat = NODE_DATA(nid);
3212
3213 val->totalram = pgdat->node_present_pages;
d23ad423 3214 val->freeram = node_page_state(nid, NR_FREE_PAGES);
98d2b0eb 3215#ifdef CONFIG_HIGHMEM
b40da049 3216 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
d23ad423
CL
3217 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3218 NR_FREE_PAGES);
98d2b0eb
CL
3219#else
3220 val->totalhigh = 0;
3221 val->freehigh = 0;
3222#endif
1da177e4
LT
3223 val->mem_unit = PAGE_SIZE;
3224}
3225#endif
3226
ddd588b5 3227/*
7bf02ea2
DR
3228 * Determine whether the node should be displayed or not, depending on whether
3229 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
ddd588b5 3230 */
7bf02ea2 3231bool skip_free_areas_node(unsigned int flags, int nid)
ddd588b5
DR
3232{
3233 bool ret = false;
cc9a6c87 3234 unsigned int cpuset_mems_cookie;
ddd588b5
DR
3235
3236 if (!(flags & SHOW_MEM_FILTER_NODES))
3237 goto out;
3238
cc9a6c87
MG
3239 do {
3240 cpuset_mems_cookie = get_mems_allowed();
3241 ret = !node_isset(nid, cpuset_current_mems_allowed);
3242 } while (!put_mems_allowed(cpuset_mems_cookie));
ddd588b5
DR
3243out:
3244 return ret;
3245}
3246
1da177e4
LT
3247#define K(x) ((x) << (PAGE_SHIFT-10))
3248
377e4f16
RV
3249static void show_migration_types(unsigned char type)
3250{
3251 static const char types[MIGRATE_TYPES] = {
3252 [MIGRATE_UNMOVABLE] = 'U',
3253 [MIGRATE_RECLAIMABLE] = 'E',
3254 [MIGRATE_MOVABLE] = 'M',
3255 [MIGRATE_RESERVE] = 'R',
3256#ifdef CONFIG_CMA
3257 [MIGRATE_CMA] = 'C',
3258#endif
194159fb 3259#ifdef CONFIG_MEMORY_ISOLATION
377e4f16 3260 [MIGRATE_ISOLATE] = 'I',
194159fb 3261#endif
377e4f16
RV
3262 };
3263 char tmp[MIGRATE_TYPES + 1];
3264 char *p = tmp;
3265 int i;
3266
3267 for (i = 0; i < MIGRATE_TYPES; i++) {
3268 if (type & (1 << i))
3269 *p++ = types[i];
3270 }
3271
3272 *p = '\0';
3273 printk("(%s) ", tmp);
3274}
3275
1da177e4
LT
3276/*
3277 * Show free area list (used inside shift_scroll-lock stuff)
3278 * We also calculate the percentage fragmentation. We do this by counting the
3279 * memory on each free list with the exception of the first item on the list.
ddd588b5
DR
3280 * Suppresses nodes that are not allowed by current's cpuset if
3281 * SHOW_MEM_FILTER_NODES is passed.
1da177e4 3282 */
7bf02ea2 3283void show_free_areas(unsigned int filter)
1da177e4 3284{
c7241913 3285 int cpu;
1da177e4
LT
3286 struct zone *zone;
3287
ee99c71c 3288 for_each_populated_zone(zone) {
7bf02ea2 3289 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3290 continue;
c7241913
JS
3291 show_node(zone);
3292 printk("%s per-cpu:\n", zone->name);
1da177e4 3293
6b482c67 3294 for_each_online_cpu(cpu) {
1da177e4
LT
3295 struct per_cpu_pageset *pageset;
3296
99dcc3e5 3297 pageset = per_cpu_ptr(zone->pageset, cpu);
1da177e4 3298
3dfa5721
CL
3299 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
3300 cpu, pageset->pcp.high,
3301 pageset->pcp.batch, pageset->pcp.count);
1da177e4
LT
3302 }
3303 }
3304
a731286d
KM
3305 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3306 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
7b854121 3307 " unevictable:%lu"
b76146ed 3308 " dirty:%lu writeback:%lu unstable:%lu\n"
3701b033 3309 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
d1ce749a
BZ
3310 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3311 " free_cma:%lu\n",
4f98a2fe 3312 global_page_state(NR_ACTIVE_ANON),
4f98a2fe 3313 global_page_state(NR_INACTIVE_ANON),
a731286d
KM
3314 global_page_state(NR_ISOLATED_ANON),
3315 global_page_state(NR_ACTIVE_FILE),
4f98a2fe 3316 global_page_state(NR_INACTIVE_FILE),
a731286d 3317 global_page_state(NR_ISOLATED_FILE),
7b854121 3318 global_page_state(NR_UNEVICTABLE),
b1e7a8fd 3319 global_page_state(NR_FILE_DIRTY),
ce866b34 3320 global_page_state(NR_WRITEBACK),
fd39fc85 3321 global_page_state(NR_UNSTABLE_NFS),
d23ad423 3322 global_page_state(NR_FREE_PAGES),
3701b033
KM
3323 global_page_state(NR_SLAB_RECLAIMABLE),
3324 global_page_state(NR_SLAB_UNRECLAIMABLE),
65ba55f5 3325 global_page_state(NR_FILE_MAPPED),
4b02108a 3326 global_page_state(NR_SHMEM),
a25700a5 3327 global_page_state(NR_PAGETABLE),
d1ce749a
BZ
3328 global_page_state(NR_BOUNCE),
3329 global_page_state(NR_FREE_CMA_PAGES));
1da177e4 3330
ee99c71c 3331 for_each_populated_zone(zone) {
1da177e4
LT
3332 int i;
3333
7bf02ea2 3334 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3335 continue;
1da177e4
LT
3336 show_node(zone);
3337 printk("%s"
3338 " free:%lukB"
3339 " min:%lukB"
3340 " low:%lukB"
3341 " high:%lukB"
4f98a2fe
RR
3342 " active_anon:%lukB"
3343 " inactive_anon:%lukB"
3344 " active_file:%lukB"
3345 " inactive_file:%lukB"
7b854121 3346 " unevictable:%lukB"
a731286d
KM
3347 " isolated(anon):%lukB"
3348 " isolated(file):%lukB"
1da177e4 3349 " present:%lukB"
9feedc9d 3350 " managed:%lukB"
4a0aa73f
KM
3351 " mlocked:%lukB"
3352 " dirty:%lukB"
3353 " writeback:%lukB"
3354 " mapped:%lukB"
4b02108a 3355 " shmem:%lukB"
4a0aa73f
KM
3356 " slab_reclaimable:%lukB"
3357 " slab_unreclaimable:%lukB"
c6a7f572 3358 " kernel_stack:%lukB"
4a0aa73f
KM
3359 " pagetables:%lukB"
3360 " unstable:%lukB"
3361 " bounce:%lukB"
d1ce749a 3362 " free_cma:%lukB"
4a0aa73f 3363 " writeback_tmp:%lukB"
1da177e4
LT
3364 " pages_scanned:%lu"
3365 " all_unreclaimable? %s"
3366 "\n",
3367 zone->name,
88f5acf8 3368 K(zone_page_state(zone, NR_FREE_PAGES)),
41858966
MG
3369 K(min_wmark_pages(zone)),
3370 K(low_wmark_pages(zone)),
3371 K(high_wmark_pages(zone)),
4f98a2fe
RR
3372 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3373 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3374 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3375 K(zone_page_state(zone, NR_INACTIVE_FILE)),
7b854121 3376 K(zone_page_state(zone, NR_UNEVICTABLE)),
a731286d
KM
3377 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3378 K(zone_page_state(zone, NR_ISOLATED_FILE)),
1da177e4 3379 K(zone->present_pages),
9feedc9d 3380 K(zone->managed_pages),
4a0aa73f
KM
3381 K(zone_page_state(zone, NR_MLOCK)),
3382 K(zone_page_state(zone, NR_FILE_DIRTY)),
3383 K(zone_page_state(zone, NR_WRITEBACK)),
3384 K(zone_page_state(zone, NR_FILE_MAPPED)),
4b02108a 3385 K(zone_page_state(zone, NR_SHMEM)),
4a0aa73f
KM
3386 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3387 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
c6a7f572
KM
3388 zone_page_state(zone, NR_KERNEL_STACK) *
3389 THREAD_SIZE / 1024,
4a0aa73f
KM
3390 K(zone_page_state(zone, NR_PAGETABLE)),
3391 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3392 K(zone_page_state(zone, NR_BOUNCE)),
d1ce749a 3393 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
4a0aa73f 3394 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
1da177e4 3395 zone->pages_scanned,
93e4a89a 3396 (zone->all_unreclaimable ? "yes" : "no")
1da177e4
LT
3397 );
3398 printk("lowmem_reserve[]:");
3399 for (i = 0; i < MAX_NR_ZONES; i++)
3400 printk(" %lu", zone->lowmem_reserve[i]);
3401 printk("\n");
3402 }
3403
ee99c71c 3404 for_each_populated_zone(zone) {
8f9de51a 3405 unsigned long nr[MAX_ORDER], flags, order, total = 0;
377e4f16 3406 unsigned char types[MAX_ORDER];
1da177e4 3407
7bf02ea2 3408 if (skip_free_areas_node(filter, zone_to_nid(zone)))
ddd588b5 3409 continue;
1da177e4
LT
3410 show_node(zone);
3411 printk("%s: ", zone->name);
1da177e4
LT
3412
3413 spin_lock_irqsave(&zone->lock, flags);
3414 for (order = 0; order < MAX_ORDER; order++) {
377e4f16
RV
3415 struct free_area *area = &zone->free_area[order];
3416 int type;
3417
3418 nr[order] = area->nr_free;
8f9de51a 3419 total += nr[order] << order;
377e4f16
RV
3420
3421 types[order] = 0;
3422 for (type = 0; type < MIGRATE_TYPES; type++) {
3423 if (!list_empty(&area->free_list[type]))
3424 types[order] |= 1 << type;
3425 }
1da177e4
LT
3426 }
3427 spin_unlock_irqrestore(&zone->lock, flags);
377e4f16 3428 for (order = 0; order < MAX_ORDER; order++) {
8f9de51a 3429 printk("%lu*%lukB ", nr[order], K(1UL) << order);
377e4f16
RV
3430 if (nr[order])
3431 show_migration_types(types[order]);
3432 }
1da177e4
LT
3433 printk("= %lukB\n", K(total));
3434 }
3435
949f7ec5
DR
3436 hugetlb_show_meminfo();
3437
e6f3602d
LW
3438 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3439
1da177e4
LT
3440 show_swap_cache_info();
3441}
3442
6fa3eb70
S
3443void show_free_areas_minimum(void)
3444{
3445 struct zone *zone;
3446 for_each_populated_zone(zone) {
3447 if (skip_free_areas_node(SHOW_MEM_FILTER_NODES, zone_to_nid(zone)))
3448 continue;
3449 show_node(zone);
3450 printk("%s"
3451 " free:%lukB"
3452 " min:%lukB"
3453 " low:%lukB"
3454 " high:%lukB"
3455 " active_anon:%lukB"
3456 " inactive_anon:%lukB"
3457 " active_file:%lukB"
3458 " inactive_file:%lukB"
3459 " unevictable:%lukB"
3460 " isolated(anon):%lukB"
3461 " isolated(file):%lukB"
3462 " present:%lukB"
3463 " managed:%lukB"
3464 " mlocked:%lukB"
3465 " dirty:%lukB"
3466 " writeback:%lukB"
3467 " mapped:%lukB"
3468 " shmem:%lukB"
3469 " slab_reclaimable:%lukB"
3470 " slab_unreclaimable:%lukB"
3471 " kernel_stack:%lukB"
3472 " pagetables:%lukB"
3473 " unstable:%lukB"
3474 " bounce:%lukB"
3475 " free_cma:%lukB"
3476 " writeback_tmp:%lukB"
3477 " pages_scanned:%lu"
3478 " all_unreclaimable? %s"
3479 "\n",
3480 zone->name,
3481 K(zone_page_state(zone, NR_FREE_PAGES)),
3482 K(min_wmark_pages(zone)),
3483 K(low_wmark_pages(zone)),
3484 K(high_wmark_pages(zone)),
3485 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3486 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3487 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3488 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3489 K(zone_page_state(zone, NR_UNEVICTABLE)),
3490 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3491 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3492 K(zone->present_pages),
3493 K(zone->managed_pages),
3494 K(zone_page_state(zone, NR_MLOCK)),
3495 K(zone_page_state(zone, NR_FILE_DIRTY)),
3496 K(zone_page_state(zone, NR_WRITEBACK)),
3497 K(zone_page_state(zone, NR_FILE_MAPPED)),
3498 K(zone_page_state(zone, NR_SHMEM)),
3499 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3500 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3501 zone_page_state(zone, NR_KERNEL_STACK) *
3502 THREAD_SIZE / 1024,
3503 K(zone_page_state(zone, NR_PAGETABLE)),
3504 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3505 K(zone_page_state(zone, NR_BOUNCE)),
3506 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3507 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3508 zone->pages_scanned,
3509 (zone->all_unreclaimable ? "yes" : "no")
3510 );
3511 }
3512
3513 for_each_populated_zone(zone) {
3514 unsigned long nr[MAX_ORDER], flags, order, total = 0;
3515
3516 if (skip_free_areas_node(SHOW_MEM_FILTER_NODES, zone_to_nid(zone)))
3517 continue;
3518 show_node(zone);
3519 printk("%s: ", zone->name);
3520
3521 spin_lock_irqsave(&zone->lock, flags);
3522 for (order = 0; order < MAX_ORDER; order++) {
3523 nr[order] = zone->free_area[order].nr_free;
3524 total += nr[order] << order;
3525 }
3526 spin_unlock_irqrestore(&zone->lock, flags);
3527 for (order = 0; order < MAX_ORDER; order++)
3528 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3529 printk("= %lukB\n", K(total));
3530 }
3531}
3532EXPORT_SYMBOL(show_free_areas_minimum);
3533
19770b32
MG
3534static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3535{
3536 zoneref->zone = zone;
3537 zoneref->zone_idx = zone_idx(zone);
3538}
3539
1da177e4
LT
3540/*
3541 * Builds allocation fallback zone lists.
1a93205b
CL
3542 *
3543 * Add all populated zones of a node to the zonelist.
1da177e4 3544 */
f0c0b2b8
KH
3545static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3546 int nr_zones, enum zone_type zone_type)
1da177e4 3547{
1a93205b
CL
3548 struct zone *zone;
3549
98d2b0eb 3550 BUG_ON(zone_type >= MAX_NR_ZONES);
2f6726e5 3551 zone_type++;
02a68a5e
CL
3552
3553 do {
2f6726e5 3554 zone_type--;
070f8032 3555 zone = pgdat->node_zones + zone_type;
1a93205b 3556 if (populated_zone(zone)) {
dd1a239f
MG
3557 zoneref_set_zone(zone,
3558 &zonelist->_zonerefs[nr_zones++]);
070f8032 3559 check_highest_zone(zone_type);
1da177e4 3560 }
02a68a5e 3561
2f6726e5 3562 } while (zone_type);
070f8032 3563 return nr_zones;
1da177e4
LT
3564}
3565
f0c0b2b8
KH
3566
3567/*
3568 * zonelist_order:
3569 * 0 = automatic detection of better ordering.
3570 * 1 = order by ([node] distance, -zonetype)
3571 * 2 = order by (-zonetype, [node] distance)
3572 *
3573 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3574 * the same zonelist. So only NUMA can configure this param.
3575 */
3576#define ZONELIST_ORDER_DEFAULT 0
3577#define ZONELIST_ORDER_NODE 1
3578#define ZONELIST_ORDER_ZONE 2
3579
3580/* zonelist order in the kernel.
3581 * set_zonelist_order() will set this to NODE or ZONE.
3582 */
3583static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3584static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3585
3586
1da177e4 3587#ifdef CONFIG_NUMA
f0c0b2b8
KH
3588/* The value user specified ....changed by config */
3589static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3590/* string for sysctl */
3591#define NUMA_ZONELIST_ORDER_LEN 16
3592char numa_zonelist_order[16] = "default";
3593
3594/*
3595 * interface for configure zonelist ordering.
3596 * command line option "numa_zonelist_order"
3597 * = "[dD]efault - default, automatic configuration.
3598 * = "[nN]ode - order by node locality, then by zone within node
3599 * = "[zZ]one - order by zone, then by locality within zone
3600 */
3601
3602static int __parse_numa_zonelist_order(char *s)
3603{
3604 if (*s == 'd' || *s == 'D') {
3605 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3606 } else if (*s == 'n' || *s == 'N') {
3607 user_zonelist_order = ZONELIST_ORDER_NODE;
3608 } else if (*s == 'z' || *s == 'Z') {
3609 user_zonelist_order = ZONELIST_ORDER_ZONE;
3610 } else {
3611 printk(KERN_WARNING
3612 "Ignoring invalid numa_zonelist_order value: "
3613 "%s\n", s);
3614 return -EINVAL;
3615 }
3616 return 0;
3617}
3618
3619static __init int setup_numa_zonelist_order(char *s)
3620{
ecb256f8
VL
3621 int ret;
3622
3623 if (!s)
3624 return 0;
3625
3626 ret = __parse_numa_zonelist_order(s);
3627 if (ret == 0)
3628 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3629
3630 return ret;
f0c0b2b8
KH
3631}
3632early_param("numa_zonelist_order", setup_numa_zonelist_order);
3633
3634/*
3635 * sysctl handler for numa_zonelist_order
3636 */
3637int numa_zonelist_order_handler(ctl_table *table, int write,
8d65af78 3638 void __user *buffer, size_t *length,
f0c0b2b8
KH
3639 loff_t *ppos)
3640{
3641 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3642 int ret;
443c6f14 3643 static DEFINE_MUTEX(zl_order_mutex);
f0c0b2b8 3644
443c6f14 3645 mutex_lock(&zl_order_mutex);
f0c0b2b8 3646 if (write)
443c6f14 3647 strcpy(saved_string, (char*)table->data);
8d65af78 3648 ret = proc_dostring(table, write, buffer, length, ppos);
f0c0b2b8 3649 if (ret)
443c6f14 3650 goto out;
f0c0b2b8
KH
3651 if (write) {
3652 int oldval = user_zonelist_order;
3653 if (__parse_numa_zonelist_order((char*)table->data)) {
3654 /*
3655 * bogus value. restore saved string
3656 */
3657 strncpy((char*)table->data, saved_string,
3658 NUMA_ZONELIST_ORDER_LEN);
3659 user_zonelist_order = oldval;
4eaf3f64
HL
3660 } else if (oldval != user_zonelist_order) {
3661 mutex_lock(&zonelists_mutex);
9adb62a5 3662 build_all_zonelists(NULL, NULL);
4eaf3f64
HL
3663 mutex_unlock(&zonelists_mutex);
3664 }
f0c0b2b8 3665 }
443c6f14
AK
3666out:
3667 mutex_unlock(&zl_order_mutex);
3668 return ret;
f0c0b2b8
KH
3669}
3670
3671
62bc62a8 3672#define MAX_NODE_LOAD (nr_online_nodes)
f0c0b2b8
KH
3673static int node_load[MAX_NUMNODES];
3674
1da177e4 3675/**
4dc3b16b 3676 * find_next_best_node - find the next node that should appear in a given node's fallback list
1da177e4
LT
3677 * @node: node whose fallback list we're appending
3678 * @used_node_mask: nodemask_t of already used nodes
3679 *
3680 * We use a number of factors to determine which is the next node that should
3681 * appear on a given node's fallback list. The node should not have appeared
3682 * already in @node's fallback list, and it should be the next closest node
3683 * according to the distance array (which contains arbitrary distance values
3684 * from each node to each node in the system), and should also prefer nodes
3685 * with no CPUs, since presumably they'll have very little allocation pressure
3686 * on them otherwise.
3687 * It returns -1 if no node is found.
3688 */
f0c0b2b8 3689static int find_next_best_node(int node, nodemask_t *used_node_mask)
1da177e4 3690{
4cf808eb 3691 int n, val;
1da177e4 3692 int min_val = INT_MAX;
00ef2d2f 3693 int best_node = NUMA_NO_NODE;
a70f7302 3694 const struct cpumask *tmp = cpumask_of_node(0);
1da177e4 3695
4cf808eb
LT
3696 /* Use the local node if we haven't already */
3697 if (!node_isset(node, *used_node_mask)) {
3698 node_set(node, *used_node_mask);
3699 return node;
3700 }
1da177e4 3701
4b0ef1fe 3702 for_each_node_state(n, N_MEMORY) {
1da177e4
LT
3703
3704 /* Don't want a node to appear more than once */
3705 if (node_isset(n, *used_node_mask))
3706 continue;
3707
1da177e4
LT
3708 /* Use the distance array to find the distance */
3709 val = node_distance(node, n);
3710
4cf808eb
LT
3711 /* Penalize nodes under us ("prefer the next node") */
3712 val += (n < node);
3713
1da177e4 3714 /* Give preference to headless and unused nodes */
a70f7302
RR
3715 tmp = cpumask_of_node(n);
3716 if (!cpumask_empty(tmp))
1da177e4
LT
3717 val += PENALTY_FOR_NODE_WITH_CPUS;
3718
3719 /* Slight preference for less loaded node */
3720 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3721 val += node_load[n];
3722
3723 if (val < min_val) {
3724 min_val = val;
3725 best_node = n;
3726 }
3727 }
3728
3729 if (best_node >= 0)
3730 node_set(best_node, *used_node_mask);
3731
3732 return best_node;
3733}
3734
f0c0b2b8
KH
3735
3736/*
3737 * Build zonelists ordered by node and zones within node.
3738 * This results in maximum locality--normal zone overflows into local
3739 * DMA zone, if any--but risks exhausting DMA zone.
3740 */
3741static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
1da177e4 3742{
f0c0b2b8 3743 int j;
1da177e4 3744 struct zonelist *zonelist;
f0c0b2b8 3745
54a6eb5c 3746 zonelist = &pgdat->node_zonelists[0];
dd1a239f 3747 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
54a6eb5c
MG
3748 ;
3749 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3750 MAX_NR_ZONES - 1);
dd1a239f
MG
3751 zonelist->_zonerefs[j].zone = NULL;
3752 zonelist->_zonerefs[j].zone_idx = 0;
f0c0b2b8
KH
3753}
3754
523b9458
CL
3755/*
3756 * Build gfp_thisnode zonelists
3757 */
3758static void build_thisnode_zonelists(pg_data_t *pgdat)
3759{
523b9458
CL
3760 int j;
3761 struct zonelist *zonelist;
3762
54a6eb5c
MG
3763 zonelist = &pgdat->node_zonelists[1];
3764 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
dd1a239f
MG
3765 zonelist->_zonerefs[j].zone = NULL;
3766 zonelist->_zonerefs[j].zone_idx = 0;
523b9458
CL
3767}
3768
f0c0b2b8
KH
3769/*
3770 * Build zonelists ordered by zone and nodes within zones.
3771 * This results in conserving DMA zone[s] until all Normal memory is
3772 * exhausted, but results in overflowing to remote node while memory
3773 * may still exist in local DMA zone.
3774 */
3775static int node_order[MAX_NUMNODES];
3776
3777static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3778{
f0c0b2b8
KH
3779 int pos, j, node;
3780 int zone_type; /* needs to be signed */
3781 struct zone *z;
3782 struct zonelist *zonelist;
3783
54a6eb5c
MG
3784 zonelist = &pgdat->node_zonelists[0];
3785 pos = 0;
3786 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3787 for (j = 0; j < nr_nodes; j++) {
3788 node = node_order[j];
3789 z = &NODE_DATA(node)->node_zones[zone_type];
3790 if (populated_zone(z)) {
dd1a239f
MG
3791 zoneref_set_zone(z,
3792 &zonelist->_zonerefs[pos++]);
54a6eb5c 3793 check_highest_zone(zone_type);
f0c0b2b8
KH
3794 }
3795 }
f0c0b2b8 3796 }
dd1a239f
MG
3797 zonelist->_zonerefs[pos].zone = NULL;
3798 zonelist->_zonerefs[pos].zone_idx = 0;
f0c0b2b8
KH
3799}
3800
3801static int default_zonelist_order(void)
3802{
3803 int nid, zone_type;
3804 unsigned long low_kmem_size,total_size;
3805 struct zone *z;
3806 int average_size;
3807 /*
88393161 3808 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
f0c0b2b8
KH
3809 * If they are really small and used heavily, the system can fall
3810 * into OOM very easily.
e325c90f 3811 * This function detect ZONE_DMA/DMA32 size and configures zone order.
f0c0b2b8
KH
3812 */
3813 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3814 low_kmem_size = 0;
3815 total_size = 0;
3816 for_each_online_node(nid) {
3817 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3818 z = &NODE_DATA(nid)->node_zones[zone_type];
3819 if (populated_zone(z)) {
3820 if (zone_type < ZONE_NORMAL)
3821 low_kmem_size += z->present_pages;
3822 total_size += z->present_pages;
e325c90f
DR
3823 } else if (zone_type == ZONE_NORMAL) {
3824 /*
3825 * If any node has only lowmem, then node order
3826 * is preferred to allow kernel allocations
3827 * locally; otherwise, they can easily infringe
3828 * on other nodes when there is an abundance of
3829 * lowmem available to allocate from.
3830 */
3831 return ZONELIST_ORDER_NODE;
f0c0b2b8
KH
3832 }
3833 }
3834 }
3835 if (!low_kmem_size || /* there are no DMA area. */
3836 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3837 return ZONELIST_ORDER_NODE;
3838 /*
3839 * look into each node's config.
3840 * If there is a node whose DMA/DMA32 memory is very big area on
3841 * local memory, NODE_ORDER may be suitable.
3842 */
37b07e41 3843 average_size = total_size /
4b0ef1fe 3844 (nodes_weight(node_states[N_MEMORY]) + 1);
f0c0b2b8
KH
3845 for_each_online_node(nid) {
3846 low_kmem_size = 0;
3847 total_size = 0;
3848 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3849 z = &NODE_DATA(nid)->node_zones[zone_type];
3850 if (populated_zone(z)) {
3851 if (zone_type < ZONE_NORMAL)
3852 low_kmem_size += z->present_pages;
3853 total_size += z->present_pages;
3854 }
3855 }
3856 if (low_kmem_size &&
3857 total_size > average_size && /* ignore small node */
3858 low_kmem_size > total_size * 70/100)
3859 return ZONELIST_ORDER_NODE;
3860 }
3861 return ZONELIST_ORDER_ZONE;
3862}
3863
3864static void set_zonelist_order(void)
3865{
3866 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3867 current_zonelist_order = default_zonelist_order();
3868 else
3869 current_zonelist_order = user_zonelist_order;
3870}
3871
3872static void build_zonelists(pg_data_t *pgdat)
3873{
3874 int j, node, load;
3875 enum zone_type i;
1da177e4 3876 nodemask_t used_mask;
f0c0b2b8
KH
3877 int local_node, prev_node;
3878 struct zonelist *zonelist;
3879 int order = current_zonelist_order;
1da177e4
LT
3880
3881 /* initialize zonelists */
523b9458 3882 for (i = 0; i < MAX_ZONELISTS; i++) {
1da177e4 3883 zonelist = pgdat->node_zonelists + i;
dd1a239f
MG
3884 zonelist->_zonerefs[0].zone = NULL;
3885 zonelist->_zonerefs[0].zone_idx = 0;
1da177e4
LT
3886 }
3887
3888 /* NUMA-aware ordering of nodes */
3889 local_node = pgdat->node_id;
62bc62a8 3890 load = nr_online_nodes;
1da177e4
LT
3891 prev_node = local_node;
3892 nodes_clear(used_mask);
f0c0b2b8 3893
f0c0b2b8
KH
3894 memset(node_order, 0, sizeof(node_order));
3895 j = 0;
3896
1da177e4
LT
3897 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3898 /*
3899 * We don't want to pressure a particular node.
3900 * So adding penalty to the first node in same
3901 * distance group to make it round-robin.
3902 */
957f822a
DR
3903 if (node_distance(local_node, node) !=
3904 node_distance(local_node, prev_node))
f0c0b2b8
KH
3905 node_load[node] = load;
3906
1da177e4
LT
3907 prev_node = node;
3908 load--;
f0c0b2b8
KH
3909 if (order == ZONELIST_ORDER_NODE)
3910 build_zonelists_in_node_order(pgdat, node);
3911 else
3912 node_order[j++] = node; /* remember order */
3913 }
1da177e4 3914
f0c0b2b8
KH
3915 if (order == ZONELIST_ORDER_ZONE) {
3916 /* calculate node order -- i.e., DMA last! */
3917 build_zonelists_in_zone_order(pgdat, j);
1da177e4 3918 }
523b9458
CL
3919
3920 build_thisnode_zonelists(pgdat);
1da177e4
LT
3921}
3922
9276b1bc 3923/* Construct the zonelist performance cache - see further mmzone.h */
f0c0b2b8 3924static void build_zonelist_cache(pg_data_t *pgdat)
9276b1bc 3925{
54a6eb5c
MG
3926 struct zonelist *zonelist;
3927 struct zonelist_cache *zlc;
dd1a239f 3928 struct zoneref *z;
9276b1bc 3929
54a6eb5c
MG
3930 zonelist = &pgdat->node_zonelists[0];
3931 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3932 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
dd1a239f
MG
3933 for (z = zonelist->_zonerefs; z->zone; z++)
3934 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
9276b1bc
PJ
3935}
3936
7aac7898
LS
3937#ifdef CONFIG_HAVE_MEMORYLESS_NODES
3938/*
3939 * Return node id of node used for "local" allocations.
3940 * I.e., first node id of first zone in arg node's generic zonelist.
3941 * Used for initializing percpu 'numa_mem', which is used primarily
3942 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3943 */
3944int local_memory_node(int node)
3945{
3946 struct zone *zone;
3947
3948 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3949 gfp_zone(GFP_KERNEL),
3950 NULL,
3951 &zone);
3952 return zone->node;
3953}
3954#endif
f0c0b2b8 3955
1da177e4
LT
3956#else /* CONFIG_NUMA */
3957
f0c0b2b8
KH
3958static void set_zonelist_order(void)
3959{
3960 current_zonelist_order = ZONELIST_ORDER_ZONE;
3961}
3962
3963static void build_zonelists(pg_data_t *pgdat)
1da177e4 3964{
19655d34 3965 int node, local_node;
54a6eb5c
MG
3966 enum zone_type j;
3967 struct zonelist *zonelist;
1da177e4
LT
3968
3969 local_node = pgdat->node_id;
1da177e4 3970
54a6eb5c
MG
3971 zonelist = &pgdat->node_zonelists[0];
3972 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
1da177e4 3973
54a6eb5c
MG
3974 /*
3975 * Now we build the zonelist so that it contains the zones
3976 * of all the other nodes.
3977 * We don't want to pressure a particular node, so when
3978 * building the zones for node N, we make sure that the
3979 * zones coming right after the local ones are those from
3980 * node N+1 (modulo N)
3981 */
3982 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3983 if (!node_online(node))
3984 continue;
3985 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3986 MAX_NR_ZONES - 1);
1da177e4 3987 }
54a6eb5c
MG
3988 for (node = 0; node < local_node; node++) {
3989 if (!node_online(node))
3990 continue;
3991 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3992 MAX_NR_ZONES - 1);
3993 }
3994
dd1a239f
MG
3995 zonelist->_zonerefs[j].zone = NULL;
3996 zonelist->_zonerefs[j].zone_idx = 0;
1da177e4
LT
3997}
3998
9276b1bc 3999/* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
f0c0b2b8 4000static void build_zonelist_cache(pg_data_t *pgdat)
9276b1bc 4001{
54a6eb5c 4002 pgdat->node_zonelists[0].zlcache_ptr = NULL;
9276b1bc
PJ
4003}
4004
1da177e4
LT
4005#endif /* CONFIG_NUMA */
4006
99dcc3e5
CL
4007/*
4008 * Boot pageset table. One per cpu which is going to be used for all
4009 * zones and all nodes. The parameters will be set in such a way
4010 * that an item put on a list will immediately be handed over to
4011 * the buddy list. This is safe since pageset manipulation is done
4012 * with interrupts disabled.
4013 *
4014 * The boot_pagesets must be kept even after bootup is complete for
4015 * unused processors and/or zones. They do play a role for bootstrapping
4016 * hotplugged processors.
4017 *
4018 * zoneinfo_show() and maybe other functions do
4019 * not check if the processor is online before following the pageset pointer.
4020 * Other parts of the kernel may not check if the zone is available.
4021 */
4022static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4023static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
1f522509 4024static void setup_zone_pageset(struct zone *zone);
99dcc3e5 4025
4eaf3f64
HL
4026/*
4027 * Global mutex to protect against size modification of zonelists
4028 * as well as to serialize pageset setup for the new populated zone.
4029 */
4030DEFINE_MUTEX(zonelists_mutex);
4031
9b1a4d38 4032/* return values int ....just for stop_machine() */
4ed7e022 4033static int __build_all_zonelists(void *data)
1da177e4 4034{
6811378e 4035 int nid;
99dcc3e5 4036 int cpu;
9adb62a5 4037 pg_data_t *self = data;
9276b1bc 4038
7f9cfb31
BL
4039#ifdef CONFIG_NUMA
4040 memset(node_load, 0, sizeof(node_load));
4041#endif
9adb62a5
JL
4042
4043 if (self && !node_online(self->node_id)) {
4044 build_zonelists(self);
4045 build_zonelist_cache(self);
4046 }
4047
9276b1bc 4048 for_each_online_node(nid) {
7ea1530a
CL
4049 pg_data_t *pgdat = NODE_DATA(nid);
4050
4051 build_zonelists(pgdat);
4052 build_zonelist_cache(pgdat);
9276b1bc 4053 }
99dcc3e5
CL
4054
4055 /*
4056 * Initialize the boot_pagesets that are going to be used
4057 * for bootstrapping processors. The real pagesets for
4058 * each zone will be allocated later when the per cpu
4059 * allocator is available.
4060 *
4061 * boot_pagesets are used also for bootstrapping offline
4062 * cpus if the system is already booted because the pagesets
4063 * are needed to initialize allocators on a specific cpu too.
4064 * F.e. the percpu allocator needs the page allocator which
4065 * needs the percpu allocator in order to allocate its pagesets
4066 * (a chicken-egg dilemma).
4067 */
7aac7898 4068 for_each_possible_cpu(cpu) {
99dcc3e5
CL
4069 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4070
7aac7898
LS
4071#ifdef CONFIG_HAVE_MEMORYLESS_NODES
4072 /*
4073 * We now know the "local memory node" for each node--
4074 * i.e., the node of the first zone in the generic zonelist.
4075 * Set up numa_mem percpu variable for on-line cpus. During
4076 * boot, only the boot cpu should be on-line; we'll init the
4077 * secondary cpus' numa_mem as they come on-line. During
4078 * node/memory hotplug, we'll fixup all on-line cpus.
4079 */
4080 if (cpu_online(cpu))
4081 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4082#endif
4083 }
4084
6811378e
YG
4085 return 0;
4086}
4087
4eaf3f64
HL
4088/*
4089 * Called with zonelists_mutex held always
4090 * unless system_state == SYSTEM_BOOTING.
4091 */
9adb62a5 4092void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
6811378e 4093{
f0c0b2b8
KH
4094 set_zonelist_order();
4095
6811378e 4096 if (system_state == SYSTEM_BOOTING) {
423b41d7 4097 __build_all_zonelists(NULL);
68ad8df4 4098 mminit_verify_zonelist();
6811378e
YG
4099 cpuset_init_current_mems_allowed();
4100 } else {
183ff22b 4101 /* we have to stop all cpus to guarantee there is no user
6811378e 4102 of zonelist */
e9959f0f 4103#ifdef CONFIG_MEMORY_HOTPLUG
9adb62a5
JL
4104 if (zone)
4105 setup_zone_pageset(zone);
e9959f0f 4106#endif
9adb62a5 4107 stop_machine(__build_all_zonelists, pgdat, NULL);
6811378e
YG
4108 /* cpuset refresh routine should be here */
4109 }
bd1e22b8 4110 vm_total_pages = nr_free_pagecache_pages();
9ef9acb0
MG
4111 /*
4112 * Disable grouping by mobility if the number of pages in the
4113 * system is too low to allow the mechanism to work. It would be
4114 * more accurate, but expensive to check per-zone. This check is
4115 * made on memory-hotadd so a system can start with mobility
4116 * disabled and enable it later
4117 */
d9c23400 4118 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
9ef9acb0
MG
4119 page_group_by_mobility_disabled = 1;
4120 else
4121 page_group_by_mobility_disabled = 0;
4122
4123 printk("Built %i zonelists in %s order, mobility grouping %s. "
4124 "Total pages: %ld\n",
62bc62a8 4125 nr_online_nodes,
f0c0b2b8 4126 zonelist_order_name[current_zonelist_order],
9ef9acb0 4127 page_group_by_mobility_disabled ? "off" : "on",
f0c0b2b8
KH
4128 vm_total_pages);
4129#ifdef CONFIG_NUMA
4130 printk("Policy zone: %s\n", zone_names[policy_zone]);
4131#endif
1da177e4
LT
4132}
4133
4134/*
4135 * Helper functions to size the waitqueue hash table.
4136 * Essentially these want to choose hash table sizes sufficiently
4137 * large so that collisions trying to wait on pages are rare.
4138 * But in fact, the number of active page waitqueues on typical
4139 * systems is ridiculously low, less than 200. So this is even
4140 * conservative, even though it seems large.
4141 *
4142 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4143 * waitqueues, i.e. the size of the waitq table given the number of pages.
4144 */
4145#define PAGES_PER_WAITQUEUE 256
4146
cca448fe 4147#ifndef CONFIG_MEMORY_HOTPLUG
02b694de 4148static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
1da177e4
LT
4149{
4150 unsigned long size = 1;
4151
4152 pages /= PAGES_PER_WAITQUEUE;
4153
4154 while (size < pages)
4155 size <<= 1;
4156
4157 /*
4158 * Once we have dozens or even hundreds of threads sleeping
4159 * on IO we've got bigger problems than wait queue collision.
4160 * Limit the size of the wait table to a reasonable size.
4161 */
4162 size = min(size, 4096UL);
4163
4164 return max(size, 4UL);
4165}
cca448fe
YG
4166#else
4167/*
4168 * A zone's size might be changed by hot-add, so it is not possible to determine
4169 * a suitable size for its wait_table. So we use the maximum size now.
4170 *
4171 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
4172 *
4173 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
4174 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4175 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
4176 *
4177 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4178 * or more by the traditional way. (See above). It equals:
4179 *
4180 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
4181 * ia64(16K page size) : = ( 8G + 4M)byte.
4182 * powerpc (64K page size) : = (32G +16M)byte.
4183 */
4184static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4185{
4186 return 4096UL;
4187}
4188#endif
1da177e4
LT
4189
4190/*
4191 * This is an integer logarithm so that shifts can be used later
4192 * to extract the more random high bits from the multiplicative
4193 * hash function before the remainder is taken.
4194 */
4195static inline unsigned long wait_table_bits(unsigned long size)
4196{
4197 return ffz(~size);
4198}
4199
4200#define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
4201
6d3163ce
AH
4202/*
4203 * Check if a pageblock contains reserved pages
4204 */
4205static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
4206{
4207 unsigned long pfn;
4208
4209 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4210 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
4211 return 1;
4212 }
4213 return 0;
4214}
4215
56fd56b8 4216/*
d9c23400 4217 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
41858966
MG
4218 * of blocks reserved is based on min_wmark_pages(zone). The memory within
4219 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
56fd56b8
MG
4220 * higher will lead to a bigger reserve which will get freed as contiguous
4221 * blocks as reclaim kicks in
4222 */
4223static void setup_zone_migrate_reserve(struct zone *zone)
4224{
6d3163ce 4225 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
56fd56b8 4226 struct page *page;
78986a67
MG
4227 unsigned long block_migratetype;
4228 int reserve;
56fd56b8 4229
d0215638
MH
4230 /*
4231 * Get the start pfn, end pfn and the number of blocks to reserve
4232 * We have to be careful to be aligned to pageblock_nr_pages to
4233 * make sure that we always check pfn_valid for the first page in
4234 * the block.
4235 */
56fd56b8 4236 start_pfn = zone->zone_start_pfn;
108bcc96 4237 end_pfn = zone_end_pfn(zone);
d0215638 4238 start_pfn = roundup(start_pfn, pageblock_nr_pages);
41858966 4239 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
d9c23400 4240 pageblock_order;
56fd56b8 4241
78986a67
MG
4242 /*
4243 * Reserve blocks are generally in place to help high-order atomic
4244 * allocations that are short-lived. A min_free_kbytes value that
4245 * would result in more than 2 reserve blocks for atomic allocations
4246 * is assumed to be in place to help anti-fragmentation for the
4247 * future allocation of hugepages at runtime.
4248 */
4249 reserve = min(2, reserve);
4250
d9c23400 4251 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
56fd56b8
MG
4252 if (!pfn_valid(pfn))
4253 continue;
4254 page = pfn_to_page(pfn);
4255
344c790e
AL
4256 /* Watch out for overlapping nodes */
4257 if (page_to_nid(page) != zone_to_nid(zone))
4258 continue;
4259
56fd56b8
MG
4260 block_migratetype = get_pageblock_migratetype(page);
4261
938929f1
MG
4262 /* Only test what is necessary when the reserves are not met */
4263 if (reserve > 0) {
4264 /*
4265 * Blocks with reserved pages will never free, skip
4266 * them.
4267 */
4268 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
4269 if (pageblock_is_reserved(pfn, block_end_pfn))
4270 continue;
56fd56b8 4271
938929f1
MG
4272 /* If this block is reserved, account for it */
4273 if (block_migratetype == MIGRATE_RESERVE) {
4274 reserve--;
4275 continue;
4276 }
4277
4278 /* Suitable for reserving if this block is movable */
4279 if (block_migratetype == MIGRATE_MOVABLE) {
4280 set_pageblock_migratetype(page,
4281 MIGRATE_RESERVE);
4282 move_freepages_block(zone, page,
4283 MIGRATE_RESERVE);
4284 reserve--;
4285 continue;
4286 }
56fd56b8
MG
4287 }
4288
4289 /*
4290 * If the reserve is met and this is a previous reserved block,
4291 * take it back
4292 */
4293 if (block_migratetype == MIGRATE_RESERVE) {
4294 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4295 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4296 }
4297 }
4298}
ac0e5b7a 4299
1da177e4
LT
4300/*
4301 * Initially all pages are reserved - free ones are freed
4302 * up by free_all_bootmem() once the early boot process is
4303 * done. Non-atomic initialization, single-pass.
4304 */
c09b4240 4305void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
a2f3aa02 4306 unsigned long start_pfn, enum memmap_context context)
1da177e4 4307{
1da177e4 4308 struct page *page;
29751f69
AW
4309 unsigned long end_pfn = start_pfn + size;
4310 unsigned long pfn;
86051ca5 4311 struct zone *z;
1da177e4 4312
22b31eec
HD
4313 if (highest_memmap_pfn < end_pfn - 1)
4314 highest_memmap_pfn = end_pfn - 1;
4315
86051ca5 4316 z = &NODE_DATA(nid)->node_zones[zone];
cbe8dd4a 4317 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
a2f3aa02
DH
4318 /*
4319 * There can be holes in boot-time mem_map[]s
4320 * handed to this function. They do not
4321 * exist on hotplugged memory.
4322 */
4323 if (context == MEMMAP_EARLY) {
4324 if (!early_pfn_valid(pfn))
4325 continue;
4326 if (!early_pfn_in_nid(pfn, nid))
4327 continue;
4328 }
d41dee36
AW
4329 page = pfn_to_page(pfn);
4330 set_page_links(page, zone, nid, pfn);
708614e6 4331 mminit_verify_page_links(page, zone, nid, pfn);
7835e98b 4332 init_page_count(page);
22b751c3
MG
4333 page_mapcount_reset(page);
4334 page_nid_reset_last(page);
1da177e4 4335 SetPageReserved(page);
b2a0ac88
MG
4336 /*
4337 * Mark the block movable so that blocks are reserved for
4338 * movable at startup. This will force kernel allocations
4339 * to reserve their blocks rather than leaking throughout
4340 * the address space during boot when many long-lived
56fd56b8
MG
4341 * kernel allocations are made. Later some blocks near
4342 * the start are marked MIGRATE_RESERVE by
4343 * setup_zone_migrate_reserve()
86051ca5
KH
4344 *
4345 * bitmap is created for zone's valid pfn range. but memmap
4346 * can be created for invalid pages (for alignment)
4347 * check here not to call set_pageblock_migratetype() against
4348 * pfn out of zone.
b2a0ac88 4349 */
86051ca5 4350 if ((z->zone_start_pfn <= pfn)
108bcc96 4351 && (pfn < zone_end_pfn(z))
86051ca5 4352 && !(pfn & (pageblock_nr_pages - 1)))
56fd56b8 4353 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
b2a0ac88 4354
1da177e4
LT
4355 INIT_LIST_HEAD(&page->lru);
4356#ifdef WANT_PAGE_VIRTUAL
4357 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
4358 if (!is_highmem_idx(zone))
3212c6be 4359 set_page_address(page, __va(pfn << PAGE_SHIFT));
1da177e4 4360#endif
1da177e4
LT
4361 }
4362}
4363
1e548deb 4364static void __meminit zone_init_free_lists(struct zone *zone)
1da177e4 4365{
b2a0ac88
MG
4366 int order, t;
4367 for_each_migratetype_order(order, t) {
4368 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
1da177e4
LT
4369 zone->free_area[order].nr_free = 0;
4370 }
4371}
4372
4373#ifndef __HAVE_ARCH_MEMMAP_INIT
4374#define memmap_init(size, nid, zone, start_pfn) \
a2f3aa02 4375 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
1da177e4
LT
4376#endif
4377
4ed7e022 4378static int __meminit zone_batchsize(struct zone *zone)
e7c8d5c9 4379{
3a6be87f 4380#ifdef CONFIG_MMU
e7c8d5c9
CL
4381 int batch;
4382
4383 /*
4384 * The per-cpu-pages pools are set to around 1000th of the
ba56e91c 4385 * size of the zone. But no more than 1/2 of a meg.
e7c8d5c9
CL
4386 *
4387 * OK, so we don't know how big the cache is. So guess.
4388 */
b40da049 4389 batch = zone->managed_pages / 1024;
ba56e91c
SR
4390 if (batch * PAGE_SIZE > 512 * 1024)
4391 batch = (512 * 1024) / PAGE_SIZE;
e7c8d5c9
CL
4392 batch /= 4; /* We effectively *= 4 below */
4393 if (batch < 1)
4394 batch = 1;
4395
4396 /*
0ceaacc9
NP
4397 * Clamp the batch to a 2^n - 1 value. Having a power
4398 * of 2 value was found to be more likely to have
4399 * suboptimal cache aliasing properties in some cases.
e7c8d5c9 4400 *
0ceaacc9
NP
4401 * For example if 2 tasks are alternately allocating
4402 * batches of pages, one task can end up with a lot
4403 * of pages of one half of the possible page colors
4404 * and the other with pages of the other colors.
e7c8d5c9 4405 */
9155203a 4406 batch = rounddown_pow_of_two(batch + batch/2) - 1;
ba56e91c 4407
e7c8d5c9 4408 return batch;
3a6be87f
DH
4409
4410#else
4411 /* The deferral and batching of frees should be suppressed under NOMMU
4412 * conditions.
4413 *
4414 * The problem is that NOMMU needs to be able to allocate large chunks
4415 * of contiguous memory as there's no hardware page translation to
4416 * assemble apparent contiguous memory from discontiguous pages.
4417 *
4418 * Queueing large contiguous runs of pages for batching, however,
4419 * causes the pages to actually be freed in smaller chunks. As there
4420 * can be a significant delay between the individual batches being
4421 * recycled, this leads to the once large chunks of space being
4422 * fragmented and becoming unavailable for high-order allocations.
4423 */
4424 return 0;
4425#endif
e7c8d5c9
CL
4426}
4427
b69a7288 4428static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2caaad41
CL
4429{
4430 struct per_cpu_pages *pcp;
5f8dcc21 4431 int migratetype;
2caaad41 4432
1c6fe946
MD
4433 memset(p, 0, sizeof(*p));
4434
3dfa5721 4435 pcp = &p->pcp;
2caaad41 4436 pcp->count = 0;
2caaad41
CL
4437 pcp->high = 6 * batch;
4438 pcp->batch = max(1UL, 1 * batch);
5f8dcc21
MG
4439 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4440 INIT_LIST_HEAD(&pcp->lists[migratetype]);
2caaad41
CL
4441}
4442
8ad4b1fb
RS
4443/*
4444 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
4445 * to the value high for the pageset p.
4446 */
4447
4448static void setup_pagelist_highmark(struct per_cpu_pageset *p,
4449 unsigned long high)
4450{
4451 struct per_cpu_pages *pcp;
4452
3dfa5721 4453 pcp = &p->pcp;
8ad4b1fb
RS
4454 pcp->high = high;
4455 pcp->batch = max(1UL, high/4);
4456 if ((high/4) > (PAGE_SHIFT * 8))
4457 pcp->batch = PAGE_SHIFT * 8;
4458}
4459
4ed7e022 4460static void __meminit setup_zone_pageset(struct zone *zone)
319774e2
WF
4461{
4462 int cpu;
4463
4464 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4465
4466 for_each_possible_cpu(cpu) {
4467 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4468
4469 setup_pageset(pcp, zone_batchsize(zone));
4470
4471 if (percpu_pagelist_fraction)
4472 setup_pagelist_highmark(pcp,
b40da049 4473 (zone->managed_pages /
319774e2
WF
4474 percpu_pagelist_fraction));
4475 }
4476}
4477
2caaad41 4478/*
99dcc3e5
CL
4479 * Allocate per cpu pagesets and initialize them.
4480 * Before this call only boot pagesets were available.
e7c8d5c9 4481 */
99dcc3e5 4482void __init setup_per_cpu_pageset(void)
e7c8d5c9 4483{
99dcc3e5 4484 struct zone *zone;
e7c8d5c9 4485
319774e2
WF
4486 for_each_populated_zone(zone)
4487 setup_zone_pageset(zone);
e7c8d5c9
CL
4488}
4489
577a32f6 4490static noinline __init_refok
cca448fe 4491int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
ed8ece2e
DH
4492{
4493 int i;
4494 struct pglist_data *pgdat = zone->zone_pgdat;
cca448fe 4495 size_t alloc_size;
ed8ece2e
DH
4496
4497 /*
4498 * The per-page waitqueue mechanism uses hashed waitqueues
4499 * per zone.
4500 */
02b694de
YG
4501 zone->wait_table_hash_nr_entries =
4502 wait_table_hash_nr_entries(zone_size_pages);
4503 zone->wait_table_bits =
4504 wait_table_bits(zone->wait_table_hash_nr_entries);
cca448fe
YG
4505 alloc_size = zone->wait_table_hash_nr_entries
4506 * sizeof(wait_queue_head_t);
4507
cd94b9db 4508 if (!slab_is_available()) {
cca448fe 4509 zone->wait_table = (wait_queue_head_t *)
8f389a99 4510 alloc_bootmem_node_nopanic(pgdat, alloc_size);
cca448fe
YG
4511 } else {
4512 /*
4513 * This case means that a zone whose size was 0 gets new memory
4514 * via memory hot-add.
4515 * But it may be the case that a new node was hot-added. In
4516 * this case vmalloc() will not be able to use this new node's
4517 * memory - this wait_table must be initialized to use this new
4518 * node itself as well.
4519 * To use this new node's memory, further consideration will be
4520 * necessary.
4521 */
8691f3a7 4522 zone->wait_table = vmalloc(alloc_size);
cca448fe
YG
4523 }
4524 if (!zone->wait_table)
4525 return -ENOMEM;
ed8ece2e 4526
02b694de 4527 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
ed8ece2e 4528 init_waitqueue_head(zone->wait_table + i);
cca448fe
YG
4529
4530 return 0;
ed8ece2e
DH
4531}
4532
c09b4240 4533static __meminit void zone_pcp_init(struct zone *zone)
ed8ece2e 4534{
99dcc3e5
CL
4535 /*
4536 * per cpu subsystem is not up at this point. The following code
4537 * relies on the ability of the linker to provide the
4538 * offset of a (static) per cpu variable into the per cpu area.
4539 */
4540 zone->pageset = &boot_pageset;
ed8ece2e 4541
f5335c0f 4542 if (zone->present_pages)
99dcc3e5
CL
4543 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4544 zone->name, zone->present_pages,
4545 zone_batchsize(zone));
ed8ece2e
DH
4546}
4547
4ed7e022 4548int __meminit init_currently_empty_zone(struct zone *zone,
718127cc 4549 unsigned long zone_start_pfn,
a2f3aa02
DH
4550 unsigned long size,
4551 enum memmap_context context)
ed8ece2e
DH
4552{
4553 struct pglist_data *pgdat = zone->zone_pgdat;
cca448fe
YG
4554 int ret;
4555 ret = zone_wait_table_init(zone, size);
4556 if (ret)
4557 return ret;
ed8ece2e
DH
4558 pgdat->nr_zones = zone_idx(zone) + 1;
4559
ed8ece2e
DH
4560 zone->zone_start_pfn = zone_start_pfn;
4561
708614e6
MG
4562 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4563 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4564 pgdat->node_id,
4565 (unsigned long)zone_idx(zone),
4566 zone_start_pfn, (zone_start_pfn + size));
4567
1e548deb 4568 zone_init_free_lists(zone);
718127cc
YG
4569
4570 return 0;
ed8ece2e
DH
4571}
4572
0ee332c1 4573#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
c713216d
MG
4574#ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4575/*
4576 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4577 * Architectures may implement their own version but if add_active_range()
4578 * was used and there are no special requirements, this is a convenient
4579 * alternative
4580 */
f2dbcfa7 4581int __meminit __early_pfn_to_nid(unsigned long pfn)
c713216d 4582{
c13291a5
TH
4583 unsigned long start_pfn, end_pfn;
4584 int i, nid;
7c243c71
RA
4585 /*
4586 * NOTE: The following SMP-unsafe globals are only used early in boot
4587 * when the kernel is running single-threaded.
4588 */
4589 static unsigned long __meminitdata last_start_pfn, last_end_pfn;
4590 static int __meminitdata last_nid;
4591
4592 if (last_start_pfn <= pfn && pfn < last_end_pfn)
4593 return last_nid;
c713216d 4594
c13291a5 4595 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
7c243c71
RA
4596 if (start_pfn <= pfn && pfn < end_pfn) {
4597 last_start_pfn = start_pfn;
4598 last_end_pfn = end_pfn;
4599 last_nid = nid;
c13291a5 4600 return nid;
7c243c71 4601 }
cc2559bc
KH
4602 /* This is a memory hole */
4603 return -1;
c713216d
MG
4604}
4605#endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4606
f2dbcfa7
KH
4607int __meminit early_pfn_to_nid(unsigned long pfn)
4608{
cc2559bc
KH
4609 int nid;
4610
4611 nid = __early_pfn_to_nid(pfn);
4612 if (nid >= 0)
4613 return nid;
4614 /* just returns 0 */
4615 return 0;
f2dbcfa7
KH
4616}
4617
cc2559bc
KH
4618#ifdef CONFIG_NODES_SPAN_OTHER_NODES
4619bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4620{
4621 int nid;
4622
4623 nid = __early_pfn_to_nid(pfn);
4624 if (nid >= 0 && nid != node)
4625 return false;
4626 return true;
4627}
4628#endif
f2dbcfa7 4629
c713216d
MG
4630/**
4631 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
88ca3b94
RD
4632 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4633 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
c713216d
MG
4634 *
4635 * If an architecture guarantees that all ranges registered with
4636 * add_active_ranges() contain no holes and may be freed, this
4637 * this function may be used instead of calling free_bootmem() manually.
4638 */
c13291a5 4639void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
cc289894 4640{
c13291a5
TH
4641 unsigned long start_pfn, end_pfn;
4642 int i, this_nid;
edbe7d23 4643
c13291a5
TH
4644 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4645 start_pfn = min(start_pfn, max_low_pfn);
4646 end_pfn = min(end_pfn, max_low_pfn);
edbe7d23 4647
c13291a5
TH
4648 if (start_pfn < end_pfn)
4649 free_bootmem_node(NODE_DATA(this_nid),
4650 PFN_PHYS(start_pfn),
4651 (end_pfn - start_pfn) << PAGE_SHIFT);
edbe7d23 4652 }
edbe7d23 4653}
edbe7d23 4654
c713216d
MG
4655/**
4656 * sparse_memory_present_with_active_regions - Call memory_present for each active range
88ca3b94 4657 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
c713216d
MG
4658 *
4659 * If an architecture guarantees that all ranges registered with
4660 * add_active_ranges() contain no holes and may be freed, this
88ca3b94 4661 * function may be used instead of calling memory_present() manually.
c713216d
MG
4662 */
4663void __init sparse_memory_present_with_active_regions(int nid)
4664{
c13291a5
TH
4665 unsigned long start_pfn, end_pfn;
4666 int i, this_nid;
c713216d 4667
c13291a5
TH
4668 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4669 memory_present(this_nid, start_pfn, end_pfn);
c713216d
MG
4670}
4671
4672/**
4673 * get_pfn_range_for_nid - Return the start and end page frames for a node
88ca3b94
RD
4674 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4675 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4676 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
c713216d
MG
4677 *
4678 * It returns the start and end page frame of a node based on information
4679 * provided by an arch calling add_active_range(). If called for a node
4680 * with no available memory, a warning is printed and the start and end
88ca3b94 4681 * PFNs will be 0.
c713216d 4682 */
a3142c8e 4683void __meminit get_pfn_range_for_nid(unsigned int nid,
c713216d
MG
4684 unsigned long *start_pfn, unsigned long *end_pfn)
4685{
c13291a5 4686 unsigned long this_start_pfn, this_end_pfn;
c713216d 4687 int i;
c13291a5 4688
c713216d
MG
4689 *start_pfn = -1UL;
4690 *end_pfn = 0;
4691
c13291a5
TH
4692 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4693 *start_pfn = min(*start_pfn, this_start_pfn);
4694 *end_pfn = max(*end_pfn, this_end_pfn);
c713216d
MG
4695 }
4696
633c0666 4697 if (*start_pfn == -1UL)
c713216d 4698 *start_pfn = 0;
c713216d
MG
4699}
4700
2a1e274a
MG
4701/*
4702 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4703 * assumption is made that zones within a node are ordered in monotonic
4704 * increasing memory addresses so that the "highest" populated zone is used
4705 */
b69a7288 4706static void __init find_usable_zone_for_movable(void)
2a1e274a
MG
4707{
4708 int zone_index;
4709 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4710 if (zone_index == ZONE_MOVABLE)
4711 continue;
4712
4713 if (arch_zone_highest_possible_pfn[zone_index] >
4714 arch_zone_lowest_possible_pfn[zone_index])
4715 break;
4716 }
4717
4718 VM_BUG_ON(zone_index == -1);
4719 movable_zone = zone_index;
4720}
4721
4722/*
4723 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
25985edc 4724 * because it is sized independent of architecture. Unlike the other zones,
2a1e274a
MG
4725 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4726 * in each node depending on the size of each node and how evenly kernelcore
4727 * is distributed. This helper function adjusts the zone ranges
4728 * provided by the architecture for a given node by using the end of the
4729 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4730 * zones within a node are in order of monotonic increases memory addresses
4731 */
b69a7288 4732static void __meminit adjust_zone_range_for_zone_movable(int nid,
2a1e274a
MG
4733 unsigned long zone_type,
4734 unsigned long node_start_pfn,
4735 unsigned long node_end_pfn,
4736 unsigned long *zone_start_pfn,
4737 unsigned long *zone_end_pfn)
4738{
4739 /* Only adjust if ZONE_MOVABLE is on this node */
4740 if (zone_movable_pfn[nid]) {
4741 /* Size ZONE_MOVABLE */
4742 if (zone_type == ZONE_MOVABLE) {
4743 *zone_start_pfn = zone_movable_pfn[nid];
4744 *zone_end_pfn = min(node_end_pfn,
4745 arch_zone_highest_possible_pfn[movable_zone]);
4746
4747 /* Adjust for ZONE_MOVABLE starting within this range */
4748 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4749 *zone_end_pfn > zone_movable_pfn[nid]) {
4750 *zone_end_pfn = zone_movable_pfn[nid];
4751
4752 /* Check if this whole range is within ZONE_MOVABLE */
4753 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4754 *zone_start_pfn = *zone_end_pfn;
4755 }
4756}
4757
c713216d
MG
4758/*
4759 * Return the number of pages a zone spans in a node, including holes
4760 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4761 */
6ea6e688 4762static unsigned long __meminit zone_spanned_pages_in_node(int nid,
c713216d
MG
4763 unsigned long zone_type,
4764 unsigned long *ignored)
4765{
4766 unsigned long node_start_pfn, node_end_pfn;
4767 unsigned long zone_start_pfn, zone_end_pfn;
4768
4769 /* Get the start and end of the node and zone */
4770 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4771 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4772 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
2a1e274a
MG
4773 adjust_zone_range_for_zone_movable(nid, zone_type,
4774 node_start_pfn, node_end_pfn,
4775 &zone_start_pfn, &zone_end_pfn);
c713216d
MG
4776
4777 /* Check that this node has pages within the zone's required range */
4778 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4779 return 0;
4780
4781 /* Move the zone boundaries inside the node if necessary */
4782 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4783 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4784
4785 /* Return the spanned pages */
4786 return zone_end_pfn - zone_start_pfn;
4787}
4788
4789/*
4790 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
88ca3b94 4791 * then all holes in the requested range will be accounted for.
c713216d 4792 */
32996250 4793unsigned long __meminit __absent_pages_in_range(int nid,
c713216d
MG
4794 unsigned long range_start_pfn,
4795 unsigned long range_end_pfn)
4796{
96e907d1
TH
4797 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4798 unsigned long start_pfn, end_pfn;
4799 int i;
c713216d 4800
96e907d1
TH
4801 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4802 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4803 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4804 nr_absent -= end_pfn - start_pfn;
c713216d 4805 }
96e907d1 4806 return nr_absent;
c713216d
MG
4807}
4808
4809/**
4810 * absent_pages_in_range - Return number of page frames in holes within a range
4811 * @start_pfn: The start PFN to start searching for holes
4812 * @end_pfn: The end PFN to stop searching for holes
4813 *
88ca3b94 4814 * It returns the number of pages frames in memory holes within a range.
c713216d
MG
4815 */
4816unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4817 unsigned long end_pfn)
4818{
4819 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4820}
4821
4822/* Return the number of page frames in holes in a zone on a node */
6ea6e688 4823static unsigned long __meminit zone_absent_pages_in_node(int nid,
c713216d
MG
4824 unsigned long zone_type,
4825 unsigned long *ignored)
4826{
96e907d1
TH
4827 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4828 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
9c7cd687
MG
4829 unsigned long node_start_pfn, node_end_pfn;
4830 unsigned long zone_start_pfn, zone_end_pfn;
4831
4832 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
96e907d1
TH
4833 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4834 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
9c7cd687 4835
2a1e274a
MG
4836 adjust_zone_range_for_zone_movable(nid, zone_type,
4837 node_start_pfn, node_end_pfn,
4838 &zone_start_pfn, &zone_end_pfn);
9c7cd687 4839 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
c713216d 4840}
0e0b864e 4841
0ee332c1 4842#else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6ea6e688 4843static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
c713216d
MG
4844 unsigned long zone_type,
4845 unsigned long *zones_size)
4846{
4847 return zones_size[zone_type];
4848}
4849
6ea6e688 4850static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
c713216d
MG
4851 unsigned long zone_type,
4852 unsigned long *zholes_size)
4853{
4854 if (!zholes_size)
4855 return 0;
4856
4857 return zholes_size[zone_type];
4858}
20e6926d 4859
0ee332c1 4860#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 4861
a3142c8e 4862static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
c713216d
MG
4863 unsigned long *zones_size, unsigned long *zholes_size)
4864{
4865 unsigned long realtotalpages, totalpages = 0;
4866 enum zone_type i;
4867
4868 for (i = 0; i < MAX_NR_ZONES; i++)
4869 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4870 zones_size);
4871 pgdat->node_spanned_pages = totalpages;
4872
4873 realtotalpages = totalpages;
4874 for (i = 0; i < MAX_NR_ZONES; i++)
4875 realtotalpages -=
4876 zone_absent_pages_in_node(pgdat->node_id, i,
4877 zholes_size);
4878 pgdat->node_present_pages = realtotalpages;
4879 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4880 realtotalpages);
4881}
4882
835c134e
MG
4883#ifndef CONFIG_SPARSEMEM
4884/*
4885 * Calculate the size of the zone->blockflags rounded to an unsigned long
d9c23400
MG
4886 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4887 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
835c134e
MG
4888 * round what is now in bits to nearest long in bits, then return it in
4889 * bytes.
4890 */
7c45512d 4891static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
835c134e
MG
4892{
4893 unsigned long usemapsize;
4894
7c45512d 4895 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
d9c23400
MG
4896 usemapsize = roundup(zonesize, pageblock_nr_pages);
4897 usemapsize = usemapsize >> pageblock_order;
835c134e
MG
4898 usemapsize *= NR_PAGEBLOCK_BITS;
4899 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4900
4901 return usemapsize / 8;
4902}
4903
4904static void __init setup_usemap(struct pglist_data *pgdat,
7c45512d
LT
4905 struct zone *zone,
4906 unsigned long zone_start_pfn,
4907 unsigned long zonesize)
835c134e 4908{
7c45512d 4909 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
835c134e 4910 zone->pageblock_flags = NULL;
58a01a45 4911 if (usemapsize)
8f389a99
YL
4912 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4913 usemapsize);
835c134e
MG
4914}
4915#else
7c45512d
LT
4916static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4917 unsigned long zone_start_pfn, unsigned long zonesize) {}
835c134e
MG
4918#endif /* CONFIG_SPARSEMEM */
4919
d9c23400 4920#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
ba72cb8c 4921
d9c23400 4922/* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
ca57df79 4923void __init set_pageblock_order(void)
d9c23400 4924{
955c1cd7
AM
4925 unsigned int order;
4926
d9c23400
MG
4927 /* Check that pageblock_nr_pages has not already been setup */
4928 if (pageblock_order)
4929 return;
4930
955c1cd7
AM
4931 if (HPAGE_SHIFT > PAGE_SHIFT)
4932 order = HUGETLB_PAGE_ORDER;
4933 else
4934 order = MAX_ORDER - 1;
4935
d9c23400
MG
4936 /*
4937 * Assume the largest contiguous order of interest is a huge page.
955c1cd7
AM
4938 * This value may be variable depending on boot parameters on IA64 and
4939 * powerpc.
d9c23400
MG
4940 */
4941 pageblock_order = order;
4942}
4943#else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4944
ba72cb8c
MG
4945/*
4946 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
955c1cd7
AM
4947 * is unused as pageblock_order is set at compile-time. See
4948 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4949 * the kernel config
ba72cb8c 4950 */
ca57df79 4951void __init set_pageblock_order(void)
ba72cb8c 4952{
ba72cb8c 4953}
d9c23400
MG
4954
4955#endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4956
01cefaef
JL
4957static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
4958 unsigned long present_pages)
4959{
4960 unsigned long pages = spanned_pages;
4961
4962 /*
4963 * Provide a more accurate estimation if there are holes within
4964 * the zone and SPARSEMEM is in use. If there are holes within the
4965 * zone, each populated memory region may cost us one or two extra
4966 * memmap pages due to alignment because memmap pages for each
4967 * populated regions may not naturally algined on page boundary.
4968 * So the (present_pages >> 4) heuristic is a tradeoff for that.
4969 */
4970 if (spanned_pages > present_pages + (present_pages >> 4) &&
4971 IS_ENABLED(CONFIG_SPARSEMEM))
4972 pages = present_pages;
4973
4974 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
4975}
4976
6fa3eb70
S
4977#ifdef CONFIG_MTKPASR
4978extern void init_mtkpasr_range(struct zone *zone);
4979#else
4980#define init_mtkpasr_range(zone) do {} while (0)
4981#endif
4982
1da177e4
LT
4983/*
4984 * Set up the zone data structures:
4985 * - mark all pages reserved
4986 * - mark all memory queues empty
4987 * - clear the memory bitmaps
6527af5d
MK
4988 *
4989 * NOTE: pgdat should get zeroed by caller.
1da177e4 4990 */
b5a0e011 4991static void __paginginit free_area_init_core(struct pglist_data *pgdat,
1da177e4
LT
4992 unsigned long *zones_size, unsigned long *zholes_size)
4993{
2f1b6248 4994 enum zone_type j;
ed8ece2e 4995 int nid = pgdat->node_id;
1da177e4 4996 unsigned long zone_start_pfn = pgdat->node_start_pfn;
718127cc 4997 int ret;
1da177e4 4998
208d54e5 4999 pgdat_resize_init(pgdat);
8177a420
AA
5000#ifdef CONFIG_NUMA_BALANCING
5001 spin_lock_init(&pgdat->numabalancing_migrate_lock);
5002 pgdat->numabalancing_migrate_nr_pages = 0;
5003 pgdat->numabalancing_migrate_next_window = jiffies;
5004#endif
1da177e4 5005 init_waitqueue_head(&pgdat->kswapd_wait);
5515061d 5006 init_waitqueue_head(&pgdat->pfmemalloc_wait);
52d4b9ac 5007 pgdat_page_cgroup_init(pgdat);
5f63b720 5008
1da177e4
LT
5009 for (j = 0; j < MAX_NR_ZONES; j++) {
5010 struct zone *zone = pgdat->node_zones + j;
9feedc9d 5011 unsigned long size, realsize, freesize, memmap_pages;
1da177e4 5012
c713216d 5013 size = zone_spanned_pages_in_node(nid, j, zones_size);
9feedc9d 5014 realsize = freesize = size - zone_absent_pages_in_node(nid, j,
c713216d 5015 zholes_size);
1da177e4 5016
0e0b864e 5017 /*
9feedc9d 5018 * Adjust freesize so that it accounts for how much memory
0e0b864e
MG
5019 * is used by this zone for memmap. This affects the watermark
5020 * and per-cpu initialisations
5021 */
01cefaef 5022 memmap_pages = calc_memmap_size(size, realsize);
9feedc9d
JL
5023 if (freesize >= memmap_pages) {
5024 freesize -= memmap_pages;
5594c8c8
YL
5025 if (memmap_pages)
5026 printk(KERN_DEBUG
5027 " %s zone: %lu pages used for memmap\n",
5028 zone_names[j], memmap_pages);
0e0b864e
MG
5029 } else
5030 printk(KERN_WARNING
9feedc9d
JL
5031 " %s zone: %lu pages exceeds freesize %lu\n",
5032 zone_names[j], memmap_pages, freesize);
0e0b864e 5033
6267276f 5034 /* Account for reserved pages */
9feedc9d
JL
5035 if (j == 0 && freesize > dma_reserve) {
5036 freesize -= dma_reserve;
d903ef9f 5037 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
6267276f 5038 zone_names[0], dma_reserve);
0e0b864e
MG
5039 }
5040
98d2b0eb 5041 if (!is_highmem_idx(j))
9feedc9d 5042 nr_kernel_pages += freesize;
01cefaef
JL
5043 /* Charge for highmem memmap if there are enough kernel pages */
5044 else if (nr_kernel_pages > memmap_pages * 2)
5045 nr_kernel_pages -= memmap_pages;
9feedc9d 5046 nr_all_pages += freesize;
1da177e4
LT
5047
5048 zone->spanned_pages = size;
306f2e9e 5049 zone->present_pages = realsize;
9feedc9d
JL
5050 /*
5051 * Set an approximate value for lowmem here, it will be adjusted
5052 * when the bootmem allocator frees pages into the buddy system.
5053 * And all highmem pages will be managed by the buddy system.
5054 */
5055 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
9614634f 5056#ifdef CONFIG_NUMA
d5f541ed 5057 zone->node = nid;
9feedc9d 5058 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
9614634f 5059 / 100;
9feedc9d 5060 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
9614634f 5061#endif
1da177e4
LT
5062 zone->name = zone_names[j];
5063 spin_lock_init(&zone->lock);
5064 spin_lock_init(&zone->lru_lock);
bdc8cb98 5065 zone_seqlock_init(zone);
1da177e4 5066 zone->zone_pgdat = pgdat;
1da177e4 5067
ed8ece2e 5068 zone_pcp_init(zone);
bea8c150 5069 lruvec_init(&zone->lruvec);
1da177e4
LT
5070 if (!size)
5071 continue;
5072
955c1cd7 5073 set_pageblock_order();
7c45512d 5074 setup_usemap(pgdat, zone, zone_start_pfn, size);
a2f3aa02
DH
5075 ret = init_currently_empty_zone(zone, zone_start_pfn,
5076 size, MEMMAP_EARLY);
718127cc 5077 BUG_ON(ret);
76cdd58e 5078 memmap_init(size, nid, j, zone_start_pfn);
1da177e4 5079 zone_start_pfn += size;
1da177e4 5080 }
6fa3eb70
S
5081
5082 /* Initialize the imposed range of active PASR: only to create a range in HIGHMEM zone! */
5083 init_mtkpasr_range(pgdat->node_zones);
1da177e4
LT
5084}
5085
577a32f6 5086static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
1da177e4 5087{
1da177e4
LT
5088 /* Skip empty nodes */
5089 if (!pgdat->node_spanned_pages)
5090 return;
5091
d41dee36 5092#ifdef CONFIG_FLAT_NODE_MEM_MAP
1da177e4
LT
5093 /* ia64 gets its own node_mem_map, before this, without bootmem */
5094 if (!pgdat->node_mem_map) {
e984bb43 5095 unsigned long size, start, end;
d41dee36
AW
5096 struct page *map;
5097
e984bb43
BP
5098 /*
5099 * The zone's endpoints aren't required to be MAX_ORDER
5100 * aligned but the node_mem_map endpoints must be in order
5101 * for the buddy allocator to function correctly.
5102 */
5103 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
108bcc96 5104 end = pgdat_end_pfn(pgdat);
e984bb43
BP
5105 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5106 size = (end - start) * sizeof(struct page);
6f167ec7
DH
5107 map = alloc_remap(pgdat->node_id, size);
5108 if (!map)
8f389a99 5109 map = alloc_bootmem_node_nopanic(pgdat, size);
e984bb43 5110 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
1da177e4 5111 }
12d810c1 5112#ifndef CONFIG_NEED_MULTIPLE_NODES
1da177e4
LT
5113 /*
5114 * With no DISCONTIG, the global mem_map is just set as node 0's
5115 */
c713216d 5116 if (pgdat == NODE_DATA(0)) {
1da177e4 5117 mem_map = NODE_DATA(0)->node_mem_map;
0ee332c1 5118#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
c713216d 5119 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
467bc461 5120 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
0ee332c1 5121#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 5122 }
1da177e4 5123#endif
d41dee36 5124#endif /* CONFIG_FLAT_NODE_MEM_MAP */
1da177e4
LT
5125}
5126
9109fb7b
JW
5127void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5128 unsigned long node_start_pfn, unsigned long *zholes_size)
1da177e4 5129{
9109fb7b
JW
5130 pg_data_t *pgdat = NODE_DATA(nid);
5131
88fdf75d 5132 /* pg_data_t should be reset to zero when it's allocated */
8783b6e2 5133 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
88fdf75d 5134
1da177e4
LT
5135 pgdat->node_id = nid;
5136 pgdat->node_start_pfn = node_start_pfn;
957f822a 5137 init_zone_allows_reclaim(nid);
c713216d 5138 calculate_node_totalpages(pgdat, zones_size, zholes_size);
1da177e4
LT
5139
5140 alloc_node_mem_map(pgdat);
e8c27ac9
YL
5141#ifdef CONFIG_FLAT_NODE_MEM_MAP
5142 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5143 nid, (unsigned long)pgdat,
5144 (unsigned long)pgdat->node_mem_map);
5145#endif
1da177e4
LT
5146
5147 free_area_init_core(pgdat, zones_size, zholes_size);
5148}
5149
0ee332c1 5150#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
418508c1
MS
5151
5152#if MAX_NUMNODES > 1
5153/*
5154 * Figure out the number of possible node ids.
5155 */
f9872caf 5156void __init setup_nr_node_ids(void)
418508c1
MS
5157{
5158 unsigned int node;
5159 unsigned int highest = 0;
5160
5161 for_each_node_mask(node, node_possible_map)
5162 highest = node;
5163 nr_node_ids = highest + 1;
5164}
418508c1
MS
5165#endif
5166
1e01979c
TH
5167/**
5168 * node_map_pfn_alignment - determine the maximum internode alignment
5169 *
5170 * This function should be called after node map is populated and sorted.
5171 * It calculates the maximum power of two alignment which can distinguish
5172 * all the nodes.
5173 *
5174 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5175 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5176 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5177 * shifted, 1GiB is enough and this function will indicate so.
5178 *
5179 * This is used to test whether pfn -> nid mapping of the chosen memory
5180 * model has fine enough granularity to avoid incorrect mapping for the
5181 * populated node map.
5182 *
5183 * Returns the determined alignment in pfn's. 0 if there is no alignment
5184 * requirement (single node).
5185 */
5186unsigned long __init node_map_pfn_alignment(void)
5187{
5188 unsigned long accl_mask = 0, last_end = 0;
c13291a5 5189 unsigned long start, end, mask;
1e01979c 5190 int last_nid = -1;
c13291a5 5191 int i, nid;
1e01979c 5192
c13291a5 5193 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
1e01979c
TH
5194 if (!start || last_nid < 0 || last_nid == nid) {
5195 last_nid = nid;
5196 last_end = end;
5197 continue;
5198 }
5199
5200 /*
5201 * Start with a mask granular enough to pin-point to the
5202 * start pfn and tick off bits one-by-one until it becomes
5203 * too coarse to separate the current node from the last.
5204 */
5205 mask = ~((1 << __ffs(start)) - 1);
5206 while (mask && last_end <= (start & (mask << 1)))
5207 mask <<= 1;
5208
5209 /* accumulate all internode masks */
5210 accl_mask |= mask;
5211 }
5212
5213 /* convert mask to number of pages */
5214 return ~accl_mask + 1;
5215}
5216
a6af2bc3 5217/* Find the lowest pfn for a node */
b69a7288 5218static unsigned long __init find_min_pfn_for_node(int nid)
c713216d 5219{
a6af2bc3 5220 unsigned long min_pfn = ULONG_MAX;
c13291a5
TH
5221 unsigned long start_pfn;
5222 int i;
1abbfb41 5223
c13291a5
TH
5224 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5225 min_pfn = min(min_pfn, start_pfn);
c713216d 5226
a6af2bc3
MG
5227 if (min_pfn == ULONG_MAX) {
5228 printk(KERN_WARNING
2bc0d261 5229 "Could not find start_pfn for node %d\n", nid);
a6af2bc3
MG
5230 return 0;
5231 }
5232
5233 return min_pfn;
c713216d
MG
5234}
5235
5236/**
5237 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5238 *
5239 * It returns the minimum PFN based on information provided via
88ca3b94 5240 * add_active_range().
c713216d
MG
5241 */
5242unsigned long __init find_min_pfn_with_active_regions(void)
5243{
5244 return find_min_pfn_for_node(MAX_NUMNODES);
5245}
5246
37b07e41
LS
5247/*
5248 * early_calculate_totalpages()
5249 * Sum pages in active regions for movable zone.
4b0ef1fe 5250 * Populate N_MEMORY for calculating usable_nodes.
37b07e41 5251 */
484f51f8 5252static unsigned long __init early_calculate_totalpages(void)
7e63efef 5253{
7e63efef 5254 unsigned long totalpages = 0;
c13291a5
TH
5255 unsigned long start_pfn, end_pfn;
5256 int i, nid;
5257
5258 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5259 unsigned long pages = end_pfn - start_pfn;
7e63efef 5260
37b07e41
LS
5261 totalpages += pages;
5262 if (pages)
4b0ef1fe 5263 node_set_state(nid, N_MEMORY);
37b07e41
LS
5264 }
5265 return totalpages;
7e63efef
MG
5266}
5267
2a1e274a
MG
5268/*
5269 * Find the PFN the Movable zone begins in each node. Kernel memory
5270 * is spread evenly between nodes as long as the nodes have enough
5271 * memory. When they don't, some nodes will have more kernelcore than
5272 * others
5273 */
b224ef85 5274static void __init find_zone_movable_pfns_for_nodes(void)
2a1e274a
MG
5275{
5276 int i, nid;
5277 unsigned long usable_startpfn;
5278 unsigned long kernelcore_node, kernelcore_remaining;
66918dcd 5279 /* save the state before borrow the nodemask */
4b0ef1fe 5280 nodemask_t saved_node_state = node_states[N_MEMORY];
37b07e41 5281 unsigned long totalpages = early_calculate_totalpages();
4b0ef1fe 5282 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
2a1e274a 5283
7e63efef
MG
5284 /*
5285 * If movablecore was specified, calculate what size of
5286 * kernelcore that corresponds so that memory usable for
5287 * any allocation type is evenly spread. If both kernelcore
5288 * and movablecore are specified, then the value of kernelcore
5289 * will be used for required_kernelcore if it's greater than
5290 * what movablecore would have allowed.
5291 */
5292 if (required_movablecore) {
7e63efef
MG
5293 unsigned long corepages;
5294
5295 /*
5296 * Round-up so that ZONE_MOVABLE is at least as large as what
5297 * was requested by the user
5298 */
5299 required_movablecore =
5300 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5301 corepages = totalpages - required_movablecore;
5302
5303 required_kernelcore = max(required_kernelcore, corepages);
5304 }
5305
20e6926d
YL
5306 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
5307 if (!required_kernelcore)
66918dcd 5308 goto out;
2a1e274a
MG
5309
5310 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
20e6926d 5311 find_usable_zone_for_movable();
2a1e274a
MG
5312 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5313
5314restart:
5315 /* Spread kernelcore memory as evenly as possible throughout nodes */
5316 kernelcore_node = required_kernelcore / usable_nodes;
4b0ef1fe 5317 for_each_node_state(nid, N_MEMORY) {
c13291a5
TH
5318 unsigned long start_pfn, end_pfn;
5319
2a1e274a
MG
5320 /*
5321 * Recalculate kernelcore_node if the division per node
5322 * now exceeds what is necessary to satisfy the requested
5323 * amount of memory for the kernel
5324 */
5325 if (required_kernelcore < kernelcore_node)
5326 kernelcore_node = required_kernelcore / usable_nodes;
5327
5328 /*
5329 * As the map is walked, we track how much memory is usable
5330 * by the kernel using kernelcore_remaining. When it is
5331 * 0, the rest of the node is usable by ZONE_MOVABLE
5332 */
5333 kernelcore_remaining = kernelcore_node;
5334
5335 /* Go through each range of PFNs within this node */
c13291a5 5336 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
2a1e274a
MG
5337 unsigned long size_pages;
5338
c13291a5 5339 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
2a1e274a
MG
5340 if (start_pfn >= end_pfn)
5341 continue;
5342
5343 /* Account for what is only usable for kernelcore */
5344 if (start_pfn < usable_startpfn) {
5345 unsigned long kernel_pages;
5346 kernel_pages = min(end_pfn, usable_startpfn)
5347 - start_pfn;
5348
5349 kernelcore_remaining -= min(kernel_pages,
5350 kernelcore_remaining);
5351 required_kernelcore -= min(kernel_pages,
5352 required_kernelcore);
5353
5354 /* Continue if range is now fully accounted */
5355 if (end_pfn <= usable_startpfn) {
5356
5357 /*
5358 * Push zone_movable_pfn to the end so
5359 * that if we have to rebalance
5360 * kernelcore across nodes, we will
5361 * not double account here
5362 */
5363 zone_movable_pfn[nid] = end_pfn;
5364 continue;
5365 }
5366 start_pfn = usable_startpfn;
5367 }
5368
5369 /*
5370 * The usable PFN range for ZONE_MOVABLE is from
5371 * start_pfn->end_pfn. Calculate size_pages as the
5372 * number of pages used as kernelcore
5373 */
5374 size_pages = end_pfn - start_pfn;
5375 if (size_pages > kernelcore_remaining)
5376 size_pages = kernelcore_remaining;
5377 zone_movable_pfn[nid] = start_pfn + size_pages;
5378
5379 /*
5380 * Some kernelcore has been met, update counts and
5381 * break if the kernelcore for this node has been
5382 * satisified
5383 */
5384 required_kernelcore -= min(required_kernelcore,
5385 size_pages);
5386 kernelcore_remaining -= size_pages;
5387 if (!kernelcore_remaining)
5388 break;
5389 }
5390 }
5391
5392 /*
5393 * If there is still required_kernelcore, we do another pass with one
5394 * less node in the count. This will push zone_movable_pfn[nid] further
5395 * along on the nodes that still have memory until kernelcore is
5396 * satisified
5397 */
5398 usable_nodes--;
5399 if (usable_nodes && required_kernelcore > usable_nodes)
5400 goto restart;
5401
5402 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5403 for (nid = 0; nid < MAX_NUMNODES; nid++)
5404 zone_movable_pfn[nid] =
5405 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
66918dcd 5406
20e6926d 5407out:
66918dcd 5408 /* restore the node_state */
4b0ef1fe 5409 node_states[N_MEMORY] = saved_node_state;
2a1e274a
MG
5410}
5411
4b0ef1fe
LJ
5412/* Any regular or high memory on that node ? */
5413static void check_for_memory(pg_data_t *pgdat, int nid)
37b07e41 5414{
37b07e41
LS
5415 enum zone_type zone_type;
5416
4b0ef1fe
LJ
5417 if (N_MEMORY == N_NORMAL_MEMORY)
5418 return;
5419
5420 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
37b07e41 5421 struct zone *zone = &pgdat->node_zones[zone_type];
d0048b0e 5422 if (zone->present_pages) {
4b0ef1fe
LJ
5423 node_set_state(nid, N_HIGH_MEMORY);
5424 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5425 zone_type <= ZONE_NORMAL)
5426 node_set_state(nid, N_NORMAL_MEMORY);
d0048b0e
BL
5427 break;
5428 }
37b07e41 5429 }
37b07e41
LS
5430}
5431
c713216d
MG
5432/**
5433 * free_area_init_nodes - Initialise all pg_data_t and zone data
88ca3b94 5434 * @max_zone_pfn: an array of max PFNs for each zone
c713216d
MG
5435 *
5436 * This will call free_area_init_node() for each active node in the system.
5437 * Using the page ranges provided by add_active_range(), the size of each
5438 * zone in each node and their holes is calculated. If the maximum PFN
5439 * between two adjacent zones match, it is assumed that the zone is empty.
5440 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5441 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5442 * starts where the previous one ended. For example, ZONE_DMA32 starts
5443 * at arch_max_dma_pfn.
5444 */
5445void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5446{
c13291a5
TH
5447 unsigned long start_pfn, end_pfn;
5448 int i, nid;
a6af2bc3 5449
c713216d
MG
5450 /* Record where the zone boundaries are */
5451 memset(arch_zone_lowest_possible_pfn, 0,
5452 sizeof(arch_zone_lowest_possible_pfn));
5453 memset(arch_zone_highest_possible_pfn, 0,
5454 sizeof(arch_zone_highest_possible_pfn));
414989d2
OH
5455
5456 start_pfn = find_min_pfn_with_active_regions();
5457
5458 for (i = 0; i < MAX_NR_ZONES; i++) {
2a1e274a
MG
5459 if (i == ZONE_MOVABLE)
5460 continue;
414989d2
OH
5461
5462 end_pfn = max(max_zone_pfn[i], start_pfn);
5463 arch_zone_lowest_possible_pfn[i] = start_pfn;
5464 arch_zone_highest_possible_pfn[i] = end_pfn;
5465
5466 start_pfn = end_pfn;
c713216d 5467 }
2a1e274a
MG
5468 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5469 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5470
5471 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5472 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
b224ef85 5473 find_zone_movable_pfns_for_nodes();
c713216d 5474
c713216d 5475 /* Print out the zone ranges */
a62e2f4f 5476 printk("Zone ranges:\n");
2a1e274a
MG
5477 for (i = 0; i < MAX_NR_ZONES; i++) {
5478 if (i == ZONE_MOVABLE)
5479 continue;
155cbfc8 5480 printk(KERN_CONT " %-8s ", zone_names[i]);
72f0ba02
DR
5481 if (arch_zone_lowest_possible_pfn[i] ==
5482 arch_zone_highest_possible_pfn[i])
155cbfc8 5483 printk(KERN_CONT "empty\n");
72f0ba02 5484 else
a62e2f4f
BH
5485 printk(KERN_CONT "[mem %0#10lx-%0#10lx]\n",
5486 arch_zone_lowest_possible_pfn[i] << PAGE_SHIFT,
5487 (arch_zone_highest_possible_pfn[i]
5488 << PAGE_SHIFT) - 1);
2a1e274a
MG
5489 }
5490
5491 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
a62e2f4f 5492 printk("Movable zone start for each node\n");
2a1e274a
MG
5493 for (i = 0; i < MAX_NUMNODES; i++) {
5494 if (zone_movable_pfn[i])
a62e2f4f
BH
5495 printk(" Node %d: %#010lx\n", i,
5496 zone_movable_pfn[i] << PAGE_SHIFT);
2a1e274a 5497 }
c713216d 5498
f2d52fe5 5499 /* Print out the early node map */
a62e2f4f 5500 printk("Early memory node ranges\n");
c13291a5 5501 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
a62e2f4f
BH
5502 printk(" node %3d: [mem %#010lx-%#010lx]\n", nid,
5503 start_pfn << PAGE_SHIFT, (end_pfn << PAGE_SHIFT) - 1);
c713216d
MG
5504
5505 /* Initialise every node */
708614e6 5506 mminit_verify_pageflags_layout();
8ef82866 5507 setup_nr_node_ids();
c713216d
MG
5508 for_each_online_node(nid) {
5509 pg_data_t *pgdat = NODE_DATA(nid);
9109fb7b 5510 free_area_init_node(nid, NULL,
c713216d 5511 find_min_pfn_for_node(nid), NULL);
37b07e41
LS
5512
5513 /* Any memory on that node */
5514 if (pgdat->node_present_pages)
4b0ef1fe
LJ
5515 node_set_state(nid, N_MEMORY);
5516 check_for_memory(pgdat, nid);
c713216d
MG
5517 }
5518}
2a1e274a 5519
7e63efef 5520static int __init cmdline_parse_core(char *p, unsigned long *core)
2a1e274a
MG
5521{
5522 unsigned long long coremem;
5523 if (!p)
5524 return -EINVAL;
5525
5526 coremem = memparse(p, &p);
7e63efef 5527 *core = coremem >> PAGE_SHIFT;
2a1e274a 5528
7e63efef 5529 /* Paranoid check that UL is enough for the coremem value */
2a1e274a
MG
5530 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5531
5532 return 0;
5533}
ed7ed365 5534
7e63efef
MG
5535/*
5536 * kernelcore=size sets the amount of memory for use for allocations that
5537 * cannot be reclaimed or migrated.
5538 */
5539static int __init cmdline_parse_kernelcore(char *p)
5540{
5541 return cmdline_parse_core(p, &required_kernelcore);
5542}
5543
5544/*
5545 * movablecore=size sets the amount of memory for use for allocations that
5546 * can be reclaimed or migrated.
5547 */
5548static int __init cmdline_parse_movablecore(char *p)
5549{
5550 return cmdline_parse_core(p, &required_movablecore);
5551}
5552
ed7ed365 5553early_param("kernelcore", cmdline_parse_kernelcore);
7e63efef 5554early_param("movablecore", cmdline_parse_movablecore);
ed7ed365 5555
0ee332c1 5556#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
c713216d 5557
69afade7
JL
5558unsigned long free_reserved_area(unsigned long start, unsigned long end,
5559 int poison, char *s)
5560{
5561 unsigned long pages, pos;
5562
5563 pos = start = PAGE_ALIGN(start);
5564 end &= PAGE_MASK;
5565 for (pages = 0; pos < end; pos += PAGE_SIZE, pages++) {
5566 if (poison)
5567 memset((void *)pos, poison, PAGE_SIZE);
bb3ec6b0 5568 free_reserved_page(virt_to_page((void *)pos));
69afade7
JL
5569 }
5570
5571 if (pages && s)
7c11e178
JP
5572 pr_info("Freeing %s memory: %ldK\n",
5573 s, pages << (PAGE_SHIFT - 10));
69afade7
JL
5574
5575 return pages;
5576}
5577
cfa11e08
JL
5578#ifdef CONFIG_HIGHMEM
5579void free_highmem_page(struct page *page)
5580{
5581 __free_reserved_page(page);
5582 totalram_pages++;
5583 totalhigh_pages++;
5584}
5585#endif
5586
0e0b864e 5587/**
88ca3b94
RD
5588 * set_dma_reserve - set the specified number of pages reserved in the first zone
5589 * @new_dma_reserve: The number of pages to mark reserved
0e0b864e
MG
5590 *
5591 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5592 * In the DMA zone, a significant percentage may be consumed by kernel image
5593 * and other unfreeable allocations which can skew the watermarks badly. This
88ca3b94
RD
5594 * function may optionally be used to account for unfreeable pages in the
5595 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5596 * smaller per-cpu batchsize.
0e0b864e
MG
5597 */
5598void __init set_dma_reserve(unsigned long new_dma_reserve)
5599{
5600 dma_reserve = new_dma_reserve;
5601}
5602
1da177e4
LT
5603void __init free_area_init(unsigned long *zones_size)
5604{
9109fb7b 5605 free_area_init_node(0, zones_size,
1da177e4
LT
5606 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5607}
1da177e4 5608
1da177e4
LT
5609static int page_alloc_cpu_notify(struct notifier_block *self,
5610 unsigned long action, void *hcpu)
5611{
5612 int cpu = (unsigned long)hcpu;
1da177e4 5613
8bb78442 5614 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
f0cb3c76 5615 lru_add_drain_cpu(cpu);
9f8f2172
CL
5616 drain_pages(cpu);
5617
5618 /*
5619 * Spill the event counters of the dead processor
5620 * into the current processors event counters.
5621 * This artificially elevates the count of the current
5622 * processor.
5623 */
f8891e5e 5624 vm_events_fold_cpu(cpu);
9f8f2172
CL
5625
5626 /*
5627 * Zero the differential counters of the dead processor
5628 * so that the vm statistics are consistent.
5629 *
5630 * This is only okay since the processor is dead and cannot
5631 * race with what we are doing.
5632 */
2244b95a 5633 refresh_cpu_vm_stats(cpu);
1da177e4
LT
5634 }
5635 return NOTIFY_OK;
5636}
1da177e4
LT
5637
5638void __init page_alloc_init(void)
5639{
5640 hotcpu_notifier(page_alloc_cpu_notify, 0);
5641}
5642
cb45b0e9
HA
5643/*
5644 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5645 * or min_free_kbytes changes.
5646 */
5647static void calculate_totalreserve_pages(void)
5648{
5649 struct pglist_data *pgdat;
5650 unsigned long reserve_pages = 0;
2f6726e5 5651 enum zone_type i, j;
cb45b0e9
HA
5652
5653 for_each_online_pgdat(pgdat) {
5654 for (i = 0; i < MAX_NR_ZONES; i++) {
5655 struct zone *zone = pgdat->node_zones + i;
5656 unsigned long max = 0;
5657
5658 /* Find valid and maximum lowmem_reserve in the zone */
5659 for (j = i; j < MAX_NR_ZONES; j++) {
5660 if (zone->lowmem_reserve[j] > max)
5661 max = zone->lowmem_reserve[j];
5662 }
5663
41858966
MG
5664 /* we treat the high watermark as reserved pages. */
5665 max += high_wmark_pages(zone);
cb45b0e9 5666
b40da049
JL
5667 if (max > zone->managed_pages)
5668 max = zone->managed_pages;
cb45b0e9 5669 reserve_pages += max;
ab8fabd4
JW
5670 /*
5671 * Lowmem reserves are not available to
5672 * GFP_HIGHUSER page cache allocations and
5673 * kswapd tries to balance zones to their high
5674 * watermark. As a result, neither should be
5675 * regarded as dirtyable memory, to prevent a
5676 * situation where reclaim has to clean pages
5677 * in order to balance the zones.
5678 */
5679 zone->dirty_balance_reserve = max;
cb45b0e9
HA
5680 }
5681 }
ab8fabd4 5682 dirty_balance_reserve = reserve_pages;
cb45b0e9
HA
5683 totalreserve_pages = reserve_pages;
5684}
5685
1da177e4
LT
5686/*
5687 * setup_per_zone_lowmem_reserve - called whenever
5688 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5689 * has a correct pages reserved value, so an adequate number of
5690 * pages are left in the zone after a successful __alloc_pages().
5691 */
5692static void setup_per_zone_lowmem_reserve(void)
5693{
5694 struct pglist_data *pgdat;
2f6726e5 5695 enum zone_type j, idx;
1da177e4 5696
ec936fc5 5697 for_each_online_pgdat(pgdat) {
1da177e4
LT
5698 for (j = 0; j < MAX_NR_ZONES; j++) {
5699 struct zone *zone = pgdat->node_zones + j;
b40da049 5700 unsigned long managed_pages = zone->managed_pages;
1da177e4
LT
5701
5702 zone->lowmem_reserve[j] = 0;
5703
2f6726e5
CL
5704 idx = j;
5705 while (idx) {
1da177e4
LT
5706 struct zone *lower_zone;
5707
2f6726e5
CL
5708 idx--;
5709
1da177e4
LT
5710 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5711 sysctl_lowmem_reserve_ratio[idx] = 1;
5712
5713 lower_zone = pgdat->node_zones + idx;
b40da049 5714 lower_zone->lowmem_reserve[j] = managed_pages /
1da177e4 5715 sysctl_lowmem_reserve_ratio[idx];
b40da049 5716 managed_pages += lower_zone->managed_pages;
1da177e4
LT
5717 }
5718 }
5719 }
cb45b0e9
HA
5720
5721 /* update totalreserve_pages */
5722 calculate_totalreserve_pages();
1da177e4
LT
5723}
5724
cfd3da1e 5725static void __setup_per_zone_wmarks(void)
1da177e4
LT
5726{
5727 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6fa3eb70 5728 unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
1da177e4
LT
5729 unsigned long lowmem_pages = 0;
5730 struct zone *zone;
5731 unsigned long flags;
5732
5733 /* Calculate total number of !ZONE_HIGHMEM pages */
5734 for_each_zone(zone) {
5735 if (!is_highmem(zone))
b40da049 5736 lowmem_pages += zone->managed_pages;
1da177e4
LT
5737 }
5738
5739 for_each_zone(zone) {
6fa3eb70 5740 u64 min, low;
ac924c60 5741
1125b4e3 5742 spin_lock_irqsave(&zone->lock, flags);
6fa3eb70
S
5743 min = (u64)pages_min * zone->managed_pages;
5744 do_div(min, lowmem_pages);
5745 low = (u64)pages_low * zone->managed_pages;
5746 do_div(low, vm_total_pages);
5747
1da177e4
LT
5748 if (is_highmem(zone)) {
5749 /*
669ed175
NP
5750 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5751 * need highmem pages, so cap pages_min to a small
5752 * value here.
5753 *
41858966 5754 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
669ed175
NP
5755 * deltas controls asynch page reclaim, and so should
5756 * not be capped for highmem.
1da177e4 5757 */
90ae8d67 5758 unsigned long min_pages;
1da177e4 5759
b40da049 5760 min_pages = zone->managed_pages / 1024;
90ae8d67 5761 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
41858966 5762 zone->watermark[WMARK_MIN] = min_pages;
1da177e4 5763 } else {
669ed175
NP
5764 /*
5765 * If it's a lowmem zone, reserve a number of pages
1da177e4
LT
5766 * proportionate to the zone's size.
5767 */
6fa3eb70 5768 zone->watermark[WMARK_MIN] = min;
1da177e4
LT
5769 }
5770
6fa3eb70
S
5771 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) +
5772 low + (min >> 2);
5773 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) +
5774 low + (min >> 1);
49f223a9 5775
56fd56b8 5776 setup_zone_migrate_reserve(zone);
1125b4e3 5777 spin_unlock_irqrestore(&zone->lock, flags);
1da177e4 5778 }
cb45b0e9
HA
5779
5780 /* update totalreserve_pages */
5781 calculate_totalreserve_pages();
1da177e4
LT
5782}
5783
cfd3da1e
MG
5784/**
5785 * setup_per_zone_wmarks - called when min_free_kbytes changes
5786 * or when memory is hot-{added|removed}
5787 *
5788 * Ensures that the watermark[min,low,high] values for each zone are set
5789 * correctly with respect to min_free_kbytes.
5790 */
5791void setup_per_zone_wmarks(void)
5792{
5793 mutex_lock(&zonelists_mutex);
5794 __setup_per_zone_wmarks();
5795 mutex_unlock(&zonelists_mutex);
5796}
5797
55a4462a 5798/*
556adecb
RR
5799 * The inactive anon list should be small enough that the VM never has to
5800 * do too much work, but large enough that each inactive page has a chance
5801 * to be referenced again before it is swapped out.
5802 *
5803 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5804 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5805 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5806 * the anonymous pages are kept on the inactive list.
5807 *
5808 * total target max
5809 * memory ratio inactive anon
5810 * -------------------------------------
5811 * 10MB 1 5MB
5812 * 100MB 1 50MB
5813 * 1GB 3 250MB
5814 * 10GB 10 0.9GB
5815 * 100GB 31 3GB
5816 * 1TB 101 10GB
5817 * 10TB 320 32GB
5818 */
1b79acc9 5819static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
556adecb 5820{
96cb4df5 5821 unsigned int gb, ratio;
556adecb 5822
96cb4df5 5823 /* Zone size in gigabytes */
b40da049 5824 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
96cb4df5 5825 if (gb)
556adecb 5826 ratio = int_sqrt(10 * gb);
96cb4df5
MK
5827 else
5828 ratio = 1;
556adecb 5829
96cb4df5
MK
5830 zone->inactive_ratio = ratio;
5831}
556adecb 5832
839a4fcc 5833static void __meminit setup_per_zone_inactive_ratio(void)
96cb4df5
MK
5834{
5835 struct zone *zone;
5836
5837 for_each_zone(zone)
5838 calculate_zone_inactive_ratio(zone);
556adecb
RR
5839}
5840
1da177e4
LT
5841/*
5842 * Initialise min_free_kbytes.
5843 *
5844 * For small machines we want it small (128k min). For large machines
5845 * we want it large (64MB max). But it is not linear, because network
5846 * bandwidth does not increase linearly with machine size. We use
5847 *
5848 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5849 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5850 *
5851 * which yields
5852 *
5853 * 16MB: 512k
5854 * 32MB: 724k
5855 * 64MB: 1024k
5856 * 128MB: 1448k
5857 * 256MB: 2048k
5858 * 512MB: 2896k
5859 * 1024MB: 4096k
5860 * 2048MB: 5792k
5861 * 4096MB: 8192k
5862 * 8192MB: 11584k
5863 * 16384MB: 16384k
5864 */
1b79acc9 5865int __meminit init_per_zone_wmark_min(void)
1da177e4
LT
5866{
5867 unsigned long lowmem_kbytes;
5868
5869 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5870
5871 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5872 if (min_free_kbytes < 128)
5873 min_free_kbytes = 128;
5874 if (min_free_kbytes > 65536)
5875 min_free_kbytes = 65536;
bc75d33f 5876 setup_per_zone_wmarks();
a6cccdc3 5877 refresh_zone_stat_thresholds();
1da177e4 5878 setup_per_zone_lowmem_reserve();
556adecb 5879 setup_per_zone_inactive_ratio();
1da177e4
LT
5880 return 0;
5881}
bc75d33f 5882module_init(init_per_zone_wmark_min)
1da177e4
LT
5883
5884/*
5885 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5886 * that we can call two helper functions whenever min_free_kbytes
6fa3eb70 5887 * or extra_free_kbytes changes.
1da177e4
LT
5888 */
5889int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
8d65af78 5890 void __user *buffer, size_t *length, loff_t *ppos)
1da177e4 5891{
8d65af78 5892 proc_dointvec(table, write, buffer, length, ppos);
3b1d92c5 5893 if (write)
bc75d33f 5894 setup_per_zone_wmarks();
1da177e4
LT
5895 return 0;
5896}
5897
9614634f
CL
5898#ifdef CONFIG_NUMA
5899int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5900 void __user *buffer, size_t *length, loff_t *ppos)
9614634f
CL
5901{
5902 struct zone *zone;
5903 int rc;
5904
8d65af78 5905 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
9614634f
CL
5906 if (rc)
5907 return rc;
5908
5909 for_each_zone(zone)
b40da049 5910 zone->min_unmapped_pages = (zone->managed_pages *
9614634f
CL
5911 sysctl_min_unmapped_ratio) / 100;
5912 return 0;
5913}
0ff38490
CL
5914
5915int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5916 void __user *buffer, size_t *length, loff_t *ppos)
0ff38490
CL
5917{
5918 struct zone *zone;
5919 int rc;
5920
8d65af78 5921 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
0ff38490
CL
5922 if (rc)
5923 return rc;
5924
5925 for_each_zone(zone)
b40da049 5926 zone->min_slab_pages = (zone->managed_pages *
0ff38490
CL
5927 sysctl_min_slab_ratio) / 100;
5928 return 0;
5929}
9614634f
CL
5930#endif
5931
1da177e4
LT
5932/*
5933 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5934 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5935 * whenever sysctl_lowmem_reserve_ratio changes.
5936 *
5937 * The reserve ratio obviously has absolutely no relation with the
41858966 5938 * minimum watermarks. The lowmem reserve ratio can only make sense
1da177e4
LT
5939 * if in function of the boot time zone sizes.
5940 */
5941int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
8d65af78 5942 void __user *buffer, size_t *length, loff_t *ppos)
1da177e4 5943{
8d65af78 5944 proc_dointvec_minmax(table, write, buffer, length, ppos);
1da177e4
LT
5945 setup_per_zone_lowmem_reserve();
5946 return 0;
5947}
5948
8ad4b1fb
RS
5949/*
5950 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5951 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
5952 * can have before it gets flushed back to buddy allocator.
5953 */
5954
5955int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
8d65af78 5956 void __user *buffer, size_t *length, loff_t *ppos)
8ad4b1fb
RS
5957{
5958 struct zone *zone;
5959 unsigned int cpu;
5960 int ret;
5961
8d65af78 5962 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
93278814 5963 if (!write || (ret < 0))
8ad4b1fb 5964 return ret;
364df0eb 5965 for_each_populated_zone(zone) {
99dcc3e5 5966 for_each_possible_cpu(cpu) {
8ad4b1fb 5967 unsigned long high;
b40da049 5968 high = zone->managed_pages / percpu_pagelist_fraction;
99dcc3e5
CL
5969 setup_pagelist_highmark(
5970 per_cpu_ptr(zone->pageset, cpu), high);
8ad4b1fb
RS
5971 }
5972 }
5973 return 0;
5974}
5975
f034b5d4 5976int hashdist = HASHDIST_DEFAULT;
1da177e4
LT
5977
5978#ifdef CONFIG_NUMA
5979static int __init set_hashdist(char *str)
5980{
5981 if (!str)
5982 return 0;
5983 hashdist = simple_strtoul(str, &str, 0);
5984 return 1;
5985}
5986__setup("hashdist=", set_hashdist);
5987#endif
5988
5989/*
5990 * allocate a large system hash table from bootmem
5991 * - it is assumed that the hash table must contain an exact power-of-2
5992 * quantity of entries
5993 * - limit is the number of hash buckets, not the total allocation size
5994 */
5995void *__init alloc_large_system_hash(const char *tablename,
5996 unsigned long bucketsize,
5997 unsigned long numentries,
5998 int scale,
5999 int flags,
6000 unsigned int *_hash_shift,
6001 unsigned int *_hash_mask,
31fe62b9
TB
6002 unsigned long low_limit,
6003 unsigned long high_limit)
1da177e4 6004{
31fe62b9 6005 unsigned long long max = high_limit;
1da177e4
LT
6006 unsigned long log2qty, size;
6007 void *table = NULL;
6008
6009 /* allow the kernel cmdline to have a say */
6010 if (!numentries) {
6011 /* round applicable memory size up to nearest megabyte */
04903664 6012 numentries = nr_kernel_pages;
1da177e4
LT
6013 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
6014 numentries >>= 20 - PAGE_SHIFT;
6015 numentries <<= 20 - PAGE_SHIFT;
6016
6017 /* limit to 1 bucket per 2^scale bytes of low memory */
6018 if (scale > PAGE_SHIFT)
6019 numentries >>= (scale - PAGE_SHIFT);
6020 else
6021 numentries <<= (PAGE_SHIFT - scale);
9ab37b8f
PM
6022
6023 /* Make sure we've got at least a 0-order allocation.. */
2c85f51d
JB
6024 if (unlikely(flags & HASH_SMALL)) {
6025 /* Makes no sense without HASH_EARLY */
6026 WARN_ON(!(flags & HASH_EARLY));
6027 if (!(numentries >> *_hash_shift)) {
6028 numentries = 1UL << *_hash_shift;
6029 BUG_ON(!numentries);
6030 }
6031 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
9ab37b8f 6032 numentries = PAGE_SIZE / bucketsize;
1da177e4 6033 }
6e692ed3 6034 numentries = roundup_pow_of_two(numentries);
1da177e4
LT
6035
6036 /* limit allocation size to 1/16 total memory by default */
6037 if (max == 0) {
6038 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6039 do_div(max, bucketsize);
6040 }
074b8517 6041 max = min(max, 0x80000000ULL);
1da177e4 6042
31fe62b9
TB
6043 if (numentries < low_limit)
6044 numentries = low_limit;
1da177e4
LT
6045 if (numentries > max)
6046 numentries = max;
6047
f0d1b0b3 6048 log2qty = ilog2(numentries);
1da177e4
LT
6049
6050 do {
6051 size = bucketsize << log2qty;
6052 if (flags & HASH_EARLY)
74768ed8 6053 table = alloc_bootmem_nopanic(size);
1da177e4
LT
6054 else if (hashdist)
6055 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6056 else {
1037b83b
ED
6057 /*
6058 * If bucketsize is not a power-of-two, we may free
a1dd268c
MG
6059 * some pages at the end of hash table which
6060 * alloc_pages_exact() automatically does
1037b83b 6061 */
264ef8a9 6062 if (get_order(size) < MAX_ORDER) {
a1dd268c 6063 table = alloc_pages_exact(size, GFP_ATOMIC);
264ef8a9
CM
6064 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6065 }
1da177e4
LT
6066 }
6067 } while (!table && size > PAGE_SIZE && --log2qty);
6068
6069 if (!table)
6070 panic("Failed to allocate %s hash table\n", tablename);
6071
f241e660 6072 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
1da177e4 6073 tablename,
f241e660 6074 (1UL << log2qty),
f0d1b0b3 6075 ilog2(size) - PAGE_SHIFT,
1da177e4
LT
6076 size);
6077
6078 if (_hash_shift)
6079 *_hash_shift = log2qty;
6080 if (_hash_mask)
6081 *_hash_mask = (1 << log2qty) - 1;
6082
6083 return table;
6084}
a117e66e 6085
835c134e
MG
6086/* Return a pointer to the bitmap storing bits affecting a block of pages */
6087static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6088 unsigned long pfn)
6089{
6090#ifdef CONFIG_SPARSEMEM
6091 return __pfn_to_section(pfn)->pageblock_flags;
6092#else
6093 return zone->pageblock_flags;
6094#endif /* CONFIG_SPARSEMEM */
6095}
6096
6097static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6098{
6099#ifdef CONFIG_SPARSEMEM
6100 pfn &= (PAGES_PER_SECTION-1);
d9c23400 6101 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
835c134e 6102#else
c060f943 6103 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
d9c23400 6104 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
835c134e
MG
6105#endif /* CONFIG_SPARSEMEM */
6106}
6107
6108/**
d9c23400 6109 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
835c134e
MG
6110 * @page: The page within the block of interest
6111 * @start_bitidx: The first bit of interest to retrieve
6112 * @end_bitidx: The last bit of interest
6113 * returns pageblock_bits flags
6114 */
6115unsigned long get_pageblock_flags_group(struct page *page,
6116 int start_bitidx, int end_bitidx)
6117{
6118 struct zone *zone;
6119 unsigned long *bitmap;
6120 unsigned long pfn, bitidx;
6121 unsigned long flags = 0;
6122 unsigned long value = 1;
6123
6124 zone = page_zone(page);
6125 pfn = page_to_pfn(page);
6126 bitmap = get_pageblock_bitmap(zone, pfn);
6127 bitidx = pfn_to_bitidx(zone, pfn);
6128
6129 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
6130 if (test_bit(bitidx + start_bitidx, bitmap))
6131 flags |= value;
6220ec78 6132
835c134e
MG
6133 return flags;
6134}
6135
6136/**
d9c23400 6137 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
835c134e
MG
6138 * @page: The page within the block of interest
6139 * @start_bitidx: The first bit of interest
6140 * @end_bitidx: The last bit of interest
6141 * @flags: The flags to set
6142 */
6143void set_pageblock_flags_group(struct page *page, unsigned long flags,
6144 int start_bitidx, int end_bitidx)
6145{
6146 struct zone *zone;
6147 unsigned long *bitmap;
6148 unsigned long pfn, bitidx;
6149 unsigned long value = 1;
6150
6151 zone = page_zone(page);
6152 pfn = page_to_pfn(page);
6153 bitmap = get_pageblock_bitmap(zone, pfn);
6154 bitidx = pfn_to_bitidx(zone, pfn);
108bcc96 6155 VM_BUG_ON(!zone_spans_pfn(zone, pfn));
835c134e
MG
6156
6157 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
6158 if (flags & value)
6159 __set_bit(bitidx + start_bitidx, bitmap);
6160 else
6161 __clear_bit(bitidx + start_bitidx, bitmap);
6162}
a5d76b54
KH
6163
6164/*
80934513
MK
6165 * This function checks whether pageblock includes unmovable pages or not.
6166 * If @count is not zero, it is okay to include less @count unmovable pages
6167 *
6168 * PageLRU check wihtout isolation or lru_lock could race so that
6169 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6170 * expect this function should be exact.
a5d76b54 6171 */
b023f468
WC
6172bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6173 bool skip_hwpoisoned_pages)
49ac8255
KH
6174{
6175 unsigned long pfn, iter, found;
47118af0
MN
6176 int mt;
6177
49ac8255
KH
6178 /*
6179 * For avoiding noise data, lru_add_drain_all() should be called
80934513 6180 * If ZONE_MOVABLE, the zone never contains unmovable pages
49ac8255
KH
6181 */
6182 if (zone_idx(zone) == ZONE_MOVABLE)
80934513 6183 return false;
47118af0
MN
6184 mt = get_pageblock_migratetype(page);
6185 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
80934513 6186 return false;
49ac8255
KH
6187
6188 pfn = page_to_pfn(page);
6189 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6190 unsigned long check = pfn + iter;
6191
29723fcc 6192 if (!pfn_valid_within(check))
49ac8255 6193 continue;
29723fcc 6194
49ac8255 6195 page = pfn_to_page(check);
97d255c8
MK
6196 /*
6197 * We can't use page_count without pin a page
6198 * because another CPU can free compound page.
6199 * This check already skips compound tails of THP
6200 * because their page->_count is zero at all time.
6201 */
6202 if (!atomic_read(&page->_count)) {
49ac8255
KH
6203 if (PageBuddy(page))
6204 iter += (1 << page_order(page)) - 1;
6205 continue;
6206 }
97d255c8 6207
b023f468
WC
6208 /*
6209 * The HWPoisoned page may be not in buddy system, and
6210 * page_count() is not 0.
6211 */
6212 if (skip_hwpoisoned_pages && PageHWPoison(page))
6213 continue;
6214
49ac8255
KH
6215 if (!PageLRU(page))
6216 found++;
6217 /*
6218 * If there are RECLAIMABLE pages, we need to check it.
6219 * But now, memory offline itself doesn't call shrink_slab()
6220 * and it still to be fixed.
6221 */
6222 /*
6223 * If the page is not RAM, page_count()should be 0.
6224 * we don't need more check. This is an _used_ not-movable page.
6225 *
6226 * The problematic thing here is PG_reserved pages. PG_reserved
6227 * is set to both of a memory hole page and a _used_ kernel
6228 * page at boot.
6229 */
6230 if (found > count)
80934513 6231 return true;
49ac8255 6232 }
80934513 6233 return false;
49ac8255
KH
6234}
6235
6236bool is_pageblock_removable_nolock(struct page *page)
6237{
656a0706
MH
6238 struct zone *zone;
6239 unsigned long pfn;
687875fb
MH
6240
6241 /*
6242 * We have to be careful here because we are iterating over memory
6243 * sections which are not zone aware so we might end up outside of
6244 * the zone but still within the section.
656a0706
MH
6245 * We have to take care about the node as well. If the node is offline
6246 * its NODE_DATA will be NULL - see page_zone.
687875fb 6247 */
656a0706
MH
6248 if (!node_online(page_to_nid(page)))
6249 return false;
6250
6251 zone = page_zone(page);
6252 pfn = page_to_pfn(page);
108bcc96 6253 if (!zone_spans_pfn(zone, pfn))
687875fb
MH
6254 return false;
6255
b023f468 6256 return !has_unmovable_pages(zone, page, 0, true);
a5d76b54 6257}
0c0e6195 6258
041d3a8c
MN
6259#ifdef CONFIG_CMA
6260
6261static unsigned long pfn_max_align_down(unsigned long pfn)
6262{
6263 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6264 pageblock_nr_pages) - 1);
6265}
6266
6267static unsigned long pfn_max_align_up(unsigned long pfn)
6268{
6269 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6270 pageblock_nr_pages));
6271}
6272
041d3a8c 6273/* [start, end) must belong to a single zone. */
bb13ffeb
MG
6274static int __alloc_contig_migrate_range(struct compact_control *cc,
6275 unsigned long start, unsigned long end)
041d3a8c
MN
6276{
6277 /* This function is based on compact_zone() from compaction.c. */
beb51eaa 6278 unsigned long nr_reclaimed;
041d3a8c
MN
6279 unsigned long pfn = start;
6280 unsigned int tries = 0;
6281 int ret = 0;
6282
be49a6e1 6283 migrate_prep();
041d3a8c 6284
bb13ffeb 6285 while (pfn < end || !list_empty(&cc->migratepages)) {
041d3a8c
MN
6286 if (fatal_signal_pending(current)) {
6287 ret = -EINTR;
6288 break;
6289 }
6290
bb13ffeb
MG
6291 if (list_empty(&cc->migratepages)) {
6292 cc->nr_migratepages = 0;
6293 pfn = isolate_migratepages_range(cc->zone, cc,
e46a2879 6294 pfn, end, true);
041d3a8c
MN
6295 if (!pfn) {
6296 ret = -EINTR;
6297 break;
6298 }
6299 tries = 0;
6300 } else if (++tries == 5) {
6301 ret = ret < 0 ? ret : -EBUSY;
6302 break;
6303 }
6304
beb51eaa
MK
6305 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6306 &cc->migratepages);
6307 cc->nr_migratepages -= nr_reclaimed;
02c6de8d 6308
9c620e2b
HD
6309 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6310 0, MIGRATE_SYNC, MR_CMA);
041d3a8c 6311 }
2a6f5124
SP
6312 if (ret < 0) {
6313 putback_movable_pages(&cc->migratepages);
6314 return ret;
6315 }
6316 return 0;
041d3a8c
MN
6317}
6318
6319/**
6320 * alloc_contig_range() -- tries to allocate given range of pages
6321 * @start: start PFN to allocate
6322 * @end: one-past-the-last PFN to allocate
0815f3d8
MN
6323 * @migratetype: migratetype of the underlaying pageblocks (either
6324 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6325 * in range must have the same migratetype and it must
6326 * be either of the two.
041d3a8c
MN
6327 *
6328 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6329 * aligned, however it's the caller's responsibility to guarantee that
6330 * we are the only thread that changes migrate type of pageblocks the
6331 * pages fall in.
6332 *
6333 * The PFN range must belong to a single zone.
6334 *
6335 * Returns zero on success or negative error code. On success all
6336 * pages which PFN is in [start, end) are allocated for the caller and
6337 * need to be freed with free_contig_range().
6338 */
0815f3d8
MN
6339int alloc_contig_range(unsigned long start, unsigned long end,
6340 unsigned migratetype)
041d3a8c 6341{
041d3a8c
MN
6342 unsigned long outer_start, outer_end;
6343 int ret = 0, order;
6344
bb13ffeb
MG
6345 struct compact_control cc = {
6346 .nr_migratepages = 0,
6347 .order = -1,
6348 .zone = page_zone(pfn_to_page(start)),
6349 .sync = true,
6350 .ignore_skip_hint = true,
6351 };
6352 INIT_LIST_HEAD(&cc.migratepages);
6353
041d3a8c
MN
6354 /*
6355 * What we do here is we mark all pageblocks in range as
6356 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6357 * have different sizes, and due to the way page allocator
6358 * work, we align the range to biggest of the two pages so
6359 * that page allocator won't try to merge buddies from
6360 * different pageblocks and change MIGRATE_ISOLATE to some
6361 * other migration type.
6362 *
6363 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6364 * migrate the pages from an unaligned range (ie. pages that
6365 * we are interested in). This will put all the pages in
6366 * range back to page allocator as MIGRATE_ISOLATE.
6367 *
6368 * When this is done, we take the pages in range from page
6369 * allocator removing them from the buddy system. This way
6370 * page allocator will never consider using them.
6371 *
6372 * This lets us mark the pageblocks back as
6373 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6374 * aligned range but not in the unaligned, original range are
6375 * put back to page allocator so that buddy can use them.
6376 */
6377
6378 ret = start_isolate_page_range(pfn_max_align_down(start),
b023f468
WC
6379 pfn_max_align_up(end), migratetype,
6380 false);
041d3a8c 6381 if (ret)
86a595f9 6382 return ret;
041d3a8c 6383
bb13ffeb 6384 ret = __alloc_contig_migrate_range(&cc, start, end);
041d3a8c
MN
6385 if (ret)
6386 goto done;
6387
6388 /*
6389 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6390 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6391 * more, all pages in [start, end) are free in page allocator.
6392 * What we are going to do is to allocate all pages from
6393 * [start, end) (that is remove them from page allocator).
6394 *
6395 * The only problem is that pages at the beginning and at the
6396 * end of interesting range may be not aligned with pages that
6397 * page allocator holds, ie. they can be part of higher order
6398 * pages. Because of this, we reserve the bigger range and
6399 * once this is done free the pages we are not interested in.
6400 *
6401 * We don't have to hold zone->lock here because the pages are
6402 * isolated thus they won't get removed from buddy.
6403 */
6404
6405 lru_add_drain_all();
6406 drain_all_pages();
6407
6408 order = 0;
6409 outer_start = start;
6410 while (!PageBuddy(pfn_to_page(outer_start))) {
6411 if (++order >= MAX_ORDER) {
6412 ret = -EBUSY;
6413 goto done;
6414 }
6415 outer_start &= ~0UL << order;
6416 }
6417
6418 /* Make sure the range is really isolated. */
b023f468 6419 if (test_pages_isolated(outer_start, end, false)) {
041d3a8c
MN
6420 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6421 outer_start, end);
6422 ret = -EBUSY;
6423 goto done;
6424 }
6425
49f223a9
MS
6426
6427 /* Grab isolated pages from freelists. */
bb13ffeb 6428 outer_end = isolate_freepages_range(&cc, outer_start, end);
041d3a8c
MN
6429 if (!outer_end) {
6430 ret = -EBUSY;
6431 goto done;
6432 }
6433
6434 /* Free head and tail (if any) */
6435 if (start != outer_start)
6436 free_contig_range(outer_start, start - outer_start);
6437 if (end != outer_end)
6438 free_contig_range(end, outer_end - end);
6439
6440done:
6441 undo_isolate_page_range(pfn_max_align_down(start),
0815f3d8 6442 pfn_max_align_up(end), migratetype);
041d3a8c
MN
6443 return ret;
6444}
6445
6446void free_contig_range(unsigned long pfn, unsigned nr_pages)
6447{
bcc2b02f
MS
6448 unsigned int count = 0;
6449
6450 for (; nr_pages--; pfn++) {
6451 struct page *page = pfn_to_page(pfn);
6452
6453 count += page_count(page) != 1;
6454 __free_page(page);
6455 }
6456 WARN(count != 0, "%d pages are still in use!\n", count);
041d3a8c
MN
6457}
6458#endif
6459
4ed7e022
JL
6460#ifdef CONFIG_MEMORY_HOTPLUG
6461static int __meminit __zone_pcp_update(void *data)
6462{
6463 struct zone *zone = data;
6464 int cpu;
6465 unsigned long batch = zone_batchsize(zone), flags;
6466
6467 for_each_possible_cpu(cpu) {
6468 struct per_cpu_pageset *pset;
6469 struct per_cpu_pages *pcp;
6470
6471 pset = per_cpu_ptr(zone->pageset, cpu);
6472 pcp = &pset->pcp;
6473
6474 local_irq_save(flags);
6475 if (pcp->count > 0)
6476 free_pcppages_bulk(zone, pcp->count, pcp);
5a883813 6477 drain_zonestat(zone, pset);
4ed7e022
JL
6478 setup_pageset(pset, batch);
6479 local_irq_restore(flags);
6480 }
6481 return 0;
6482}
6483
6484void __meminit zone_pcp_update(struct zone *zone)
6485{
6486 stop_machine(__zone_pcp_update, zone, NULL);
6487}
6488#endif
6489
340175b7
JL
6490void zone_pcp_reset(struct zone *zone)
6491{
6492 unsigned long flags;
5a883813
MK
6493 int cpu;
6494 struct per_cpu_pageset *pset;
340175b7
JL
6495
6496 /* avoid races with drain_pages() */
6497 local_irq_save(flags);
6498 if (zone->pageset != &boot_pageset) {
5a883813
MK
6499 for_each_online_cpu(cpu) {
6500 pset = per_cpu_ptr(zone->pageset, cpu);
6501 drain_zonestat(zone, pset);
6502 }
340175b7
JL
6503 free_percpu(zone->pageset);
6504 zone->pageset = &boot_pageset;
6505 }
6506 local_irq_restore(flags);
6507}
6508
6dcd73d7 6509#ifdef CONFIG_MEMORY_HOTREMOVE
0c0e6195
KH
6510/*
6511 * All pages in the range must be isolated before calling this.
6512 */
6513void
6514__offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6515{
6516 struct page *page;
6517 struct zone *zone;
6518 int order, i;
6519 unsigned long pfn;
6520 unsigned long flags;
6521 /* find the first valid pfn */
6522 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6523 if (pfn_valid(pfn))
6524 break;
6525 if (pfn == end_pfn)
6526 return;
6527 zone = page_zone(pfn_to_page(pfn));
6528 spin_lock_irqsave(&zone->lock, flags);
6529 pfn = start_pfn;
6530 while (pfn < end_pfn) {
6531 if (!pfn_valid(pfn)) {
6532 pfn++;
6533 continue;
6534 }
6535 page = pfn_to_page(pfn);
b023f468
WC
6536 /*
6537 * The HWPoisoned page may be not in buddy system, and
6538 * page_count() is not 0.
6539 */
6540 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6541 pfn++;
6542 SetPageReserved(page);
6543 continue;
6544 }
6545
0c0e6195
KH
6546 BUG_ON(page_count(page));
6547 BUG_ON(!PageBuddy(page));
6548 order = page_order(page);
6549#ifdef CONFIG_DEBUG_VM
6550 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6551 pfn, 1 << order, end_pfn);
6552#endif
6553 list_del(&page->lru);
6554 rmv_page_order(page);
6555 zone->free_area[order].nr_free--;
76422578
WL
6556#ifdef CONFIG_HIGHMEM
6557 if (PageHighMem(page))
6558 totalhigh_pages -= 1 << order;
6559#endif
0c0e6195
KH
6560 for (i = 0; i < (1 << order); i++)
6561 SetPageReserved((page+i));
6562 pfn += (1 << order);
6563 }
6564 spin_unlock_irqrestore(&zone->lock, flags);
6565}
6566#endif
8d22ba1b
WF
6567
6568#ifdef CONFIG_MEMORY_FAILURE
6569bool is_free_buddy_page(struct page *page)
6570{
6571 struct zone *zone = page_zone(page);
6572 unsigned long pfn = page_to_pfn(page);
6573 unsigned long flags;
6574 int order;
6575
6576 spin_lock_irqsave(&zone->lock, flags);
6577 for (order = 0; order < MAX_ORDER; order++) {
6578 struct page *page_head = page - (pfn & ((1 << order) - 1));
6579
6580 if (PageBuddy(page_head) && page_order(page_head) >= order)
6581 break;
6582 }
6583 spin_unlock_irqrestore(&zone->lock, flags);
6584
6585 return order < MAX_ORDER;
6586}
6587#endif
718a3821 6588
51300cef 6589static const struct trace_print_flags pageflag_names[] = {
718a3821
WF
6590 {1UL << PG_locked, "locked" },
6591 {1UL << PG_error, "error" },
6592 {1UL << PG_referenced, "referenced" },
6593 {1UL << PG_uptodate, "uptodate" },
6594 {1UL << PG_dirty, "dirty" },
6595 {1UL << PG_lru, "lru" },
6596 {1UL << PG_active, "active" },
6597 {1UL << PG_slab, "slab" },
6598 {1UL << PG_owner_priv_1, "owner_priv_1" },
6599 {1UL << PG_arch_1, "arch_1" },
6600 {1UL << PG_reserved, "reserved" },
6601 {1UL << PG_private, "private" },
6602 {1UL << PG_private_2, "private_2" },
6603 {1UL << PG_writeback, "writeback" },
6604#ifdef CONFIG_PAGEFLAGS_EXTENDED
6605 {1UL << PG_head, "head" },
6606 {1UL << PG_tail, "tail" },
6607#else
6608 {1UL << PG_compound, "compound" },
6609#endif
6610 {1UL << PG_swapcache, "swapcache" },
6611 {1UL << PG_mappedtodisk, "mappedtodisk" },
6612 {1UL << PG_reclaim, "reclaim" },
718a3821
WF
6613 {1UL << PG_swapbacked, "swapbacked" },
6614 {1UL << PG_unevictable, "unevictable" },
6615#ifdef CONFIG_MMU
6616 {1UL << PG_mlocked, "mlocked" },
6617#endif
6618#ifdef CONFIG_ARCH_USES_PG_UNCACHED
6619 {1UL << PG_uncached, "uncached" },
6620#endif
6621#ifdef CONFIG_MEMORY_FAILURE
6622 {1UL << PG_hwpoison, "hwpoison" },
be9cd873
GS
6623#endif
6624#ifdef CONFIG_TRANSPARENT_HUGEPAGE
6625 {1UL << PG_compound_lock, "compound_lock" },
718a3821 6626#endif
718a3821
WF
6627};
6628
6629static void dump_page_flags(unsigned long flags)
6630{
6631 const char *delim = "";
6632 unsigned long mask;
6633 int i;
6634
51300cef 6635 BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS);
acc50c11 6636
718a3821
WF
6637 printk(KERN_ALERT "page flags: %#lx(", flags);
6638
6639 /* remove zone id */
6640 flags &= (1UL << NR_PAGEFLAGS) - 1;
6641
51300cef 6642 for (i = 0; i < ARRAY_SIZE(pageflag_names) && flags; i++) {
718a3821
WF
6643
6644 mask = pageflag_names[i].mask;
6645 if ((flags & mask) != mask)
6646 continue;
6647
6648 flags &= ~mask;
6649 printk("%s%s", delim, pageflag_names[i].name);
6650 delim = "|";
6651 }
6652
6653 /* check for left over flags */
6654 if (flags)
6655 printk("%s%#lx", delim, flags);
6656
6657 printk(")\n");
6658}
6659
6660void dump_page(struct page *page)
6661{
6662 printk(KERN_ALERT
6663 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
4e9f64c4 6664 page, atomic_read(&page->_count), page_mapcount(page),
718a3821
WF
6665 page->mapping, page->index);
6666 dump_page_flags(page->flags);
f212ad7c 6667 mem_cgroup_print_bad_page(page);
718a3821 6668}
6fa3eb70
S
6669
6670#ifdef CONFIG_MTKPASR
6671/* Find free pages - Caller must acquire zone->lock */
6672int pasr_find_free_page(struct page *page, struct list_head *freelist)
6673{
6674 struct zone *z = page_zone(page);
6675 unsigned int order;
6676 int free_count, i;
6677
6678 /* Remove page from free list */
6679 order = page_order(page);
6680 list_del(&page->lru);
6681 z->free_area[order].nr_free--;
6682 rmv_page_order(page);
6683 __mod_zone_page_state(z, NR_FREE_PAGES, -(1UL << order));
6684
6685 /* Split into individual pages */
6686 set_page_refcounted(page);
6687 split_page(page, order);
6688
6689 /* Add to freelist */
6690 free_count = 1 << order;
6691 for (i = 0; i < free_count; i++) {
6692 list_add(&page->lru, freelist);
6693 page++;
6694 }
6695
6696 return free_count;
6697}
6698EXPORT_SYMBOL(pasr_find_free_page);
6699
6700/* Given an offset and return corresponding valid, inuse page */
6701struct page *pasr_acquire_inuse_page(enum zone_type ztype, unsigned long which_pfn)
6702{
6703 struct page *page;
6704
6705 /* Check & Return inuse page */
6706 if (pfn_valid(which_pfn)) {
6707 page = pfn_to_page(which_pfn);
6708 if (page_count(page) != 0) {
6709 return page;
6710 }
6711 }
6712
6713 return NULL;
6714}
6715EXPORT_SYMBOL(pasr_acquire_inuse_page);
6716
6717/* Compute maximum safe order for page allocation */
6718int pasr_compute_safe_order(void)
6719{
6720 struct zone *z = &NODE_DATA(0)->node_zones[ZONE_NORMAL];
6721 int order;
6722 unsigned long watermark = low_wmark_pages(z);
6723 long free_pages = zone_page_state(z, NR_FREE_PAGES);
6724
6725 /* Start from order:1 to make system more robust */
6726 for (order = 1; order < MAX_ORDER; ++order) {
6727 if (!__zone_watermark_ok(z, order, (watermark + (1 << order)), 0, 0, free_pages)) {
6728 return (order - 2);
6729 }
6730 }
6731
6732 return (MAX_ORDER - 1);
6733}
6734EXPORT_SYMBOL(pasr_compute_safe_order);
6735#endif /* CONFIG_MTKPASR */