ia64/xen-unstable

view linux-2.6-xen-sparse/mm/page_alloc.c @ 8186:28bd01c9b596

Merge
author djm@kirby.fc.hp.com
date Fri Dec 02 12:52:25 2005 -0600 (2005-12-02)
parents 06d84bf87159
children 4b06313b9790
line source
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 */
17 #include <linux/config.h>
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/cpuset.h>
35 #include <linux/nodemask.h>
36 #include <linux/vmalloc.h>
38 #include <asm/tlbflush.h>
39 #include "internal.h"
41 /*
42 * MCD - HACK: Find somewhere to initialize this EARLY, or make this
43 * initializer cleaner
44 */
45 nodemask_t node_online_map = { { [0] = 1UL } };
46 EXPORT_SYMBOL(node_online_map);
47 nodemask_t node_possible_map = NODE_MASK_ALL;
48 EXPORT_SYMBOL(node_possible_map);
49 struct pglist_data *pgdat_list;
50 unsigned long totalram_pages;
51 unsigned long totalhigh_pages;
52 long nr_swap_pages;
54 /*
55 * results with 256, 32 in the lowmem_reserve sysctl:
56 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
57 * 1G machine -> (16M dma, 784M normal, 224M high)
58 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
59 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
60 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
61 */
62 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { 256, 32 };
64 EXPORT_SYMBOL(totalram_pages);
65 EXPORT_SYMBOL(nr_swap_pages);
67 /*
68 * Used by page_zone() to look up the address of the struct zone whose
69 * id is encoded in the upper bits of page->flags
70 */
71 struct zone *zone_table[1 << (ZONES_SHIFT + NODES_SHIFT)];
72 EXPORT_SYMBOL(zone_table);
74 static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
75 int min_free_kbytes = 1024;
77 unsigned long __initdata nr_kernel_pages;
78 unsigned long __initdata nr_all_pages;
80 /*
81 * Temporary debugging check for pages not lying within a given zone.
82 */
83 static int bad_range(struct zone *zone, struct page *page)
84 {
85 if (page_to_pfn(page) >= zone->zone_start_pfn + zone->spanned_pages)
86 return 1;
87 if (page_to_pfn(page) < zone->zone_start_pfn)
88 return 1;
89 #ifdef CONFIG_HOLES_IN_ZONE
90 if (!pfn_valid(page_to_pfn(page)))
91 return 1;
92 #endif
93 if (zone != page_zone(page))
94 return 1;
95 return 0;
96 }
98 static void bad_page(const char *function, struct page *page)
99 {
100 printk(KERN_EMERG "Bad page state at %s (in process '%s', page %p)\n",
101 function, current->comm, page);
102 printk(KERN_EMERG "flags:0x%0*lx mapping:%p mapcount:%d count:%d\n",
103 (int)(2*sizeof(page_flags_t)), (unsigned long)page->flags,
104 page->mapping, page_mapcount(page), page_count(page));
105 printk(KERN_EMERG "Backtrace:\n");
106 dump_stack();
107 printk(KERN_EMERG "Trying to fix it up, but a reboot is needed\n");
108 page->flags &= ~(1 << PG_private |
109 1 << PG_locked |
110 1 << PG_lru |
111 1 << PG_active |
112 1 << PG_dirty |
113 1 << PG_swapcache |
114 1 << PG_writeback);
115 set_page_count(page, 0);
116 reset_page_mapcount(page);
117 page->mapping = NULL;
118 tainted |= TAINT_BAD_PAGE;
119 }
121 #ifndef CONFIG_HUGETLB_PAGE
122 #define prep_compound_page(page, order) do { } while (0)
123 #define destroy_compound_page(page, order) do { } while (0)
124 #else
125 /*
126 * Higher-order pages are called "compound pages". They are structured thusly:
127 *
128 * The first PAGE_SIZE page is called the "head page".
129 *
130 * The remaining PAGE_SIZE pages are called "tail pages".
131 *
132 * All pages have PG_compound set. All pages have their ->private pointing at
133 * the head page (even the head page has this).
134 *
135 * The first tail page's ->mapping, if non-zero, holds the address of the
136 * compound page's put_page() function.
137 *
138 * The order of the allocation is stored in the first tail page's ->index
139 * This is only for debug at present. This usage means that zero-order pages
140 * may not be compound.
141 */
142 static void prep_compound_page(struct page *page, unsigned long order)
143 {
144 int i;
145 int nr_pages = 1 << order;
147 page[1].mapping = NULL;
148 page[1].index = order;
149 for (i = 0; i < nr_pages; i++) {
150 struct page *p = page + i;
152 SetPageCompound(p);
153 p->private = (unsigned long)page;
154 }
155 }
157 static void destroy_compound_page(struct page *page, unsigned long order)
158 {
159 int i;
160 int nr_pages = 1 << order;
162 if (!PageCompound(page))
163 return;
165 if (page[1].index != order)
166 bad_page(__FUNCTION__, page);
168 for (i = 0; i < nr_pages; i++) {
169 struct page *p = page + i;
171 if (!PageCompound(p))
172 bad_page(__FUNCTION__, page);
173 if (p->private != (unsigned long)page)
174 bad_page(__FUNCTION__, page);
175 ClearPageCompound(p);
176 }
177 }
178 #endif /* CONFIG_HUGETLB_PAGE */
180 /*
181 * function for dealing with page's order in buddy system.
182 * zone->lock is already acquired when we use these.
183 * So, we don't need atomic page->flags operations here.
184 */
185 static inline unsigned long page_order(struct page *page) {
186 return page->private;
187 }
189 static inline void set_page_order(struct page *page, int order) {
190 page->private = order;
191 __SetPagePrivate(page);
192 }
194 static inline void rmv_page_order(struct page *page)
195 {
196 __ClearPagePrivate(page);
197 page->private = 0;
198 }
200 /*
201 * Locate the struct page for both the matching buddy in our
202 * pair (buddy1) and the combined O(n+1) page they form (page).
203 *
204 * 1) Any buddy B1 will have an order O twin B2 which satisfies
205 * the following equation:
206 * B2 = B1 ^ (1 << O)
207 * For example, if the starting buddy (buddy2) is #8 its order
208 * 1 buddy is #10:
209 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
210 *
211 * 2) Any buddy B will have an order O+1 parent P which
212 * satisfies the following equation:
213 * P = B & ~(1 << O)
214 *
215 * Assumption: *_mem_map is contigious at least up to MAX_ORDER
216 */
217 static inline struct page *
218 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
219 {
220 unsigned long buddy_idx = page_idx ^ (1 << order);
222 return page + (buddy_idx - page_idx);
223 }
225 static inline unsigned long
226 __find_combined_index(unsigned long page_idx, unsigned int order)
227 {
228 return (page_idx & ~(1 << order));
229 }
231 /*
232 * This function checks whether a page is free && is the buddy
233 * we can do coalesce a page and its buddy if
234 * (a) the buddy is free &&
235 * (b) the buddy is on the buddy system &&
236 * (c) a page and its buddy have the same order.
237 * for recording page's order, we use page->private and PG_private.
238 *
239 */
240 static inline int page_is_buddy(struct page *page, int order)
241 {
242 if (PagePrivate(page) &&
243 (page_order(page) == order) &&
244 !PageReserved(page) &&
245 page_count(page) == 0)
246 return 1;
247 return 0;
248 }
250 /*
251 * Freeing function for a buddy system allocator.
252 *
253 * The concept of a buddy system is to maintain direct-mapped table
254 * (containing bit values) for memory blocks of various "orders".
255 * The bottom level table contains the map for the smallest allocatable
256 * units of memory (here, pages), and each level above it describes
257 * pairs of units from the levels below, hence, "buddies".
258 * At a high level, all that happens here is marking the table entry
259 * at the bottom level available, and propagating the changes upward
260 * as necessary, plus some accounting needed to play nicely with other
261 * parts of the VM system.
262 * At each level, we keep a list of pages, which are heads of continuous
263 * free pages of length of (1 << order) and marked with PG_Private.Page's
264 * order is recorded in page->private field.
265 * So when we are allocating or freeing one, we can derive the state of the
266 * other. That is, if we allocate a small block, and both were
267 * free, the remainder of the region must be split into blocks.
268 * If a block is freed, and its buddy is also free, then this
269 * triggers coalescing into a block of larger size.
270 *
271 * -- wli
272 */
274 static inline void __free_pages_bulk (struct page *page,
275 struct zone *zone, unsigned int order)
276 {
277 unsigned long page_idx;
278 int order_size = 1 << order;
280 if (unlikely(order))
281 destroy_compound_page(page, order);
283 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
285 BUG_ON(page_idx & (order_size - 1));
286 BUG_ON(bad_range(zone, page));
288 zone->free_pages += order_size;
289 while (order < MAX_ORDER-1) {
290 unsigned long combined_idx;
291 struct free_area *area;
292 struct page *buddy;
294 combined_idx = __find_combined_index(page_idx, order);
295 buddy = __page_find_buddy(page, page_idx, order);
297 if (bad_range(zone, buddy))
298 break;
299 if (!page_is_buddy(buddy, order))
300 break; /* Move the buddy up one level. */
301 list_del(&buddy->lru);
302 area = zone->free_area + order;
303 area->nr_free--;
304 rmv_page_order(buddy);
305 page = page + (combined_idx - page_idx);
306 page_idx = combined_idx;
307 order++;
308 }
309 set_page_order(page, order);
310 list_add(&page->lru, &zone->free_area[order].free_list);
311 zone->free_area[order].nr_free++;
312 }
314 static inline void free_pages_check(const char *function, struct page *page)
315 {
316 if ( page_mapcount(page) ||
317 page->mapping != NULL ||
318 page_count(page) != 0 ||
319 (page->flags & (
320 1 << PG_lru |
321 1 << PG_private |
322 1 << PG_locked |
323 1 << PG_active |
324 1 << PG_reclaim |
325 1 << PG_slab |
326 1 << PG_swapcache |
327 1 << PG_writeback )))
328 bad_page(function, page);
329 if (PageDirty(page))
330 ClearPageDirty(page);
331 }
333 /*
334 * Frees a list of pages.
335 * Assumes all pages on list are in same zone, and of same order.
336 * count is the number of pages to free, or 0 for all on the list.
337 *
338 * If the zone was previously in an "all pages pinned" state then look to
339 * see if this freeing clears that state.
340 *
341 * And clear the zone's pages_scanned counter, to hold off the "all pages are
342 * pinned" detection logic.
343 */
344 static int
345 free_pages_bulk(struct zone *zone, int count,
346 struct list_head *list, unsigned int order)
347 {
348 unsigned long flags;
349 struct page *page = NULL;
350 int ret = 0;
352 spin_lock_irqsave(&zone->lock, flags);
353 zone->all_unreclaimable = 0;
354 zone->pages_scanned = 0;
355 while (!list_empty(list) && count--) {
356 page = list_entry(list->prev, struct page, lru);
357 /* have to delete it as __free_pages_bulk list manipulates */
358 list_del(&page->lru);
359 __free_pages_bulk(page, zone, order);
360 ret++;
361 }
362 spin_unlock_irqrestore(&zone->lock, flags);
363 return ret;
364 }
366 void __free_pages_ok(struct page *page, unsigned int order)
367 {
368 LIST_HEAD(list);
369 int i;
371 if (arch_free_page(page, order))
372 return;
374 mod_page_state(pgfree, 1 << order);
376 #ifndef CONFIG_MMU
377 if (order > 0)
378 for (i = 1 ; i < (1 << order) ; ++i)
379 __put_page(page + i);
380 #endif
382 for (i = 0 ; i < (1 << order) ; ++i)
383 free_pages_check(__FUNCTION__, page + i);
384 list_add(&page->lru, &list);
385 kernel_map_pages(page, 1<<order, 0);
386 free_pages_bulk(page_zone(page), 1, &list, order);
387 }
390 /*
391 * The order of subdivision here is critical for the IO subsystem.
392 * Please do not alter this order without good reasons and regression
393 * testing. Specifically, as large blocks of memory are subdivided,
394 * the order in which smaller blocks are delivered depends on the order
395 * they're subdivided in this function. This is the primary factor
396 * influencing the order in which pages are delivered to the IO
397 * subsystem according to empirical testing, and this is also justified
398 * by considering the behavior of a buddy system containing a single
399 * large block of memory acted on by a series of small allocations.
400 * This behavior is a critical factor in sglist merging's success.
401 *
402 * -- wli
403 */
404 static inline struct page *
405 expand(struct zone *zone, struct page *page,
406 int low, int high, struct free_area *area)
407 {
408 unsigned long size = 1 << high;
410 while (high > low) {
411 area--;
412 high--;
413 size >>= 1;
414 BUG_ON(bad_range(zone, &page[size]));
415 list_add(&page[size].lru, &area->free_list);
416 area->nr_free++;
417 set_page_order(&page[size], high);
418 }
419 return page;
420 }
422 void set_page_refs(struct page *page, int order)
423 {
424 #ifdef CONFIG_MMU
425 set_page_count(page, 1);
426 #else
427 int i;
429 /*
430 * We need to reference all the pages for this order, otherwise if
431 * anyone accesses one of the pages with (get/put) it will be freed.
432 * - eg: access_process_vm()
433 */
434 for (i = 0; i < (1 << order); i++)
435 set_page_count(page + i, 1);
436 #endif /* CONFIG_MMU */
437 }
439 /*
440 * This page is about to be returned from the page allocator
441 */
442 static void prep_new_page(struct page *page, int order)
443 {
444 if (page->mapping || page_mapcount(page) ||
445 (page->flags & (
446 1 << PG_private |
447 1 << PG_locked |
448 1 << PG_lru |
449 1 << PG_active |
450 1 << PG_dirty |
451 1 << PG_reclaim |
452 1 << PG_swapcache |
453 1 << PG_writeback )))
454 bad_page(__FUNCTION__, page);
456 page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
457 1 << PG_referenced | 1 << PG_arch_1 |
458 1 << PG_checked | 1 << PG_mappedtodisk);
459 page->private = 0;
460 set_page_refs(page, order);
461 kernel_map_pages(page, 1 << order, 1);
462 }
464 /*
465 * Do the hard work of removing an element from the buddy allocator.
466 * Call me with the zone->lock already held.
467 */
468 static struct page *__rmqueue(struct zone *zone, unsigned int order)
469 {
470 struct free_area * area;
471 unsigned int current_order;
472 struct page *page;
474 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
475 area = zone->free_area + current_order;
476 if (list_empty(&area->free_list))
477 continue;
479 page = list_entry(area->free_list.next, struct page, lru);
480 list_del(&page->lru);
481 rmv_page_order(page);
482 area->nr_free--;
483 zone->free_pages -= 1UL << order;
484 return expand(zone, page, order, current_order, area);
485 }
487 return NULL;
488 }
490 /*
491 * Obtain a specified number of elements from the buddy allocator, all under
492 * a single hold of the lock, for efficiency. Add them to the supplied list.
493 * Returns the number of new pages which were placed at *list.
494 */
495 static int rmqueue_bulk(struct zone *zone, unsigned int order,
496 unsigned long count, struct list_head *list)
497 {
498 unsigned long flags;
499 int i;
500 int allocated = 0;
501 struct page *page;
503 spin_lock_irqsave(&zone->lock, flags);
504 for (i = 0; i < count; ++i) {
505 page = __rmqueue(zone, order);
506 if (page == NULL)
507 break;
508 allocated++;
509 list_add_tail(&page->lru, list);
510 }
511 spin_unlock_irqrestore(&zone->lock, flags);
512 return allocated;
513 }
515 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
516 static void __drain_pages(unsigned int cpu)
517 {
518 struct zone *zone;
519 int i;
521 for_each_zone(zone) {
522 struct per_cpu_pageset *pset;
524 pset = &zone->pageset[cpu];
525 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
526 struct per_cpu_pages *pcp;
528 pcp = &pset->pcp[i];
529 pcp->count -= free_pages_bulk(zone, pcp->count,
530 &pcp->list, 0);
531 }
532 }
533 }
534 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
536 #ifdef CONFIG_PM
538 void mark_free_pages(struct zone *zone)
539 {
540 unsigned long zone_pfn, flags;
541 int order;
542 struct list_head *curr;
544 if (!zone->spanned_pages)
545 return;
547 spin_lock_irqsave(&zone->lock, flags);
548 for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
549 ClearPageNosaveFree(pfn_to_page(zone_pfn + zone->zone_start_pfn));
551 for (order = MAX_ORDER - 1; order >= 0; --order)
552 list_for_each(curr, &zone->free_area[order].free_list) {
553 unsigned long start_pfn, i;
555 start_pfn = page_to_pfn(list_entry(curr, struct page, lru));
557 for (i=0; i < (1<<order); i++)
558 SetPageNosaveFree(pfn_to_page(start_pfn+i));
559 }
560 spin_unlock_irqrestore(&zone->lock, flags);
561 }
563 /*
564 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
565 */
566 void drain_local_pages(void)
567 {
568 unsigned long flags;
570 local_irq_save(flags);
571 __drain_pages(smp_processor_id());
572 local_irq_restore(flags);
573 }
574 #endif /* CONFIG_PM */
576 static void zone_statistics(struct zonelist *zonelist, struct zone *z)
577 {
578 #ifdef CONFIG_NUMA
579 unsigned long flags;
580 int cpu;
581 pg_data_t *pg = z->zone_pgdat;
582 pg_data_t *orig = zonelist->zones[0]->zone_pgdat;
583 struct per_cpu_pageset *p;
585 local_irq_save(flags);
586 cpu = smp_processor_id();
587 p = &z->pageset[cpu];
588 if (pg == orig) {
589 z->pageset[cpu].numa_hit++;
590 } else {
591 p->numa_miss++;
592 zonelist->zones[0]->pageset[cpu].numa_foreign++;
593 }
594 if (pg == NODE_DATA(numa_node_id()))
595 p->local_node++;
596 else
597 p->other_node++;
598 local_irq_restore(flags);
599 #endif
600 }
602 /*
603 * Free a 0-order page
604 */
605 static void FASTCALL(free_hot_cold_page(struct page *page, int cold));
606 static void fastcall free_hot_cold_page(struct page *page, int cold)
607 {
608 struct zone *zone = page_zone(page);
609 struct per_cpu_pages *pcp;
610 unsigned long flags;
612 if (arch_free_page(page, 0))
613 return;
615 kernel_map_pages(page, 1, 0);
616 inc_page_state(pgfree);
617 if (PageAnon(page))
618 page->mapping = NULL;
619 free_pages_check(__FUNCTION__, page);
620 pcp = &zone->pageset[get_cpu()].pcp[cold];
621 local_irq_save(flags);
622 if (pcp->count >= pcp->high)
623 pcp->count -= free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
624 list_add(&page->lru, &pcp->list);
625 pcp->count++;
626 local_irq_restore(flags);
627 put_cpu();
628 }
630 void fastcall free_hot_page(struct page *page)
631 {
632 free_hot_cold_page(page, 0);
633 }
635 void fastcall free_cold_page(struct page *page)
636 {
637 free_hot_cold_page(page, 1);
638 }
640 static inline void prep_zero_page(struct page *page, int order, unsigned int __nocast gfp_flags)
641 {
642 int i;
644 BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
645 for(i = 0; i < (1 << order); i++)
646 clear_highpage(page + i);
647 }
649 /*
650 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
651 * we cheat by calling it from here, in the order > 0 path. Saves a branch
652 * or two.
653 */
654 static struct page *
655 buffered_rmqueue(struct zone *zone, int order, unsigned int __nocast gfp_flags)
656 {
657 unsigned long flags;
658 struct page *page = NULL;
659 int cold = !!(gfp_flags & __GFP_COLD);
661 if (order == 0) {
662 struct per_cpu_pages *pcp;
664 pcp = &zone->pageset[get_cpu()].pcp[cold];
665 local_irq_save(flags);
666 if (pcp->count <= pcp->low)
667 pcp->count += rmqueue_bulk(zone, 0,
668 pcp->batch, &pcp->list);
669 if (pcp->count) {
670 page = list_entry(pcp->list.next, struct page, lru);
671 list_del(&page->lru);
672 pcp->count--;
673 }
674 local_irq_restore(flags);
675 put_cpu();
676 }
678 if (page == NULL) {
679 spin_lock_irqsave(&zone->lock, flags);
680 page = __rmqueue(zone, order);
681 spin_unlock_irqrestore(&zone->lock, flags);
682 }
684 if (page != NULL) {
685 BUG_ON(bad_range(zone, page));
686 mod_page_state_zone(zone, pgalloc, 1 << order);
687 prep_new_page(page, order);
689 if (gfp_flags & __GFP_ZERO)
690 prep_zero_page(page, order, gfp_flags);
692 if (order && (gfp_flags & __GFP_COMP))
693 prep_compound_page(page, order);
694 }
695 return page;
696 }
698 /*
699 * Return 1 if free pages are above 'mark'. This takes into account the order
700 * of the allocation.
701 */
702 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
703 int classzone_idx, int can_try_harder, int gfp_high)
704 {
705 /* free_pages my go negative - that's OK */
706 long min = mark, free_pages = z->free_pages - (1 << order) + 1;
707 int o;
709 if (gfp_high)
710 min -= min / 2;
711 if (can_try_harder)
712 min -= min / 4;
714 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
715 return 0;
716 for (o = 0; o < order; o++) {
717 /* At the next order, this order's pages become unavailable */
718 free_pages -= z->free_area[o].nr_free << o;
720 /* Require fewer higher order pages to be free */
721 min >>= 1;
723 if (free_pages <= min)
724 return 0;
725 }
726 return 1;
727 }
729 /*
730 * This is the 'heart' of the zoned buddy allocator.
731 */
732 struct page * fastcall
733 __alloc_pages(unsigned int __nocast gfp_mask, unsigned int order,
734 struct zonelist *zonelist)
735 {
736 const int wait = gfp_mask & __GFP_WAIT;
737 struct zone **zones, *z;
738 struct page *page;
739 struct reclaim_state reclaim_state;
740 struct task_struct *p = current;
741 int i;
742 int classzone_idx;
743 int do_retry;
744 int can_try_harder;
745 int did_some_progress;
747 might_sleep_if(wait);
749 /*
750 * The caller may dip into page reserves a bit more if the caller
751 * cannot run direct reclaim, or is the caller has realtime scheduling
752 * policy
753 */
754 can_try_harder = (unlikely(rt_task(p)) && !in_interrupt()) || !wait;
756 zones = zonelist->zones; /* the list of zones suitable for gfp_mask */
758 if (unlikely(zones[0] == NULL)) {
759 /* Should this ever happen?? */
760 return NULL;
761 }
763 classzone_idx = zone_idx(zones[0]);
765 restart:
766 /* Go through the zonelist once, looking for a zone with enough free */
767 for (i = 0; (z = zones[i]) != NULL; i++) {
769 if (!zone_watermark_ok(z, order, z->pages_low,
770 classzone_idx, 0, 0))
771 continue;
773 if (!cpuset_zone_allowed(z))
774 continue;
776 page = buffered_rmqueue(z, order, gfp_mask);
777 if (page)
778 goto got_pg;
779 }
781 for (i = 0; (z = zones[i]) != NULL; i++)
782 wakeup_kswapd(z, order);
784 /*
785 * Go through the zonelist again. Let __GFP_HIGH and allocations
786 * coming from realtime tasks to go deeper into reserves
787 *
788 * This is the last chance, in general, before the goto nopage.
789 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
790 */
791 for (i = 0; (z = zones[i]) != NULL; i++) {
792 if (!zone_watermark_ok(z, order, z->pages_min,
793 classzone_idx, can_try_harder,
794 gfp_mask & __GFP_HIGH))
795 continue;
797 if (wait && !cpuset_zone_allowed(z))
798 continue;
800 page = buffered_rmqueue(z, order, gfp_mask);
801 if (page)
802 goto got_pg;
803 }
805 /* This allocation should allow future memory freeing. */
807 if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
808 && !in_interrupt()) {
809 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
810 /* go through the zonelist yet again, ignoring mins */
811 for (i = 0; (z = zones[i]) != NULL; i++) {
812 if (!cpuset_zone_allowed(z))
813 continue;
814 page = buffered_rmqueue(z, order, gfp_mask);
815 if (page)
816 goto got_pg;
817 }
818 }
819 goto nopage;
820 }
822 /* Atomic allocations - we can't balance anything */
823 if (!wait)
824 goto nopage;
826 rebalance:
827 cond_resched();
829 /* We now go into synchronous reclaim */
830 p->flags |= PF_MEMALLOC;
831 reclaim_state.reclaimed_slab = 0;
832 p->reclaim_state = &reclaim_state;
834 did_some_progress = try_to_free_pages(zones, gfp_mask, order);
836 p->reclaim_state = NULL;
837 p->flags &= ~PF_MEMALLOC;
839 cond_resched();
841 if (likely(did_some_progress)) {
842 /*
843 * Go through the zonelist yet one more time, keep
844 * very high watermark here, this is only to catch
845 * a parallel oom killing, we must fail if we're still
846 * under heavy pressure.
847 */
848 for (i = 0; (z = zones[i]) != NULL; i++) {
849 if (!zone_watermark_ok(z, order, z->pages_min,
850 classzone_idx, can_try_harder,
851 gfp_mask & __GFP_HIGH))
852 continue;
854 if (!cpuset_zone_allowed(z))
855 continue;
857 page = buffered_rmqueue(z, order, gfp_mask);
858 if (page)
859 goto got_pg;
860 }
861 } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
862 /*
863 * Go through the zonelist yet one more time, keep
864 * very high watermark here, this is only to catch
865 * a parallel oom killing, we must fail if we're still
866 * under heavy pressure.
867 */
868 for (i = 0; (z = zones[i]) != NULL; i++) {
869 if (!zone_watermark_ok(z, order, z->pages_high,
870 classzone_idx, 0, 0))
871 continue;
873 if (!cpuset_zone_allowed(z))
874 continue;
876 page = buffered_rmqueue(z, order, gfp_mask);
877 if (page)
878 goto got_pg;
879 }
881 out_of_memory(gfp_mask);
882 goto restart;
883 }
885 /*
886 * Don't let big-order allocations loop unless the caller explicitly
887 * requests that. Wait for some write requests to complete then retry.
888 *
889 * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
890 * <= 3, but that may not be true in other implementations.
891 */
892 do_retry = 0;
893 if (!(gfp_mask & __GFP_NORETRY)) {
894 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
895 do_retry = 1;
896 if (gfp_mask & __GFP_NOFAIL)
897 do_retry = 1;
898 }
899 if (do_retry) {
900 blk_congestion_wait(WRITE, HZ/50);
901 goto rebalance;
902 }
904 nopage:
905 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
906 printk(KERN_WARNING "%s: page allocation failure."
907 " order:%d, mode:0x%x\n",
908 p->comm, order, gfp_mask);
909 dump_stack();
910 }
911 return NULL;
912 got_pg:
913 zone_statistics(zonelist, z);
914 return page;
915 }
917 EXPORT_SYMBOL(__alloc_pages);
919 /*
920 * Common helper functions.
921 */
922 fastcall unsigned long __get_free_pages(unsigned int __nocast gfp_mask, unsigned int order)
923 {
924 struct page * page;
925 page = alloc_pages(gfp_mask, order);
926 if (!page)
927 return 0;
928 return (unsigned long) page_address(page);
929 }
931 EXPORT_SYMBOL(__get_free_pages);
933 fastcall unsigned long get_zeroed_page(unsigned int __nocast gfp_mask)
934 {
935 struct page * page;
937 /*
938 * get_zeroed_page() returns a 32-bit address, which cannot represent
939 * a highmem page
940 */
941 BUG_ON(gfp_mask & __GFP_HIGHMEM);
943 page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
944 if (page)
945 return (unsigned long) page_address(page);
946 return 0;
947 }
949 EXPORT_SYMBOL(get_zeroed_page);
951 void __pagevec_free(struct pagevec *pvec)
952 {
953 int i = pagevec_count(pvec);
955 while (--i >= 0)
956 free_hot_cold_page(pvec->pages[i], pvec->cold);
957 }
959 fastcall void __free_pages(struct page *page, unsigned int order)
960 {
961 if (!PageReserved(page) && put_page_testzero(page)) {
962 if (order == 0)
963 free_hot_page(page);
964 else
965 __free_pages_ok(page, order);
966 }
967 }
969 EXPORT_SYMBOL(__free_pages);
971 fastcall void free_pages(unsigned long addr, unsigned int order)
972 {
973 if (addr != 0) {
974 BUG_ON(!virt_addr_valid((void *)addr));
975 __free_pages(virt_to_page((void *)addr), order);
976 }
977 }
979 EXPORT_SYMBOL(free_pages);
981 /*
982 * Total amount of free (allocatable) RAM:
983 */
984 unsigned int nr_free_pages(void)
985 {
986 unsigned int sum = 0;
987 struct zone *zone;
989 for_each_zone(zone)
990 sum += zone->free_pages;
992 return sum;
993 }
995 EXPORT_SYMBOL(nr_free_pages);
997 #ifdef CONFIG_NUMA
998 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
999 {
1000 unsigned int i, sum = 0;
1002 for (i = 0; i < MAX_NR_ZONES; i++)
1003 sum += pgdat->node_zones[i].free_pages;
1005 return sum;
1007 #endif
1009 static unsigned int nr_free_zone_pages(int offset)
1011 pg_data_t *pgdat;
1012 unsigned int sum = 0;
1014 for_each_pgdat(pgdat) {
1015 struct zonelist *zonelist = pgdat->node_zonelists + offset;
1016 struct zone **zonep = zonelist->zones;
1017 struct zone *zone;
1019 for (zone = *zonep++; zone; zone = *zonep++) {
1020 unsigned long size = zone->present_pages;
1021 unsigned long high = zone->pages_high;
1022 if (size > high)
1023 sum += size - high;
1027 return sum;
1030 /*
1031 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1032 */
1033 unsigned int nr_free_buffer_pages(void)
1035 return nr_free_zone_pages(GFP_USER & GFP_ZONEMASK);
1038 /*
1039 * Amount of free RAM allocatable within all zones
1040 */
1041 unsigned int nr_free_pagecache_pages(void)
1043 return nr_free_zone_pages(GFP_HIGHUSER & GFP_ZONEMASK);
1046 #ifdef CONFIG_HIGHMEM
1047 unsigned int nr_free_highpages (void)
1049 pg_data_t *pgdat;
1050 unsigned int pages = 0;
1052 for_each_pgdat(pgdat)
1053 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1055 return pages;
1057 #endif
1059 #ifdef CONFIG_NUMA
1060 static void show_node(struct zone *zone)
1062 printk("Node %d ", zone->zone_pgdat->node_id);
1064 #else
1065 #define show_node(zone) do { } while (0)
1066 #endif
1068 /*
1069 * Accumulate the page_state information across all CPUs.
1070 * The result is unavoidably approximate - it can change
1071 * during and after execution of this function.
1072 */
1073 static DEFINE_PER_CPU(struct page_state, page_states) = {0};
1075 atomic_t nr_pagecache = ATOMIC_INIT(0);
1076 EXPORT_SYMBOL(nr_pagecache);
1077 #ifdef CONFIG_SMP
1078 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
1079 #endif
1081 void __get_page_state(struct page_state *ret, int nr)
1083 int cpu = 0;
1085 memset(ret, 0, sizeof(*ret));
1087 cpu = first_cpu(cpu_online_map);
1088 while (cpu < NR_CPUS) {
1089 unsigned long *in, *out, off;
1091 in = (unsigned long *)&per_cpu(page_states, cpu);
1093 cpu = next_cpu(cpu, cpu_online_map);
1095 if (cpu < NR_CPUS)
1096 prefetch(&per_cpu(page_states, cpu));
1098 out = (unsigned long *)ret;
1099 for (off = 0; off < nr; off++)
1100 *out++ += *in++;
1104 void get_page_state(struct page_state *ret)
1106 int nr;
1108 nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
1109 nr /= sizeof(unsigned long);
1111 __get_page_state(ret, nr + 1);
1114 void get_full_page_state(struct page_state *ret)
1116 __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long));
1119 unsigned long __read_page_state(unsigned offset)
1121 unsigned long ret = 0;
1122 int cpu;
1124 for_each_online_cpu(cpu) {
1125 unsigned long in;
1127 in = (unsigned long)&per_cpu(page_states, cpu) + offset;
1128 ret += *((unsigned long *)in);
1130 return ret;
1133 void __mod_page_state(unsigned offset, unsigned long delta)
1135 unsigned long flags;
1136 void* ptr;
1138 local_irq_save(flags);
1139 ptr = &__get_cpu_var(page_states);
1140 *(unsigned long*)(ptr + offset) += delta;
1141 local_irq_restore(flags);
1144 EXPORT_SYMBOL(__mod_page_state);
1146 void __get_zone_counts(unsigned long *active, unsigned long *inactive,
1147 unsigned long *free, struct pglist_data *pgdat)
1149 struct zone *zones = pgdat->node_zones;
1150 int i;
1152 *active = 0;
1153 *inactive = 0;
1154 *free = 0;
1155 for (i = 0; i < MAX_NR_ZONES; i++) {
1156 *active += zones[i].nr_active;
1157 *inactive += zones[i].nr_inactive;
1158 *free += zones[i].free_pages;
1162 void get_zone_counts(unsigned long *active,
1163 unsigned long *inactive, unsigned long *free)
1165 struct pglist_data *pgdat;
1167 *active = 0;
1168 *inactive = 0;
1169 *free = 0;
1170 for_each_pgdat(pgdat) {
1171 unsigned long l, m, n;
1172 __get_zone_counts(&l, &m, &n, pgdat);
1173 *active += l;
1174 *inactive += m;
1175 *free += n;
1179 void si_meminfo(struct sysinfo *val)
1181 val->totalram = totalram_pages;
1182 val->sharedram = 0;
1183 val->freeram = nr_free_pages();
1184 val->bufferram = nr_blockdev_pages();
1185 #ifdef CONFIG_HIGHMEM
1186 val->totalhigh = totalhigh_pages;
1187 val->freehigh = nr_free_highpages();
1188 #else
1189 val->totalhigh = 0;
1190 val->freehigh = 0;
1191 #endif
1192 val->mem_unit = PAGE_SIZE;
1195 EXPORT_SYMBOL(si_meminfo);
1197 #ifdef CONFIG_NUMA
1198 void si_meminfo_node(struct sysinfo *val, int nid)
1200 pg_data_t *pgdat = NODE_DATA(nid);
1202 val->totalram = pgdat->node_present_pages;
1203 val->freeram = nr_free_pages_pgdat(pgdat);
1204 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1205 val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1206 val->mem_unit = PAGE_SIZE;
1208 #endif
1210 #define K(x) ((x) << (PAGE_SHIFT-10))
1212 /*
1213 * Show free area list (used inside shift_scroll-lock stuff)
1214 * We also calculate the percentage fragmentation. We do this by counting the
1215 * memory on each free list with the exception of the first item on the list.
1216 */
1217 void show_free_areas(void)
1219 struct page_state ps;
1220 int cpu, temperature;
1221 unsigned long active;
1222 unsigned long inactive;
1223 unsigned long free;
1224 struct zone *zone;
1226 for_each_zone(zone) {
1227 show_node(zone);
1228 printk("%s per-cpu:", zone->name);
1230 if (!zone->present_pages) {
1231 printk(" empty\n");
1232 continue;
1233 } else
1234 printk("\n");
1236 for (cpu = 0; cpu < NR_CPUS; ++cpu) {
1237 struct per_cpu_pageset *pageset;
1239 if (!cpu_possible(cpu))
1240 continue;
1242 pageset = zone->pageset + cpu;
1244 for (temperature = 0; temperature < 2; temperature++)
1245 printk("cpu %d %s: low %d, high %d, batch %d\n",
1246 cpu,
1247 temperature ? "cold" : "hot",
1248 pageset->pcp[temperature].low,
1249 pageset->pcp[temperature].high,
1250 pageset->pcp[temperature].batch);
1254 get_page_state(&ps);
1255 get_zone_counts(&active, &inactive, &free);
1257 printk("\nFree pages: %11ukB (%ukB HighMem)\n",
1258 K(nr_free_pages()),
1259 K(nr_free_highpages()));
1261 printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1262 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1263 active,
1264 inactive,
1265 ps.nr_dirty,
1266 ps.nr_writeback,
1267 ps.nr_unstable,
1268 nr_free_pages(),
1269 ps.nr_slab,
1270 ps.nr_mapped,
1271 ps.nr_page_table_pages);
1273 for_each_zone(zone) {
1274 int i;
1276 show_node(zone);
1277 printk("%s"
1278 " free:%lukB"
1279 " min:%lukB"
1280 " low:%lukB"
1281 " high:%lukB"
1282 " active:%lukB"
1283 " inactive:%lukB"
1284 " present:%lukB"
1285 " pages_scanned:%lu"
1286 " all_unreclaimable? %s"
1287 "\n",
1288 zone->name,
1289 K(zone->free_pages),
1290 K(zone->pages_min),
1291 K(zone->pages_low),
1292 K(zone->pages_high),
1293 K(zone->nr_active),
1294 K(zone->nr_inactive),
1295 K(zone->present_pages),
1296 zone->pages_scanned,
1297 (zone->all_unreclaimable ? "yes" : "no")
1298 );
1299 printk("lowmem_reserve[]:");
1300 for (i = 0; i < MAX_NR_ZONES; i++)
1301 printk(" %lu", zone->lowmem_reserve[i]);
1302 printk("\n");
1305 for_each_zone(zone) {
1306 unsigned long nr, flags, order, total = 0;
1308 show_node(zone);
1309 printk("%s: ", zone->name);
1310 if (!zone->present_pages) {
1311 printk("empty\n");
1312 continue;
1315 spin_lock_irqsave(&zone->lock, flags);
1316 for (order = 0; order < MAX_ORDER; order++) {
1317 nr = zone->free_area[order].nr_free;
1318 total += nr << order;
1319 printk("%lu*%lukB ", nr, K(1UL) << order);
1321 spin_unlock_irqrestore(&zone->lock, flags);
1322 printk("= %lukB\n", K(total));
1325 show_swap_cache_info();
1328 /*
1329 * Builds allocation fallback zone lists.
1330 */
1331 static int __init build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int j, int k)
1333 switch (k) {
1334 struct zone *zone;
1335 default:
1336 BUG();
1337 case ZONE_HIGHMEM:
1338 zone = pgdat->node_zones + ZONE_HIGHMEM;
1339 if (zone->present_pages) {
1340 #ifndef CONFIG_HIGHMEM
1341 BUG();
1342 #endif
1343 zonelist->zones[j++] = zone;
1345 case ZONE_NORMAL:
1346 zone = pgdat->node_zones + ZONE_NORMAL;
1347 if (zone->present_pages)
1348 zonelist->zones[j++] = zone;
1349 case ZONE_DMA:
1350 zone = pgdat->node_zones + ZONE_DMA;
1351 if (zone->present_pages)
1352 zonelist->zones[j++] = zone;
1355 return j;
1358 #ifdef CONFIG_NUMA
1359 #define MAX_NODE_LOAD (num_online_nodes())
1360 static int __initdata node_load[MAX_NUMNODES];
1361 /**
1362 * find_next_best_node - find the next node that should appear in a given node's fallback list
1363 * @node: node whose fallback list we're appending
1364 * @used_node_mask: nodemask_t of already used nodes
1366 * We use a number of factors to determine which is the next node that should
1367 * appear on a given node's fallback list. The node should not have appeared
1368 * already in @node's fallback list, and it should be the next closest node
1369 * according to the distance array (which contains arbitrary distance values
1370 * from each node to each node in the system), and should also prefer nodes
1371 * with no CPUs, since presumably they'll have very little allocation pressure
1372 * on them otherwise.
1373 * It returns -1 if no node is found.
1374 */
1375 static int __init find_next_best_node(int node, nodemask_t *used_node_mask)
1377 int i, n, val;
1378 int min_val = INT_MAX;
1379 int best_node = -1;
1381 for_each_online_node(i) {
1382 cpumask_t tmp;
1384 /* Start from local node */
1385 n = (node+i) % num_online_nodes();
1387 /* Don't want a node to appear more than once */
1388 if (node_isset(n, *used_node_mask))
1389 continue;
1391 /* Use the local node if we haven't already */
1392 if (!node_isset(node, *used_node_mask)) {
1393 best_node = node;
1394 break;
1397 /* Use the distance array to find the distance */
1398 val = node_distance(node, n);
1400 /* Give preference to headless and unused nodes */
1401 tmp = node_to_cpumask(n);
1402 if (!cpus_empty(tmp))
1403 val += PENALTY_FOR_NODE_WITH_CPUS;
1405 /* Slight preference for less loaded node */
1406 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1407 val += node_load[n];
1409 if (val < min_val) {
1410 min_val = val;
1411 best_node = n;
1415 if (best_node >= 0)
1416 node_set(best_node, *used_node_mask);
1418 return best_node;
1421 static void __init build_zonelists(pg_data_t *pgdat)
1423 int i, j, k, node, local_node;
1424 int prev_node, load;
1425 struct zonelist *zonelist;
1426 nodemask_t used_mask;
1428 /* initialize zonelists */
1429 for (i = 0; i < GFP_ZONETYPES; i++) {
1430 zonelist = pgdat->node_zonelists + i;
1431 zonelist->zones[0] = NULL;
1434 /* NUMA-aware ordering of nodes */
1435 local_node = pgdat->node_id;
1436 load = num_online_nodes();
1437 prev_node = local_node;
1438 nodes_clear(used_mask);
1439 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1440 /*
1441 * We don't want to pressure a particular node.
1442 * So adding penalty to the first node in same
1443 * distance group to make it round-robin.
1444 */
1445 if (node_distance(local_node, node) !=
1446 node_distance(local_node, prev_node))
1447 node_load[node] += load;
1448 prev_node = node;
1449 load--;
1450 for (i = 0; i < GFP_ZONETYPES; i++) {
1451 zonelist = pgdat->node_zonelists + i;
1452 for (j = 0; zonelist->zones[j] != NULL; j++);
1454 k = ZONE_NORMAL;
1455 if (i & __GFP_HIGHMEM)
1456 k = ZONE_HIGHMEM;
1457 if (i & __GFP_DMA)
1458 k = ZONE_DMA;
1460 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1461 zonelist->zones[j] = NULL;
1466 #else /* CONFIG_NUMA */
1468 static void __init build_zonelists(pg_data_t *pgdat)
1470 int i, j, k, node, local_node;
1472 local_node = pgdat->node_id;
1473 for (i = 0; i < GFP_ZONETYPES; i++) {
1474 struct zonelist *zonelist;
1476 zonelist = pgdat->node_zonelists + i;
1478 j = 0;
1479 k = ZONE_NORMAL;
1480 if (i & __GFP_HIGHMEM)
1481 k = ZONE_HIGHMEM;
1482 if (i & __GFP_DMA)
1483 k = ZONE_DMA;
1485 j = build_zonelists_node(pgdat, zonelist, j, k);
1486 /*
1487 * Now we build the zonelist so that it contains the zones
1488 * of all the other nodes.
1489 * We don't want to pressure a particular node, so when
1490 * building the zones for node N, we make sure that the
1491 * zones coming right after the local ones are those from
1492 * node N+1 (modulo N)
1493 */
1494 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
1495 if (!node_online(node))
1496 continue;
1497 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1499 for (node = 0; node < local_node; node++) {
1500 if (!node_online(node))
1501 continue;
1502 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1505 zonelist->zones[j] = NULL;
1509 #endif /* CONFIG_NUMA */
1511 void __init build_all_zonelists(void)
1513 int i;
1515 for_each_online_node(i)
1516 build_zonelists(NODE_DATA(i));
1517 printk("Built %i zonelists\n", num_online_nodes());
1518 cpuset_init_current_mems_allowed();
1521 /*
1522 * Helper functions to size the waitqueue hash table.
1523 * Essentially these want to choose hash table sizes sufficiently
1524 * large so that collisions trying to wait on pages are rare.
1525 * But in fact, the number of active page waitqueues on typical
1526 * systems is ridiculously low, less than 200. So this is even
1527 * conservative, even though it seems large.
1529 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1530 * waitqueues, i.e. the size of the waitq table given the number of pages.
1531 */
1532 #define PAGES_PER_WAITQUEUE 256
1534 static inline unsigned long wait_table_size(unsigned long pages)
1536 unsigned long size = 1;
1538 pages /= PAGES_PER_WAITQUEUE;
1540 while (size < pages)
1541 size <<= 1;
1543 /*
1544 * Once we have dozens or even hundreds of threads sleeping
1545 * on IO we've got bigger problems than wait queue collision.
1546 * Limit the size of the wait table to a reasonable size.
1547 */
1548 size = min(size, 4096UL);
1550 return max(size, 4UL);
1553 /*
1554 * This is an integer logarithm so that shifts can be used later
1555 * to extract the more random high bits from the multiplicative
1556 * hash function before the remainder is taken.
1557 */
1558 static inline unsigned long wait_table_bits(unsigned long size)
1560 return ffz(~size);
1563 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1565 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1566 unsigned long *zones_size, unsigned long *zholes_size)
1568 unsigned long realtotalpages, totalpages = 0;
1569 int i;
1571 for (i = 0; i < MAX_NR_ZONES; i++)
1572 totalpages += zones_size[i];
1573 pgdat->node_spanned_pages = totalpages;
1575 realtotalpages = totalpages;
1576 if (zholes_size)
1577 for (i = 0; i < MAX_NR_ZONES; i++)
1578 realtotalpages -= zholes_size[i];
1579 pgdat->node_present_pages = realtotalpages;
1580 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1584 /*
1585 * Initially all pages are reserved - free ones are freed
1586 * up by free_all_bootmem() once the early boot process is
1587 * done. Non-atomic initialization, single-pass.
1588 */
1589 void __init memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1590 unsigned long start_pfn)
1592 struct page *start = pfn_to_page(start_pfn);
1593 struct page *page;
1595 for (page = start; page < (start + size); page++) {
1596 set_page_zone(page, NODEZONE(nid, zone));
1597 set_page_count(page, 0);
1598 reset_page_mapcount(page);
1599 SetPageReserved(page);
1600 INIT_LIST_HEAD(&page->lru);
1601 #ifdef WANT_PAGE_VIRTUAL
1602 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1603 if (!is_highmem_idx(zone))
1604 set_page_address(page, __va(start_pfn << PAGE_SHIFT));
1605 #endif
1606 start_pfn++;
1610 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone,
1611 unsigned long size)
1613 int order;
1614 for (order = 0; order < MAX_ORDER ; order++) {
1615 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1616 zone->free_area[order].nr_free = 0;
1620 #ifndef __HAVE_ARCH_MEMMAP_INIT
1621 #define memmap_init(size, nid, zone, start_pfn) \
1622 memmap_init_zone((size), (nid), (zone), (start_pfn))
1623 #endif
1625 /*
1626 * Set up the zone data structures:
1627 * - mark all pages reserved
1628 * - mark all memory queues empty
1629 * - clear the memory bitmaps
1630 */
1631 static void __init free_area_init_core(struct pglist_data *pgdat,
1632 unsigned long *zones_size, unsigned long *zholes_size)
1634 unsigned long i, j;
1635 const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);
1636 int cpu, nid = pgdat->node_id;
1637 unsigned long zone_start_pfn = pgdat->node_start_pfn;
1639 pgdat->nr_zones = 0;
1640 init_waitqueue_head(&pgdat->kswapd_wait);
1641 pgdat->kswapd_max_order = 0;
1643 for (j = 0; j < MAX_NR_ZONES; j++) {
1644 struct zone *zone = pgdat->node_zones + j;
1645 unsigned long size, realsize;
1646 unsigned long batch;
1648 zone_table[NODEZONE(nid, j)] = zone;
1649 realsize = size = zones_size[j];
1650 if (zholes_size)
1651 realsize -= zholes_size[j];
1653 if (j == ZONE_DMA || j == ZONE_NORMAL)
1654 nr_kernel_pages += realsize;
1655 nr_all_pages += realsize;
1657 zone->spanned_pages = size;
1658 zone->present_pages = realsize;
1659 zone->name = zone_names[j];
1660 spin_lock_init(&zone->lock);
1661 spin_lock_init(&zone->lru_lock);
1662 zone->zone_pgdat = pgdat;
1663 zone->free_pages = 0;
1665 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
1667 /*
1668 * The per-cpu-pages pools are set to around 1000th of the
1669 * size of the zone. But no more than 1/4 of a meg - there's
1670 * no point in going beyond the size of L2 cache.
1672 * OK, so we don't know how big the cache is. So guess.
1673 */
1674 batch = zone->present_pages / 1024;
1675 if (batch * PAGE_SIZE > 256 * 1024)
1676 batch = (256 * 1024) / PAGE_SIZE;
1677 batch /= 4; /* We effectively *= 4 below */
1678 if (batch < 1)
1679 batch = 1;
1681 /*
1682 * Clamp the batch to a 2^n - 1 value. Having a power
1683 * of 2 value was found to be more likely to have
1684 * suboptimal cache aliasing properties in some cases.
1686 * For example if 2 tasks are alternately allocating
1687 * batches of pages, one task can end up with a lot
1688 * of pages of one half of the possible page colors
1689 * and the other with pages of the other colors.
1690 */
1691 batch = (1 << fls(batch + batch/2)) - 1;
1693 for (cpu = 0; cpu < NR_CPUS; cpu++) {
1694 struct per_cpu_pages *pcp;
1696 pcp = &zone->pageset[cpu].pcp[0]; /* hot */
1697 pcp->count = 0;
1698 pcp->low = 2 * batch;
1699 pcp->high = 6 * batch;
1700 pcp->batch = 1 * batch;
1701 INIT_LIST_HEAD(&pcp->list);
1703 pcp = &zone->pageset[cpu].pcp[1]; /* cold */
1704 pcp->count = 0;
1705 pcp->low = 0;
1706 pcp->high = 2 * batch;
1707 pcp->batch = 1 * batch;
1708 INIT_LIST_HEAD(&pcp->list);
1710 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%lu\n",
1711 zone_names[j], realsize, batch);
1712 INIT_LIST_HEAD(&zone->active_list);
1713 INIT_LIST_HEAD(&zone->inactive_list);
1714 zone->nr_scan_active = 0;
1715 zone->nr_scan_inactive = 0;
1716 zone->nr_active = 0;
1717 zone->nr_inactive = 0;
1718 if (!size)
1719 continue;
1721 /*
1722 * The per-page waitqueue mechanism uses hashed waitqueues
1723 * per zone.
1724 */
1725 zone->wait_table_size = wait_table_size(size);
1726 zone->wait_table_bits =
1727 wait_table_bits(zone->wait_table_size);
1728 zone->wait_table = (wait_queue_head_t *)
1729 alloc_bootmem_node(pgdat, zone->wait_table_size
1730 * sizeof(wait_queue_head_t));
1732 for(i = 0; i < zone->wait_table_size; ++i)
1733 init_waitqueue_head(zone->wait_table + i);
1735 pgdat->nr_zones = j+1;
1737 zone->zone_mem_map = pfn_to_page(zone_start_pfn);
1738 zone->zone_start_pfn = zone_start_pfn;
1740 if ((zone_start_pfn) & (zone_required_alignment-1))
1741 printk(KERN_CRIT "BUG: wrong zone alignment, it will crash\n");
1743 memmap_init(size, nid, j, zone_start_pfn);
1745 zone_start_pfn += size;
1747 zone_init_free_lists(pgdat, zone, zone->spanned_pages);
1751 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
1753 unsigned long size;
1755 /* Skip empty nodes */
1756 if (!pgdat->node_spanned_pages)
1757 return;
1759 /* ia64 gets its own node_mem_map, before this, without bootmem */
1760 if (!pgdat->node_mem_map) {
1761 size = (pgdat->node_spanned_pages + 1) * sizeof(struct page);
1762 pgdat->node_mem_map = alloc_bootmem_node(pgdat, size);
1764 #ifndef CONFIG_DISCONTIGMEM
1765 /*
1766 * With no DISCONTIG, the global mem_map is just set as node 0's
1767 */
1768 if (pgdat == NODE_DATA(0))
1769 mem_map = NODE_DATA(0)->node_mem_map;
1770 #endif
1773 void __init free_area_init_node(int nid, struct pglist_data *pgdat,
1774 unsigned long *zones_size, unsigned long node_start_pfn,
1775 unsigned long *zholes_size)
1777 pgdat->node_id = nid;
1778 pgdat->node_start_pfn = node_start_pfn;
1779 calculate_zone_totalpages(pgdat, zones_size, zholes_size);
1781 alloc_node_mem_map(pgdat);
1783 free_area_init_core(pgdat, zones_size, zholes_size);
1786 #ifndef CONFIG_DISCONTIGMEM
1787 static bootmem_data_t contig_bootmem_data;
1788 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
1790 EXPORT_SYMBOL(contig_page_data);
1792 void __init free_area_init(unsigned long *zones_size)
1794 free_area_init_node(0, &contig_page_data, zones_size,
1795 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
1797 #endif
1799 #ifdef CONFIG_PROC_FS
1801 #include <linux/seq_file.h>
1803 static void *frag_start(struct seq_file *m, loff_t *pos)
1805 pg_data_t *pgdat;
1806 loff_t node = *pos;
1808 for (pgdat = pgdat_list; pgdat && node; pgdat = pgdat->pgdat_next)
1809 --node;
1811 return pgdat;
1814 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
1816 pg_data_t *pgdat = (pg_data_t *)arg;
1818 (*pos)++;
1819 return pgdat->pgdat_next;
1822 static void frag_stop(struct seq_file *m, void *arg)
1826 /*
1827 * This walks the free areas for each zone.
1828 */
1829 static int frag_show(struct seq_file *m, void *arg)
1831 pg_data_t *pgdat = (pg_data_t *)arg;
1832 struct zone *zone;
1833 struct zone *node_zones = pgdat->node_zones;
1834 unsigned long flags;
1835 int order;
1837 for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
1838 if (!zone->present_pages)
1839 continue;
1841 spin_lock_irqsave(&zone->lock, flags);
1842 seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1843 for (order = 0; order < MAX_ORDER; ++order)
1844 seq_printf(m, "%6lu ", zone->free_area[order].nr_free);
1845 spin_unlock_irqrestore(&zone->lock, flags);
1846 seq_putc(m, '\n');
1848 return 0;
1851 struct seq_operations fragmentation_op = {
1852 .start = frag_start,
1853 .next = frag_next,
1854 .stop = frag_stop,
1855 .show = frag_show,
1856 };
1858 static char *vmstat_text[] = {
1859 "nr_dirty",
1860 "nr_writeback",
1861 "nr_unstable",
1862 "nr_page_table_pages",
1863 "nr_mapped",
1864 "nr_slab",
1866 "pgpgin",
1867 "pgpgout",
1868 "pswpin",
1869 "pswpout",
1870 "pgalloc_high",
1872 "pgalloc_normal",
1873 "pgalloc_dma",
1874 "pgfree",
1875 "pgactivate",
1876 "pgdeactivate",
1878 "pgfault",
1879 "pgmajfault",
1880 "pgrefill_high",
1881 "pgrefill_normal",
1882 "pgrefill_dma",
1884 "pgsteal_high",
1885 "pgsteal_normal",
1886 "pgsteal_dma",
1887 "pgscan_kswapd_high",
1888 "pgscan_kswapd_normal",
1890 "pgscan_kswapd_dma",
1891 "pgscan_direct_high",
1892 "pgscan_direct_normal",
1893 "pgscan_direct_dma",
1894 "pginodesteal",
1896 "slabs_scanned",
1897 "kswapd_steal",
1898 "kswapd_inodesteal",
1899 "pageoutrun",
1900 "allocstall",
1902 "pgrotated",
1903 "nr_bounce",
1904 };
1906 static void *vmstat_start(struct seq_file *m, loff_t *pos)
1908 struct page_state *ps;
1910 if (*pos >= ARRAY_SIZE(vmstat_text))
1911 return NULL;
1913 ps = kmalloc(sizeof(*ps), GFP_KERNEL);
1914 m->private = ps;
1915 if (!ps)
1916 return ERR_PTR(-ENOMEM);
1917 get_full_page_state(ps);
1918 ps->pgpgin /= 2; /* sectors -> kbytes */
1919 ps->pgpgout /= 2;
1920 return (unsigned long *)ps + *pos;
1923 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
1925 (*pos)++;
1926 if (*pos >= ARRAY_SIZE(vmstat_text))
1927 return NULL;
1928 return (unsigned long *)m->private + *pos;
1931 static int vmstat_show(struct seq_file *m, void *arg)
1933 unsigned long *l = arg;
1934 unsigned long off = l - (unsigned long *)m->private;
1936 seq_printf(m, "%s %lu\n", vmstat_text[off], *l);
1937 return 0;
1940 static void vmstat_stop(struct seq_file *m, void *arg)
1942 kfree(m->private);
1943 m->private = NULL;
1946 struct seq_operations vmstat_op = {
1947 .start = vmstat_start,
1948 .next = vmstat_next,
1949 .stop = vmstat_stop,
1950 .show = vmstat_show,
1951 };
1953 #endif /* CONFIG_PROC_FS */
1955 #ifdef CONFIG_HOTPLUG_CPU
1956 static int page_alloc_cpu_notify(struct notifier_block *self,
1957 unsigned long action, void *hcpu)
1959 int cpu = (unsigned long)hcpu;
1960 long *count;
1961 unsigned long *src, *dest;
1963 if (action == CPU_DEAD) {
1964 int i;
1966 /* Drain local pagecache count. */
1967 count = &per_cpu(nr_pagecache_local, cpu);
1968 atomic_add(*count, &nr_pagecache);
1969 *count = 0;
1970 local_irq_disable();
1971 __drain_pages(cpu);
1973 /* Add dead cpu's page_states to our own. */
1974 dest = (unsigned long *)&__get_cpu_var(page_states);
1975 src = (unsigned long *)&per_cpu(page_states, cpu);
1977 for (i = 0; i < sizeof(struct page_state)/sizeof(unsigned long);
1978 i++) {
1979 dest[i] += src[i];
1980 src[i] = 0;
1983 local_irq_enable();
1985 return NOTIFY_OK;
1987 #endif /* CONFIG_HOTPLUG_CPU */
1989 void __init page_alloc_init(void)
1991 hotcpu_notifier(page_alloc_cpu_notify, 0);
1994 /*
1995 * setup_per_zone_lowmem_reserve - called whenever
1996 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
1997 * has a correct pages reserved value, so an adequate number of
1998 * pages are left in the zone after a successful __alloc_pages().
1999 */
2000 static void setup_per_zone_lowmem_reserve(void)
2002 struct pglist_data *pgdat;
2003 int j, idx;
2005 for_each_pgdat(pgdat) {
2006 for (j = 0; j < MAX_NR_ZONES; j++) {
2007 struct zone *zone = pgdat->node_zones + j;
2008 unsigned long present_pages = zone->present_pages;
2010 zone->lowmem_reserve[j] = 0;
2012 for (idx = j-1; idx >= 0; idx--) {
2013 struct zone *lower_zone;
2015 if (sysctl_lowmem_reserve_ratio[idx] < 1)
2016 sysctl_lowmem_reserve_ratio[idx] = 1;
2018 lower_zone = pgdat->node_zones + idx;
2019 lower_zone->lowmem_reserve[j] = present_pages /
2020 sysctl_lowmem_reserve_ratio[idx];
2021 present_pages += lower_zone->present_pages;
2027 /*
2028 * setup_per_zone_pages_min - called when min_free_kbytes changes. Ensures
2029 * that the pages_{min,low,high} values for each zone are set correctly
2030 * with respect to min_free_kbytes.
2031 */
2032 static void setup_per_zone_pages_min(void)
2034 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
2035 unsigned long lowmem_pages = 0;
2036 struct zone *zone;
2037 unsigned long flags;
2039 /* Calculate total number of !ZONE_HIGHMEM pages */
2040 for_each_zone(zone) {
2041 if (!is_highmem(zone))
2042 lowmem_pages += zone->present_pages;
2045 for_each_zone(zone) {
2046 spin_lock_irqsave(&zone->lru_lock, flags);
2047 if (is_highmem(zone)) {
2048 /*
2049 * Often, highmem doesn't need to reserve any pages.
2050 * But the pages_min/low/high values are also used for
2051 * batching up page reclaim activity so we need a
2052 * decent value here.
2053 */
2054 int min_pages;
2056 min_pages = zone->present_pages / 1024;
2057 if (min_pages < SWAP_CLUSTER_MAX)
2058 min_pages = SWAP_CLUSTER_MAX;
2059 if (min_pages > 128)
2060 min_pages = 128;
2061 zone->pages_min = min_pages;
2062 } else {
2063 /* if it's a lowmem zone, reserve a number of pages
2064 * proportionate to the zone's size.
2065 */
2066 zone->pages_min = (pages_min * zone->present_pages) /
2067 lowmem_pages;
2070 /*
2071 * When interpreting these watermarks, just keep in mind that:
2072 * zone->pages_min == (zone->pages_min * 4) / 4;
2073 */
2074 zone->pages_low = (zone->pages_min * 5) / 4;
2075 zone->pages_high = (zone->pages_min * 6) / 4;
2076 spin_unlock_irqrestore(&zone->lru_lock, flags);
2080 /*
2081 * Initialise min_free_kbytes.
2083 * For small machines we want it small (128k min). For large machines
2084 * we want it large (64MB max). But it is not linear, because network
2085 * bandwidth does not increase linearly with machine size. We use
2087 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
2088 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
2090 * which yields
2092 * 16MB: 512k
2093 * 32MB: 724k
2094 * 64MB: 1024k
2095 * 128MB: 1448k
2096 * 256MB: 2048k
2097 * 512MB: 2896k
2098 * 1024MB: 4096k
2099 * 2048MB: 5792k
2100 * 4096MB: 8192k
2101 * 8192MB: 11584k
2102 * 16384MB: 16384k
2103 */
2104 static int __init init_per_zone_pages_min(void)
2106 unsigned long lowmem_kbytes;
2108 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
2110 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
2111 if (min_free_kbytes < 128)
2112 min_free_kbytes = 128;
2113 if (min_free_kbytes > 65536)
2114 min_free_kbytes = 65536;
2115 setup_per_zone_pages_min();
2116 setup_per_zone_lowmem_reserve();
2117 return 0;
2119 module_init(init_per_zone_pages_min)
2121 /*
2122 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
2123 * that we can call two helper functions whenever min_free_kbytes
2124 * changes.
2125 */
2126 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
2127 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2129 proc_dointvec(table, write, file, buffer, length, ppos);
2130 setup_per_zone_pages_min();
2131 return 0;
2134 /*
2135 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
2136 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
2137 * whenever sysctl_lowmem_reserve_ratio changes.
2139 * The reserve ratio obviously has absolutely no relation with the
2140 * pages_min watermarks. The lowmem reserve ratio can only make sense
2141 * if in function of the boot time zone sizes.
2142 */
2143 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
2144 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2146 proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2147 setup_per_zone_lowmem_reserve();
2148 return 0;
2151 __initdata int hashdist = HASHDIST_DEFAULT;
2153 #ifdef CONFIG_NUMA
2154 static int __init set_hashdist(char *str)
2156 if (!str)
2157 return 0;
2158 hashdist = simple_strtoul(str, &str, 0);
2159 return 1;
2161 __setup("hashdist=", set_hashdist);
2162 #endif
2164 /*
2165 * allocate a large system hash table from bootmem
2166 * - it is assumed that the hash table must contain an exact power-of-2
2167 * quantity of entries
2168 * - limit is the number of hash buckets, not the total allocation size
2169 */
2170 void *__init alloc_large_system_hash(const char *tablename,
2171 unsigned long bucketsize,
2172 unsigned long numentries,
2173 int scale,
2174 int flags,
2175 unsigned int *_hash_shift,
2176 unsigned int *_hash_mask,
2177 unsigned long limit)
2179 unsigned long long max = limit;
2180 unsigned long log2qty, size;
2181 void *table = NULL;
2183 /* allow the kernel cmdline to have a say */
2184 if (!numentries) {
2185 /* round applicable memory size up to nearest megabyte */
2186 numentries = (flags & HASH_HIGHMEM) ? nr_all_pages : nr_kernel_pages;
2187 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2188 numentries >>= 20 - PAGE_SHIFT;
2189 numentries <<= 20 - PAGE_SHIFT;
2191 /* limit to 1 bucket per 2^scale bytes of low memory */
2192 if (scale > PAGE_SHIFT)
2193 numentries >>= (scale - PAGE_SHIFT);
2194 else
2195 numentries <<= (PAGE_SHIFT - scale);
2197 /* rounded up to nearest power of 2 in size */
2198 numentries = 1UL << (long_log2(numentries) + 1);
2200 /* limit allocation size to 1/16 total memory by default */
2201 if (max == 0) {
2202 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2203 do_div(max, bucketsize);
2206 if (numentries > max)
2207 numentries = max;
2209 log2qty = long_log2(numentries);
2211 do {
2212 size = bucketsize << log2qty;
2213 if (flags & HASH_EARLY)
2214 table = alloc_bootmem(size);
2215 else if (hashdist)
2216 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
2217 else {
2218 unsigned long order;
2219 for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
2221 table = (void*) __get_free_pages(GFP_ATOMIC, order);
2223 } while (!table && size > PAGE_SIZE && --log2qty);
2225 if (!table)
2226 panic("Failed to allocate %s hash table\n", tablename);
2228 printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2229 tablename,
2230 (1U << log2qty),
2231 long_log2(size) - PAGE_SHIFT,
2232 size);
2234 if (_hash_shift)
2235 *_hash_shift = log2qty;
2236 if (_hash_mask)
2237 *_hash_mask = (1 << log2qty) - 1;
2239 return table;