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