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