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