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