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