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