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