mm: report the pagesize backing a VMA in /proc/pid/smaps
[linux-2.6.git] / mm / hugetlb.c
1 /*
2  * Generic hugetlb support.
3  * (C) William Irwin, April 2004
4  */
5 #include <linux/gfp.h>
6 #include <linux/list.h>
7 #include <linux/init.h>
8 #include <linux/module.h>
9 #include <linux/mm.h>
10 #include <linux/seq_file.h>
11 #include <linux/sysctl.h>
12 #include <linux/highmem.h>
13 #include <linux/mmu_notifier.h>
14 #include <linux/nodemask.h>
15 #include <linux/pagemap.h>
16 #include <linux/mempolicy.h>
17 #include <linux/cpuset.h>
18 #include <linux/mutex.h>
19 #include <linux/bootmem.h>
20 #include <linux/sysfs.h>
21
22 #include <asm/page.h>
23 #include <asm/pgtable.h>
24 #include <asm/io.h>
25
26 #include <linux/hugetlb.h>
27 #include "internal.h"
28
29 const unsigned long hugetlb_zero = 0, hugetlb_infinity = ~0UL;
30 static gfp_t htlb_alloc_mask = GFP_HIGHUSER;
31 unsigned long hugepages_treat_as_movable;
32
33 static int max_hstate;
34 unsigned int default_hstate_idx;
35 struct hstate hstates[HUGE_MAX_HSTATE];
36
37 __initdata LIST_HEAD(huge_boot_pages);
38
39 /* for command line parsing */
40 static struct hstate * __initdata parsed_hstate;
41 static unsigned long __initdata default_hstate_max_huge_pages;
42 static unsigned long __initdata default_hstate_size;
43
44 #define for_each_hstate(h) \
45         for ((h) = hstates; (h) < &hstates[max_hstate]; (h)++)
46
47 /*
48  * Protects updates to hugepage_freelists, nr_huge_pages, and free_huge_pages
49  */
50 static DEFINE_SPINLOCK(hugetlb_lock);
51
52 /*
53  * Region tracking -- allows tracking of reservations and instantiated pages
54  *                    across the pages in a mapping.
55  *
56  * The region data structures are protected by a combination of the mmap_sem
57  * and the hugetlb_instantion_mutex.  To access or modify a region the caller
58  * must either hold the mmap_sem for write, or the mmap_sem for read and
59  * the hugetlb_instantiation mutex:
60  *
61  *      down_write(&mm->mmap_sem);
62  * or
63  *      down_read(&mm->mmap_sem);
64  *      mutex_lock(&hugetlb_instantiation_mutex);
65  */
66 struct file_region {
67         struct list_head link;
68         long from;
69         long to;
70 };
71
72 static long region_add(struct list_head *head, long f, long t)
73 {
74         struct file_region *rg, *nrg, *trg;
75
76         /* Locate the region we are either in or before. */
77         list_for_each_entry(rg, head, link)
78                 if (f <= rg->to)
79                         break;
80
81         /* Round our left edge to the current segment if it encloses us. */
82         if (f > rg->from)
83                 f = rg->from;
84
85         /* Check for and consume any regions we now overlap with. */
86         nrg = rg;
87         list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
88                 if (&rg->link == head)
89                         break;
90                 if (rg->from > t)
91                         break;
92
93                 /* If this area reaches higher then extend our area to
94                  * include it completely.  If this is not the first area
95                  * which we intend to reuse, free it. */
96                 if (rg->to > t)
97                         t = rg->to;
98                 if (rg != nrg) {
99                         list_del(&rg->link);
100                         kfree(rg);
101                 }
102         }
103         nrg->from = f;
104         nrg->to = t;
105         return 0;
106 }
107
108 static long region_chg(struct list_head *head, long f, long t)
109 {
110         struct file_region *rg, *nrg;
111         long chg = 0;
112
113         /* Locate the region we are before or in. */
114         list_for_each_entry(rg, head, link)
115                 if (f <= rg->to)
116                         break;
117
118         /* If we are below the current region then a new region is required.
119          * Subtle, allocate a new region at the position but make it zero
120          * size such that we can guarantee to record the reservation. */
121         if (&rg->link == head || t < rg->from) {
122                 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
123                 if (!nrg)
124                         return -ENOMEM;
125                 nrg->from = f;
126                 nrg->to   = f;
127                 INIT_LIST_HEAD(&nrg->link);
128                 list_add(&nrg->link, rg->link.prev);
129
130                 return t - f;
131         }
132
133         /* Round our left edge to the current segment if it encloses us. */
134         if (f > rg->from)
135                 f = rg->from;
136         chg = t - f;
137
138         /* Check for and consume any regions we now overlap with. */
139         list_for_each_entry(rg, rg->link.prev, link) {
140                 if (&rg->link == head)
141                         break;
142                 if (rg->from > t)
143                         return chg;
144
145                 /* We overlap with this area, if it extends futher than
146                  * us then we must extend ourselves.  Account for its
147                  * existing reservation. */
148                 if (rg->to > t) {
149                         chg += rg->to - t;
150                         t = rg->to;
151                 }
152                 chg -= rg->to - rg->from;
153         }
154         return chg;
155 }
156
157 static long region_truncate(struct list_head *head, long end)
158 {
159         struct file_region *rg, *trg;
160         long chg = 0;
161
162         /* Locate the region we are either in or before. */
163         list_for_each_entry(rg, head, link)
164                 if (end <= rg->to)
165                         break;
166         if (&rg->link == head)
167                 return 0;
168
169         /* If we are in the middle of a region then adjust it. */
170         if (end > rg->from) {
171                 chg = rg->to - end;
172                 rg->to = end;
173                 rg = list_entry(rg->link.next, typeof(*rg), link);
174         }
175
176         /* Drop any remaining regions. */
177         list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
178                 if (&rg->link == head)
179                         break;
180                 chg += rg->to - rg->from;
181                 list_del(&rg->link);
182                 kfree(rg);
183         }
184         return chg;
185 }
186
187 static long region_count(struct list_head *head, long f, long t)
188 {
189         struct file_region *rg;
190         long chg = 0;
191
192         /* Locate each segment we overlap with, and count that overlap. */
193         list_for_each_entry(rg, head, link) {
194                 int seg_from;
195                 int seg_to;
196
197                 if (rg->to <= f)
198                         continue;
199                 if (rg->from >= t)
200                         break;
201
202                 seg_from = max(rg->from, f);
203                 seg_to = min(rg->to, t);
204
205                 chg += seg_to - seg_from;
206         }
207
208         return chg;
209 }
210
211 /*
212  * Convert the address within this vma to the page offset within
213  * the mapping, in pagecache page units; huge pages here.
214  */
215 static pgoff_t vma_hugecache_offset(struct hstate *h,
216                         struct vm_area_struct *vma, unsigned long address)
217 {
218         return ((address - vma->vm_start) >> huge_page_shift(h)) +
219                         (vma->vm_pgoff >> huge_page_order(h));
220 }
221
222 /*
223  * Return the size of the pages allocated when backing a VMA. In the majority
224  * cases this will be same size as used by the page table entries.
225  */
226 unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
227 {
228         struct hstate *hstate;
229
230         if (!is_vm_hugetlb_page(vma))
231                 return PAGE_SIZE;
232
233         hstate = hstate_vma(vma);
234
235         return 1UL << (hstate->order + PAGE_SHIFT);
236 }
237
238 /*
239  * Flags for MAP_PRIVATE reservations.  These are stored in the bottom
240  * bits of the reservation map pointer, which are always clear due to
241  * alignment.
242  */
243 #define HPAGE_RESV_OWNER    (1UL << 0)
244 #define HPAGE_RESV_UNMAPPED (1UL << 1)
245 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
246
247 /*
248  * These helpers are used to track how many pages are reserved for
249  * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
250  * is guaranteed to have their future faults succeed.
251  *
252  * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
253  * the reserve counters are updated with the hugetlb_lock held. It is safe
254  * to reset the VMA at fork() time as it is not in use yet and there is no
255  * chance of the global counters getting corrupted as a result of the values.
256  *
257  * The private mapping reservation is represented in a subtly different
258  * manner to a shared mapping.  A shared mapping has a region map associated
259  * with the underlying file, this region map represents the backing file
260  * pages which have ever had a reservation assigned which this persists even
261  * after the page is instantiated.  A private mapping has a region map
262  * associated with the original mmap which is attached to all VMAs which
263  * reference it, this region map represents those offsets which have consumed
264  * reservation ie. where pages have been instantiated.
265  */
266 static unsigned long get_vma_private_data(struct vm_area_struct *vma)
267 {
268         return (unsigned long)vma->vm_private_data;
269 }
270
271 static void set_vma_private_data(struct vm_area_struct *vma,
272                                                         unsigned long value)
273 {
274         vma->vm_private_data = (void *)value;
275 }
276
277 struct resv_map {
278         struct kref refs;
279         struct list_head regions;
280 };
281
282 static struct resv_map *resv_map_alloc(void)
283 {
284         struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
285         if (!resv_map)
286                 return NULL;
287
288         kref_init(&resv_map->refs);
289         INIT_LIST_HEAD(&resv_map->regions);
290
291         return resv_map;
292 }
293
294 static void resv_map_release(struct kref *ref)
295 {
296         struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
297
298         /* Clear out any active regions before we release the map. */
299         region_truncate(&resv_map->regions, 0);
300         kfree(resv_map);
301 }
302
303 static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
304 {
305         VM_BUG_ON(!is_vm_hugetlb_page(vma));
306         if (!(vma->vm_flags & VM_SHARED))
307                 return (struct resv_map *)(get_vma_private_data(vma) &
308                                                         ~HPAGE_RESV_MASK);
309         return NULL;
310 }
311
312 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
313 {
314         VM_BUG_ON(!is_vm_hugetlb_page(vma));
315         VM_BUG_ON(vma->vm_flags & VM_SHARED);
316
317         set_vma_private_data(vma, (get_vma_private_data(vma) &
318                                 HPAGE_RESV_MASK) | (unsigned long)map);
319 }
320
321 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
322 {
323         VM_BUG_ON(!is_vm_hugetlb_page(vma));
324         VM_BUG_ON(vma->vm_flags & VM_SHARED);
325
326         set_vma_private_data(vma, get_vma_private_data(vma) | flags);
327 }
328
329 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
330 {
331         VM_BUG_ON(!is_vm_hugetlb_page(vma));
332
333         return (get_vma_private_data(vma) & flag) != 0;
334 }
335
336 /* Decrement the reserved pages in the hugepage pool by one */
337 static void decrement_hugepage_resv_vma(struct hstate *h,
338                         struct vm_area_struct *vma)
339 {
340         if (vma->vm_flags & VM_NORESERVE)
341                 return;
342
343         if (vma->vm_flags & VM_SHARED) {
344                 /* Shared mappings always use reserves */
345                 h->resv_huge_pages--;
346         } else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
347                 /*
348                  * Only the process that called mmap() has reserves for
349                  * private mappings.
350                  */
351                 h->resv_huge_pages--;
352         }
353 }
354
355 /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
356 void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
357 {
358         VM_BUG_ON(!is_vm_hugetlb_page(vma));
359         if (!(vma->vm_flags & VM_SHARED))
360                 vma->vm_private_data = (void *)0;
361 }
362
363 /* Returns true if the VMA has associated reserve pages */
364 static int vma_has_reserves(struct vm_area_struct *vma)
365 {
366         if (vma->vm_flags & VM_SHARED)
367                 return 1;
368         if (is_vma_resv_set(vma, HPAGE_RESV_OWNER))
369                 return 1;
370         return 0;
371 }
372
373 static void clear_gigantic_page(struct page *page,
374                         unsigned long addr, unsigned long sz)
375 {
376         int i;
377         struct page *p = page;
378
379         might_sleep();
380         for (i = 0; i < sz/PAGE_SIZE; i++, p = mem_map_next(p, page, i)) {
381                 cond_resched();
382                 clear_user_highpage(p, addr + i * PAGE_SIZE);
383         }
384 }
385 static void clear_huge_page(struct page *page,
386                         unsigned long addr, unsigned long sz)
387 {
388         int i;
389
390         if (unlikely(sz > MAX_ORDER_NR_PAGES))
391                 return clear_gigantic_page(page, addr, sz);
392
393         might_sleep();
394         for (i = 0; i < sz/PAGE_SIZE; i++) {
395                 cond_resched();
396                 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
397         }
398 }
399
400 static void copy_gigantic_page(struct page *dst, struct page *src,
401                            unsigned long addr, struct vm_area_struct *vma)
402 {
403         int i;
404         struct hstate *h = hstate_vma(vma);
405         struct page *dst_base = dst;
406         struct page *src_base = src;
407         might_sleep();
408         for (i = 0; i < pages_per_huge_page(h); ) {
409                 cond_resched();
410                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
411
412                 i++;
413                 dst = mem_map_next(dst, dst_base, i);
414                 src = mem_map_next(src, src_base, i);
415         }
416 }
417 static void copy_huge_page(struct page *dst, struct page *src,
418                            unsigned long addr, struct vm_area_struct *vma)
419 {
420         int i;
421         struct hstate *h = hstate_vma(vma);
422
423         if (unlikely(pages_per_huge_page(h) > MAX_ORDER_NR_PAGES))
424                 return copy_gigantic_page(dst, src, addr, vma);
425
426         might_sleep();
427         for (i = 0; i < pages_per_huge_page(h); i++) {
428                 cond_resched();
429                 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
430         }
431 }
432
433 static void enqueue_huge_page(struct hstate *h, struct page *page)
434 {
435         int nid = page_to_nid(page);
436         list_add(&page->lru, &h->hugepage_freelists[nid]);
437         h->free_huge_pages++;
438         h->free_huge_pages_node[nid]++;
439 }
440
441 static struct page *dequeue_huge_page(struct hstate *h)
442 {
443         int nid;
444         struct page *page = NULL;
445
446         for (nid = 0; nid < MAX_NUMNODES; ++nid) {
447                 if (!list_empty(&h->hugepage_freelists[nid])) {
448                         page = list_entry(h->hugepage_freelists[nid].next,
449                                           struct page, lru);
450                         list_del(&page->lru);
451                         h->free_huge_pages--;
452                         h->free_huge_pages_node[nid]--;
453                         break;
454                 }
455         }
456         return page;
457 }
458
459 static struct page *dequeue_huge_page_vma(struct hstate *h,
460                                 struct vm_area_struct *vma,
461                                 unsigned long address, int avoid_reserve)
462 {
463         int nid;
464         struct page *page = NULL;
465         struct mempolicy *mpol;
466         nodemask_t *nodemask;
467         struct zonelist *zonelist = huge_zonelist(vma, address,
468                                         htlb_alloc_mask, &mpol, &nodemask);
469         struct zone *zone;
470         struct zoneref *z;
471
472         /*
473          * A child process with MAP_PRIVATE mappings created by their parent
474          * have no page reserves. This check ensures that reservations are
475          * not "stolen". The child may still get SIGKILLed
476          */
477         if (!vma_has_reserves(vma) &&
478                         h->free_huge_pages - h->resv_huge_pages == 0)
479                 return NULL;
480
481         /* If reserves cannot be used, ensure enough pages are in the pool */
482         if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
483                 return NULL;
484
485         for_each_zone_zonelist_nodemask(zone, z, zonelist,
486                                                 MAX_NR_ZONES - 1, nodemask) {
487                 nid = zone_to_nid(zone);
488                 if (cpuset_zone_allowed_softwall(zone, htlb_alloc_mask) &&
489                     !list_empty(&h->hugepage_freelists[nid])) {
490                         page = list_entry(h->hugepage_freelists[nid].next,
491                                           struct page, lru);
492                         list_del(&page->lru);
493                         h->free_huge_pages--;
494                         h->free_huge_pages_node[nid]--;
495
496                         if (!avoid_reserve)
497                                 decrement_hugepage_resv_vma(h, vma);
498
499                         break;
500                 }
501         }
502         mpol_cond_put(mpol);
503         return page;
504 }
505
506 static void update_and_free_page(struct hstate *h, struct page *page)
507 {
508         int i;
509
510         VM_BUG_ON(h->order >= MAX_ORDER);
511
512         h->nr_huge_pages--;
513         h->nr_huge_pages_node[page_to_nid(page)]--;
514         for (i = 0; i < pages_per_huge_page(h); i++) {
515                 page[i].flags &= ~(1 << PG_locked | 1 << PG_error | 1 << PG_referenced |
516                                 1 << PG_dirty | 1 << PG_active | 1 << PG_reserved |
517                                 1 << PG_private | 1<< PG_writeback);
518         }
519         set_compound_page_dtor(page, NULL);
520         set_page_refcounted(page);
521         arch_release_hugepage(page);
522         __free_pages(page, huge_page_order(h));
523 }
524
525 struct hstate *size_to_hstate(unsigned long size)
526 {
527         struct hstate *h;
528
529         for_each_hstate(h) {
530                 if (huge_page_size(h) == size)
531                         return h;
532         }
533         return NULL;
534 }
535
536 static void free_huge_page(struct page *page)
537 {
538         /*
539          * Can't pass hstate in here because it is called from the
540          * compound page destructor.
541          */
542         struct hstate *h = page_hstate(page);
543         int nid = page_to_nid(page);
544         struct address_space *mapping;
545
546         mapping = (struct address_space *) page_private(page);
547         set_page_private(page, 0);
548         BUG_ON(page_count(page));
549         INIT_LIST_HEAD(&page->lru);
550
551         spin_lock(&hugetlb_lock);
552         if (h->surplus_huge_pages_node[nid] && huge_page_order(h) < MAX_ORDER) {
553                 update_and_free_page(h, page);
554                 h->surplus_huge_pages--;
555                 h->surplus_huge_pages_node[nid]--;
556         } else {
557                 enqueue_huge_page(h, page);
558         }
559         spin_unlock(&hugetlb_lock);
560         if (mapping)
561                 hugetlb_put_quota(mapping, 1);
562 }
563
564 /*
565  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
566  * balanced by operating on them in a round-robin fashion.
567  * Returns 1 if an adjustment was made.
568  */
569 static int adjust_pool_surplus(struct hstate *h, int delta)
570 {
571         static int prev_nid;
572         int nid = prev_nid;
573         int ret = 0;
574
575         VM_BUG_ON(delta != -1 && delta != 1);
576         do {
577                 nid = next_node(nid, node_online_map);
578                 if (nid == MAX_NUMNODES)
579                         nid = first_node(node_online_map);
580
581                 /* To shrink on this node, there must be a surplus page */
582                 if (delta < 0 && !h->surplus_huge_pages_node[nid])
583                         continue;
584                 /* Surplus cannot exceed the total number of pages */
585                 if (delta > 0 && h->surplus_huge_pages_node[nid] >=
586                                                 h->nr_huge_pages_node[nid])
587                         continue;
588
589                 h->surplus_huge_pages += delta;
590                 h->surplus_huge_pages_node[nid] += delta;
591                 ret = 1;
592                 break;
593         } while (nid != prev_nid);
594
595         prev_nid = nid;
596         return ret;
597 }
598
599 static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
600 {
601         set_compound_page_dtor(page, free_huge_page);
602         spin_lock(&hugetlb_lock);
603         h->nr_huge_pages++;
604         h->nr_huge_pages_node[nid]++;
605         spin_unlock(&hugetlb_lock);
606         put_page(page); /* free it into the hugepage allocator */
607 }
608
609 static struct page *alloc_fresh_huge_page_node(struct hstate *h, int nid)
610 {
611         struct page *page;
612
613         if (h->order >= MAX_ORDER)
614                 return NULL;
615
616         page = alloc_pages_node(nid,
617                 htlb_alloc_mask|__GFP_COMP|__GFP_THISNODE|
618                                                 __GFP_REPEAT|__GFP_NOWARN,
619                 huge_page_order(h));
620         if (page) {
621                 if (arch_prepare_hugepage(page)) {
622                         __free_pages(page, huge_page_order(h));
623                         return NULL;
624                 }
625                 prep_new_huge_page(h, page, nid);
626         }
627
628         return page;
629 }
630
631 /*
632  * Use a helper variable to find the next node and then
633  * copy it back to hugetlb_next_nid afterwards:
634  * otherwise there's a window in which a racer might
635  * pass invalid nid MAX_NUMNODES to alloc_pages_node.
636  * But we don't need to use a spin_lock here: it really
637  * doesn't matter if occasionally a racer chooses the
638  * same nid as we do.  Move nid forward in the mask even
639  * if we just successfully allocated a hugepage so that
640  * the next caller gets hugepages on the next node.
641  */
642 static int hstate_next_node(struct hstate *h)
643 {
644         int next_nid;
645         next_nid = next_node(h->hugetlb_next_nid, node_online_map);
646         if (next_nid == MAX_NUMNODES)
647                 next_nid = first_node(node_online_map);
648         h->hugetlb_next_nid = next_nid;
649         return next_nid;
650 }
651
652 static int alloc_fresh_huge_page(struct hstate *h)
653 {
654         struct page *page;
655         int start_nid;
656         int next_nid;
657         int ret = 0;
658
659         start_nid = h->hugetlb_next_nid;
660
661         do {
662                 page = alloc_fresh_huge_page_node(h, h->hugetlb_next_nid);
663                 if (page)
664                         ret = 1;
665                 next_nid = hstate_next_node(h);
666         } while (!page && h->hugetlb_next_nid != start_nid);
667
668         if (ret)
669                 count_vm_event(HTLB_BUDDY_PGALLOC);
670         else
671                 count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
672
673         return ret;
674 }
675
676 static struct page *alloc_buddy_huge_page(struct hstate *h,
677                         struct vm_area_struct *vma, unsigned long address)
678 {
679         struct page *page;
680         unsigned int nid;
681
682         if (h->order >= MAX_ORDER)
683                 return NULL;
684
685         /*
686          * Assume we will successfully allocate the surplus page to
687          * prevent racing processes from causing the surplus to exceed
688          * overcommit
689          *
690          * This however introduces a different race, where a process B
691          * tries to grow the static hugepage pool while alloc_pages() is
692          * called by process A. B will only examine the per-node
693          * counters in determining if surplus huge pages can be
694          * converted to normal huge pages in adjust_pool_surplus(). A
695          * won't be able to increment the per-node counter, until the
696          * lock is dropped by B, but B doesn't drop hugetlb_lock until
697          * no more huge pages can be converted from surplus to normal
698          * state (and doesn't try to convert again). Thus, we have a
699          * case where a surplus huge page exists, the pool is grown, and
700          * the surplus huge page still exists after, even though it
701          * should just have been converted to a normal huge page. This
702          * does not leak memory, though, as the hugepage will be freed
703          * once it is out of use. It also does not allow the counters to
704          * go out of whack in adjust_pool_surplus() as we don't modify
705          * the node values until we've gotten the hugepage and only the
706          * per-node value is checked there.
707          */
708         spin_lock(&hugetlb_lock);
709         if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
710                 spin_unlock(&hugetlb_lock);
711                 return NULL;
712         } else {
713                 h->nr_huge_pages++;
714                 h->surplus_huge_pages++;
715         }
716         spin_unlock(&hugetlb_lock);
717
718         page = alloc_pages(htlb_alloc_mask|__GFP_COMP|
719                                         __GFP_REPEAT|__GFP_NOWARN,
720                                         huge_page_order(h));
721
722         if (page && arch_prepare_hugepage(page)) {
723                 __free_pages(page, huge_page_order(h));
724                 return NULL;
725         }
726
727         spin_lock(&hugetlb_lock);
728         if (page) {
729                 /*
730                  * This page is now managed by the hugetlb allocator and has
731                  * no users -- drop the buddy allocator's reference.
732                  */
733                 put_page_testzero(page);
734                 VM_BUG_ON(page_count(page));
735                 nid = page_to_nid(page);
736                 set_compound_page_dtor(page, free_huge_page);
737                 /*
738                  * We incremented the global counters already
739                  */
740                 h->nr_huge_pages_node[nid]++;
741                 h->surplus_huge_pages_node[nid]++;
742                 __count_vm_event(HTLB_BUDDY_PGALLOC);
743         } else {
744                 h->nr_huge_pages--;
745                 h->surplus_huge_pages--;
746                 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
747         }
748         spin_unlock(&hugetlb_lock);
749
750         return page;
751 }
752
753 /*
754  * Increase the hugetlb pool such that it can accomodate a reservation
755  * of size 'delta'.
756  */
757 static int gather_surplus_pages(struct hstate *h, int delta)
758 {
759         struct list_head surplus_list;
760         struct page *page, *tmp;
761         int ret, i;
762         int needed, allocated;
763
764         needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
765         if (needed <= 0) {
766                 h->resv_huge_pages += delta;
767                 return 0;
768         }
769
770         allocated = 0;
771         INIT_LIST_HEAD(&surplus_list);
772
773         ret = -ENOMEM;
774 retry:
775         spin_unlock(&hugetlb_lock);
776         for (i = 0; i < needed; i++) {
777                 page = alloc_buddy_huge_page(h, NULL, 0);
778                 if (!page) {
779                         /*
780                          * We were not able to allocate enough pages to
781                          * satisfy the entire reservation so we free what
782                          * we've allocated so far.
783                          */
784                         spin_lock(&hugetlb_lock);
785                         needed = 0;
786                         goto free;
787                 }
788
789                 list_add(&page->lru, &surplus_list);
790         }
791         allocated += needed;
792
793         /*
794          * After retaking hugetlb_lock, we need to recalculate 'needed'
795          * because either resv_huge_pages or free_huge_pages may have changed.
796          */
797         spin_lock(&hugetlb_lock);
798         needed = (h->resv_huge_pages + delta) -
799                         (h->free_huge_pages + allocated);
800         if (needed > 0)
801                 goto retry;
802
803         /*
804          * The surplus_list now contains _at_least_ the number of extra pages
805          * needed to accomodate the reservation.  Add the appropriate number
806          * of pages to the hugetlb pool and free the extras back to the buddy
807          * allocator.  Commit the entire reservation here to prevent another
808          * process from stealing the pages as they are added to the pool but
809          * before they are reserved.
810          */
811         needed += allocated;
812         h->resv_huge_pages += delta;
813         ret = 0;
814 free:
815         /* Free the needed pages to the hugetlb pool */
816         list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
817                 if ((--needed) < 0)
818                         break;
819                 list_del(&page->lru);
820                 enqueue_huge_page(h, page);
821         }
822
823         /* Free unnecessary surplus pages to the buddy allocator */
824         if (!list_empty(&surplus_list)) {
825                 spin_unlock(&hugetlb_lock);
826                 list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
827                         list_del(&page->lru);
828                         /*
829                          * The page has a reference count of zero already, so
830                          * call free_huge_page directly instead of using
831                          * put_page.  This must be done with hugetlb_lock
832                          * unlocked which is safe because free_huge_page takes
833                          * hugetlb_lock before deciding how to free the page.
834                          */
835                         free_huge_page(page);
836                 }
837                 spin_lock(&hugetlb_lock);
838         }
839
840         return ret;
841 }
842
843 /*
844  * When releasing a hugetlb pool reservation, any surplus pages that were
845  * allocated to satisfy the reservation must be explicitly freed if they were
846  * never used.
847  */
848 static void return_unused_surplus_pages(struct hstate *h,
849                                         unsigned long unused_resv_pages)
850 {
851         static int nid = -1;
852         struct page *page;
853         unsigned long nr_pages;
854
855         /*
856          * We want to release as many surplus pages as possible, spread
857          * evenly across all nodes. Iterate across all nodes until we
858          * can no longer free unreserved surplus pages. This occurs when
859          * the nodes with surplus pages have no free pages.
860          */
861         unsigned long remaining_iterations = num_online_nodes();
862
863         /* Uncommit the reservation */
864         h->resv_huge_pages -= unused_resv_pages;
865
866         /* Cannot return gigantic pages currently */
867         if (h->order >= MAX_ORDER)
868                 return;
869
870         nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
871
872         while (remaining_iterations-- && nr_pages) {
873                 nid = next_node(nid, node_online_map);
874                 if (nid == MAX_NUMNODES)
875                         nid = first_node(node_online_map);
876
877                 if (!h->surplus_huge_pages_node[nid])
878                         continue;
879
880                 if (!list_empty(&h->hugepage_freelists[nid])) {
881                         page = list_entry(h->hugepage_freelists[nid].next,
882                                           struct page, lru);
883                         list_del(&page->lru);
884                         update_and_free_page(h, page);
885                         h->free_huge_pages--;
886                         h->free_huge_pages_node[nid]--;
887                         h->surplus_huge_pages--;
888                         h->surplus_huge_pages_node[nid]--;
889                         nr_pages--;
890                         remaining_iterations = num_online_nodes();
891                 }
892         }
893 }
894
895 /*
896  * Determine if the huge page at addr within the vma has an associated
897  * reservation.  Where it does not we will need to logically increase
898  * reservation and actually increase quota before an allocation can occur.
899  * Where any new reservation would be required the reservation change is
900  * prepared, but not committed.  Once the page has been quota'd allocated
901  * an instantiated the change should be committed via vma_commit_reservation.
902  * No action is required on failure.
903  */
904 static int vma_needs_reservation(struct hstate *h,
905                         struct vm_area_struct *vma, unsigned long addr)
906 {
907         struct address_space *mapping = vma->vm_file->f_mapping;
908         struct inode *inode = mapping->host;
909
910         if (vma->vm_flags & VM_SHARED) {
911                 pgoff_t idx = vma_hugecache_offset(h, vma, addr);
912                 return region_chg(&inode->i_mapping->private_list,
913                                                         idx, idx + 1);
914
915         } else if (!is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
916                 return 1;
917
918         } else  {
919                 int err;
920                 pgoff_t idx = vma_hugecache_offset(h, vma, addr);
921                 struct resv_map *reservations = vma_resv_map(vma);
922
923                 err = region_chg(&reservations->regions, idx, idx + 1);
924                 if (err < 0)
925                         return err;
926                 return 0;
927         }
928 }
929 static void vma_commit_reservation(struct hstate *h,
930                         struct vm_area_struct *vma, unsigned long addr)
931 {
932         struct address_space *mapping = vma->vm_file->f_mapping;
933         struct inode *inode = mapping->host;
934
935         if (vma->vm_flags & VM_SHARED) {
936                 pgoff_t idx = vma_hugecache_offset(h, vma, addr);
937                 region_add(&inode->i_mapping->private_list, idx, idx + 1);
938
939         } else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
940                 pgoff_t idx = vma_hugecache_offset(h, vma, addr);
941                 struct resv_map *reservations = vma_resv_map(vma);
942
943                 /* Mark this page used in the map. */
944                 region_add(&reservations->regions, idx, idx + 1);
945         }
946 }
947
948 static struct page *alloc_huge_page(struct vm_area_struct *vma,
949                                     unsigned long addr, int avoid_reserve)
950 {
951         struct hstate *h = hstate_vma(vma);
952         struct page *page;
953         struct address_space *mapping = vma->vm_file->f_mapping;
954         struct inode *inode = mapping->host;
955         unsigned int chg;
956
957         /*
958          * Processes that did not create the mapping will have no reserves and
959          * will not have accounted against quota. Check that the quota can be
960          * made before satisfying the allocation
961          * MAP_NORESERVE mappings may also need pages and quota allocated
962          * if no reserve mapping overlaps.
963          */
964         chg = vma_needs_reservation(h, vma, addr);
965         if (chg < 0)
966                 return ERR_PTR(chg);
967         if (chg)
968                 if (hugetlb_get_quota(inode->i_mapping, chg))
969                         return ERR_PTR(-ENOSPC);
970
971         spin_lock(&hugetlb_lock);
972         page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);
973         spin_unlock(&hugetlb_lock);
974
975         if (!page) {
976                 page = alloc_buddy_huge_page(h, vma, addr);
977                 if (!page) {
978                         hugetlb_put_quota(inode->i_mapping, chg);
979                         return ERR_PTR(-VM_FAULT_OOM);
980                 }
981         }
982
983         set_page_refcounted(page);
984         set_page_private(page, (unsigned long) mapping);
985
986         vma_commit_reservation(h, vma, addr);
987
988         return page;
989 }
990
991 __attribute__((weak)) int alloc_bootmem_huge_page(struct hstate *h)
992 {
993         struct huge_bootmem_page *m;
994         int nr_nodes = nodes_weight(node_online_map);
995
996         while (nr_nodes) {
997                 void *addr;
998
999                 addr = __alloc_bootmem_node_nopanic(
1000                                 NODE_DATA(h->hugetlb_next_nid),
1001                                 huge_page_size(h), huge_page_size(h), 0);
1002
1003                 if (addr) {
1004                         /*
1005                          * Use the beginning of the huge page to store the
1006                          * huge_bootmem_page struct (until gather_bootmem
1007                          * puts them into the mem_map).
1008                          */
1009                         m = addr;
1010                         if (m)
1011                                 goto found;
1012                 }
1013                 hstate_next_node(h);
1014                 nr_nodes--;
1015         }
1016         return 0;
1017
1018 found:
1019         BUG_ON((unsigned long)virt_to_phys(m) & (huge_page_size(h) - 1));
1020         /* Put them into a private list first because mem_map is not up yet */
1021         list_add(&m->list, &huge_boot_pages);
1022         m->hstate = h;
1023         return 1;
1024 }
1025
1026 static void prep_compound_huge_page(struct page *page, int order)
1027 {
1028         if (unlikely(order > (MAX_ORDER - 1)))
1029                 prep_compound_gigantic_page(page, order);
1030         else
1031                 prep_compound_page(page, order);
1032 }
1033
1034 /* Put bootmem huge pages into the standard lists after mem_map is up */
1035 static void __init gather_bootmem_prealloc(void)
1036 {
1037         struct huge_bootmem_page *m;
1038
1039         list_for_each_entry(m, &huge_boot_pages, list) {
1040                 struct page *page = virt_to_page(m);
1041                 struct hstate *h = m->hstate;
1042                 __ClearPageReserved(page);
1043                 WARN_ON(page_count(page) != 1);
1044                 prep_compound_huge_page(page, h->order);
1045                 prep_new_huge_page(h, page, page_to_nid(page));
1046         }
1047 }
1048
1049 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
1050 {
1051         unsigned long i;
1052
1053         for (i = 0; i < h->max_huge_pages; ++i) {
1054                 if (h->order >= MAX_ORDER) {
1055                         if (!alloc_bootmem_huge_page(h))
1056                                 break;
1057                 } else if (!alloc_fresh_huge_page(h))
1058                         break;
1059         }
1060         h->max_huge_pages = i;
1061 }
1062
1063 static void __init hugetlb_init_hstates(void)
1064 {
1065         struct hstate *h;
1066
1067         for_each_hstate(h) {
1068                 /* oversize hugepages were init'ed in early boot */
1069                 if (h->order < MAX_ORDER)
1070                         hugetlb_hstate_alloc_pages(h);
1071         }
1072 }
1073
1074 static char * __init memfmt(char *buf, unsigned long n)
1075 {
1076         if (n >= (1UL << 30))
1077                 sprintf(buf, "%lu GB", n >> 30);
1078         else if (n >= (1UL << 20))
1079                 sprintf(buf, "%lu MB", n >> 20);
1080         else
1081                 sprintf(buf, "%lu KB", n >> 10);
1082         return buf;
1083 }
1084
1085 static void __init report_hugepages(void)
1086 {
1087         struct hstate *h;
1088
1089         for_each_hstate(h) {
1090                 char buf[32];
1091                 printk(KERN_INFO "HugeTLB registered %s page size, "
1092                                  "pre-allocated %ld pages\n",
1093                         memfmt(buf, huge_page_size(h)),
1094                         h->free_huge_pages);
1095         }
1096 }
1097
1098 #ifdef CONFIG_HIGHMEM
1099 static void try_to_free_low(struct hstate *h, unsigned long count)
1100 {
1101         int i;
1102
1103         if (h->order >= MAX_ORDER)
1104                 return;
1105
1106         for (i = 0; i < MAX_NUMNODES; ++i) {
1107                 struct page *page, *next;
1108                 struct list_head *freel = &h->hugepage_freelists[i];
1109                 list_for_each_entry_safe(page, next, freel, lru) {
1110                         if (count >= h->nr_huge_pages)
1111                                 return;
1112                         if (PageHighMem(page))
1113                                 continue;
1114                         list_del(&page->lru);
1115                         update_and_free_page(h, page);
1116                         h->free_huge_pages--;
1117                         h->free_huge_pages_node[page_to_nid(page)]--;
1118                 }
1119         }
1120 }
1121 #else
1122 static inline void try_to_free_low(struct hstate *h, unsigned long count)
1123 {
1124 }
1125 #endif
1126
1127 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
1128 static unsigned long set_max_huge_pages(struct hstate *h, unsigned long count)
1129 {
1130         unsigned long min_count, ret;
1131
1132         if (h->order >= MAX_ORDER)
1133                 return h->max_huge_pages;
1134
1135         /*
1136          * Increase the pool size
1137          * First take pages out of surplus state.  Then make up the
1138          * remaining difference by allocating fresh huge pages.
1139          *
1140          * We might race with alloc_buddy_huge_page() here and be unable
1141          * to convert a surplus huge page to a normal huge page. That is
1142          * not critical, though, it just means the overall size of the
1143          * pool might be one hugepage larger than it needs to be, but
1144          * within all the constraints specified by the sysctls.
1145          */
1146         spin_lock(&hugetlb_lock);
1147         while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
1148                 if (!adjust_pool_surplus(h, -1))
1149                         break;
1150         }
1151
1152         while (count > persistent_huge_pages(h)) {
1153                 /*
1154                  * If this allocation races such that we no longer need the
1155                  * page, free_huge_page will handle it by freeing the page
1156                  * and reducing the surplus.
1157                  */
1158                 spin_unlock(&hugetlb_lock);
1159                 ret = alloc_fresh_huge_page(h);
1160                 spin_lock(&hugetlb_lock);
1161                 if (!ret)
1162                         goto out;
1163
1164         }
1165
1166         /*
1167          * Decrease the pool size
1168          * First return free pages to the buddy allocator (being careful
1169          * to keep enough around to satisfy reservations).  Then place
1170          * pages into surplus state as needed so the pool will shrink
1171          * to the desired size as pages become free.
1172          *
1173          * By placing pages into the surplus state independent of the
1174          * overcommit value, we are allowing the surplus pool size to
1175          * exceed overcommit. There are few sane options here. Since
1176          * alloc_buddy_huge_page() is checking the global counter,
1177          * though, we'll note that we're not allowed to exceed surplus
1178          * and won't grow the pool anywhere else. Not until one of the
1179          * sysctls are changed, or the surplus pages go out of use.
1180          */
1181         min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
1182         min_count = max(count, min_count);
1183         try_to_free_low(h, min_count);
1184         while (min_count < persistent_huge_pages(h)) {
1185                 struct page *page = dequeue_huge_page(h);
1186                 if (!page)
1187                         break;
1188                 update_and_free_page(h, page);
1189         }
1190         while (count < persistent_huge_pages(h)) {
1191                 if (!adjust_pool_surplus(h, 1))
1192                         break;
1193         }
1194 out:
1195         ret = persistent_huge_pages(h);
1196         spin_unlock(&hugetlb_lock);
1197         return ret;
1198 }
1199
1200 #define HSTATE_ATTR_RO(_name) \
1201         static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1202
1203 #define HSTATE_ATTR(_name) \
1204         static struct kobj_attribute _name##_attr = \
1205                 __ATTR(_name, 0644, _name##_show, _name##_store)
1206
1207 static struct kobject *hugepages_kobj;
1208 static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
1209
1210 static struct hstate *kobj_to_hstate(struct kobject *kobj)
1211 {
1212         int i;
1213         for (i = 0; i < HUGE_MAX_HSTATE; i++)
1214                 if (hstate_kobjs[i] == kobj)
1215                         return &hstates[i];
1216         BUG();
1217         return NULL;
1218 }
1219
1220 static ssize_t nr_hugepages_show(struct kobject *kobj,
1221                                         struct kobj_attribute *attr, char *buf)
1222 {
1223         struct hstate *h = kobj_to_hstate(kobj);
1224         return sprintf(buf, "%lu\n", h->nr_huge_pages);
1225 }
1226 static ssize_t nr_hugepages_store(struct kobject *kobj,
1227                 struct kobj_attribute *attr, const char *buf, size_t count)
1228 {
1229         int err;
1230         unsigned long input;
1231         struct hstate *h = kobj_to_hstate(kobj);
1232
1233         err = strict_strtoul(buf, 10, &input);
1234         if (err)
1235                 return 0;
1236
1237         h->max_huge_pages = set_max_huge_pages(h, input);
1238
1239         return count;
1240 }
1241 HSTATE_ATTR(nr_hugepages);
1242
1243 static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
1244                                         struct kobj_attribute *attr, char *buf)
1245 {
1246         struct hstate *h = kobj_to_hstate(kobj);
1247         return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
1248 }
1249 static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
1250                 struct kobj_attribute *attr, const char *buf, size_t count)
1251 {
1252         int err;
1253         unsigned long input;
1254         struct hstate *h = kobj_to_hstate(kobj);
1255
1256         err = strict_strtoul(buf, 10, &input);
1257         if (err)
1258                 return 0;
1259
1260         spin_lock(&hugetlb_lock);
1261         h->nr_overcommit_huge_pages = input;
1262         spin_unlock(&hugetlb_lock);
1263
1264         return count;
1265 }
1266 HSTATE_ATTR(nr_overcommit_hugepages);
1267
1268 static ssize_t free_hugepages_show(struct kobject *kobj,
1269                                         struct kobj_attribute *attr, char *buf)
1270 {
1271         struct hstate *h = kobj_to_hstate(kobj);
1272         return sprintf(buf, "%lu\n", h->free_huge_pages);
1273 }
1274 HSTATE_ATTR_RO(free_hugepages);
1275
1276 static ssize_t resv_hugepages_show(struct kobject *kobj,
1277                                         struct kobj_attribute *attr, char *buf)
1278 {
1279         struct hstate *h = kobj_to_hstate(kobj);
1280         return sprintf(buf, "%lu\n", h->resv_huge_pages);
1281 }
1282 HSTATE_ATTR_RO(resv_hugepages);
1283
1284 static ssize_t surplus_hugepages_show(struct kobject *kobj,
1285                                         struct kobj_attribute *attr, char *buf)
1286 {
1287         struct hstate *h = kobj_to_hstate(kobj);
1288         return sprintf(buf, "%lu\n", h->surplus_huge_pages);
1289 }
1290 HSTATE_ATTR_RO(surplus_hugepages);
1291
1292 static struct attribute *hstate_attrs[] = {
1293         &nr_hugepages_attr.attr,
1294         &nr_overcommit_hugepages_attr.attr,
1295         &free_hugepages_attr.attr,
1296         &resv_hugepages_attr.attr,
1297         &surplus_hugepages_attr.attr,
1298         NULL,
1299 };
1300
1301 static struct attribute_group hstate_attr_group = {
1302         .attrs = hstate_attrs,
1303 };
1304
1305 static int __init hugetlb_sysfs_add_hstate(struct hstate *h)
1306 {
1307         int retval;
1308
1309         hstate_kobjs[h - hstates] = kobject_create_and_add(h->name,
1310                                                         hugepages_kobj);
1311         if (!hstate_kobjs[h - hstates])
1312                 return -ENOMEM;
1313
1314         retval = sysfs_create_group(hstate_kobjs[h - hstates],
1315                                                         &hstate_attr_group);
1316         if (retval)
1317                 kobject_put(hstate_kobjs[h - hstates]);
1318
1319         return retval;
1320 }
1321
1322 static void __init hugetlb_sysfs_init(void)
1323 {
1324         struct hstate *h;
1325         int err;
1326
1327         hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
1328         if (!hugepages_kobj)
1329                 return;
1330
1331         for_each_hstate(h) {
1332                 err = hugetlb_sysfs_add_hstate(h);
1333                 if (err)
1334                         printk(KERN_ERR "Hugetlb: Unable to add hstate %s",
1335                                                                 h->name);
1336         }
1337 }
1338
1339 static void __exit hugetlb_exit(void)
1340 {
1341         struct hstate *h;
1342
1343         for_each_hstate(h) {
1344                 kobject_put(hstate_kobjs[h - hstates]);
1345         }
1346
1347         kobject_put(hugepages_kobj);
1348 }
1349 module_exit(hugetlb_exit);
1350
1351 static int __init hugetlb_init(void)
1352 {
1353         /* Some platform decide whether they support huge pages at boot
1354          * time. On these, such as powerpc, HPAGE_SHIFT is set to 0 when
1355          * there is no such support
1356          */
1357         if (HPAGE_SHIFT == 0)
1358                 return 0;
1359
1360         if (!size_to_hstate(default_hstate_size)) {
1361                 default_hstate_size = HPAGE_SIZE;
1362                 if (!size_to_hstate(default_hstate_size))
1363                         hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
1364         }
1365         default_hstate_idx = size_to_hstate(default_hstate_size) - hstates;
1366         if (default_hstate_max_huge_pages)
1367                 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
1368
1369         hugetlb_init_hstates();
1370
1371         gather_bootmem_prealloc();
1372
1373         report_hugepages();
1374
1375         hugetlb_sysfs_init();
1376
1377         return 0;
1378 }
1379 module_init(hugetlb_init);
1380
1381 /* Should be called on processing a hugepagesz=... option */
1382 void __init hugetlb_add_hstate(unsigned order)
1383 {
1384         struct hstate *h;
1385         unsigned long i;
1386
1387         if (size_to_hstate(PAGE_SIZE << order)) {
1388                 printk(KERN_WARNING "hugepagesz= specified twice, ignoring\n");
1389                 return;
1390         }
1391         BUG_ON(max_hstate >= HUGE_MAX_HSTATE);
1392         BUG_ON(order == 0);
1393         h = &hstates[max_hstate++];
1394         h->order = order;
1395         h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
1396         h->nr_huge_pages = 0;
1397         h->free_huge_pages = 0;
1398         for (i = 0; i < MAX_NUMNODES; ++i)
1399                 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
1400         h->hugetlb_next_nid = first_node(node_online_map);
1401         snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
1402                                         huge_page_size(h)/1024);
1403
1404         parsed_hstate = h;
1405 }
1406
1407 static int __init hugetlb_nrpages_setup(char *s)
1408 {
1409         unsigned long *mhp;
1410         static unsigned long *last_mhp;
1411
1412         /*
1413          * !max_hstate means we haven't parsed a hugepagesz= parameter yet,
1414          * so this hugepages= parameter goes to the "default hstate".
1415          */
1416         if (!max_hstate)
1417                 mhp = &default_hstate_max_huge_pages;
1418         else
1419                 mhp = &parsed_hstate->max_huge_pages;
1420
1421         if (mhp == last_mhp) {
1422                 printk(KERN_WARNING "hugepages= specified twice without "
1423                         "interleaving hugepagesz=, ignoring\n");
1424                 return 1;
1425         }
1426
1427         if (sscanf(s, "%lu", mhp) <= 0)
1428                 *mhp = 0;
1429
1430         /*
1431          * Global state is always initialized later in hugetlb_init.
1432          * But we need to allocate >= MAX_ORDER hstates here early to still
1433          * use the bootmem allocator.
1434          */
1435         if (max_hstate && parsed_hstate->order >= MAX_ORDER)
1436                 hugetlb_hstate_alloc_pages(parsed_hstate);
1437
1438         last_mhp = mhp;
1439
1440         return 1;
1441 }
1442 __setup("hugepages=", hugetlb_nrpages_setup);
1443
1444 static int __init hugetlb_default_setup(char *s)
1445 {
1446         default_hstate_size = memparse(s, &s);
1447         return 1;
1448 }
1449 __setup("default_hugepagesz=", hugetlb_default_setup);
1450
1451 static unsigned int cpuset_mems_nr(unsigned int *array)
1452 {
1453         int node;
1454         unsigned int nr = 0;
1455
1456         for_each_node_mask(node, cpuset_current_mems_allowed)
1457                 nr += array[node];
1458
1459         return nr;
1460 }
1461
1462 #ifdef CONFIG_SYSCTL
1463 int hugetlb_sysctl_handler(struct ctl_table *table, int write,
1464                            struct file *file, void __user *buffer,
1465                            size_t *length, loff_t *ppos)
1466 {
1467         struct hstate *h = &default_hstate;
1468         unsigned long tmp;
1469
1470         if (!write)
1471                 tmp = h->max_huge_pages;
1472
1473         table->data = &tmp;
1474         table->maxlen = sizeof(unsigned long);
1475         proc_doulongvec_minmax(table, write, file, buffer, length, ppos);
1476
1477         if (write)
1478                 h->max_huge_pages = set_max_huge_pages(h, tmp);
1479
1480         return 0;
1481 }
1482
1483 int hugetlb_treat_movable_handler(struct ctl_table *table, int write,
1484                         struct file *file, void __user *buffer,
1485                         size_t *length, loff_t *ppos)
1486 {
1487         proc_dointvec(table, write, file, buffer, length, ppos);
1488         if (hugepages_treat_as_movable)
1489                 htlb_alloc_mask = GFP_HIGHUSER_MOVABLE;
1490         else
1491                 htlb_alloc_mask = GFP_HIGHUSER;
1492         return 0;
1493 }
1494
1495 int hugetlb_overcommit_handler(struct ctl_table *table, int write,
1496                         struct file *file, void __user *buffer,
1497                         size_t *length, loff_t *ppos)
1498 {
1499         struct hstate *h = &default_hstate;
1500         unsigned long tmp;
1501
1502         if (!write)
1503                 tmp = h->nr_overcommit_huge_pages;
1504
1505         table->data = &tmp;
1506         table->maxlen = sizeof(unsigned long);
1507         proc_doulongvec_minmax(table, write, file, buffer, length, ppos);
1508
1509         if (write) {
1510                 spin_lock(&hugetlb_lock);
1511                 h->nr_overcommit_huge_pages = tmp;
1512                 spin_unlock(&hugetlb_lock);
1513         }
1514
1515         return 0;
1516 }
1517
1518 #endif /* CONFIG_SYSCTL */
1519
1520 void hugetlb_report_meminfo(struct seq_file *m)
1521 {
1522         struct hstate *h = &default_hstate;
1523         seq_printf(m,
1524                         "HugePages_Total:   %5lu\n"
1525                         "HugePages_Free:    %5lu\n"
1526                         "HugePages_Rsvd:    %5lu\n"
1527                         "HugePages_Surp:    %5lu\n"
1528                         "Hugepagesize:   %8lu kB\n",
1529                         h->nr_huge_pages,
1530                         h->free_huge_pages,
1531                         h->resv_huge_pages,
1532                         h->surplus_huge_pages,
1533                         1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
1534 }
1535
1536 int hugetlb_report_node_meminfo(int nid, char *buf)
1537 {
1538         struct hstate *h = &default_hstate;
1539         return sprintf(buf,
1540                 "Node %d HugePages_Total: %5u\n"
1541                 "Node %d HugePages_Free:  %5u\n"
1542                 "Node %d HugePages_Surp:  %5u\n",
1543                 nid, h->nr_huge_pages_node[nid],
1544                 nid, h->free_huge_pages_node[nid],
1545                 nid, h->surplus_huge_pages_node[nid]);
1546 }
1547
1548 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
1549 unsigned long hugetlb_total_pages(void)
1550 {
1551         struct hstate *h = &default_hstate;
1552         return h->nr_huge_pages * pages_per_huge_page(h);
1553 }
1554
1555 static int hugetlb_acct_memory(struct hstate *h, long delta)
1556 {
1557         int ret = -ENOMEM;
1558
1559         spin_lock(&hugetlb_lock);
1560         /*
1561          * When cpuset is configured, it breaks the strict hugetlb page
1562          * reservation as the accounting is done on a global variable. Such
1563          * reservation is completely rubbish in the presence of cpuset because
1564          * the reservation is not checked against page availability for the
1565          * current cpuset. Application can still potentially OOM'ed by kernel
1566          * with lack of free htlb page in cpuset that the task is in.
1567          * Attempt to enforce strict accounting with cpuset is almost
1568          * impossible (or too ugly) because cpuset is too fluid that
1569          * task or memory node can be dynamically moved between cpusets.
1570          *
1571          * The change of semantics for shared hugetlb mapping with cpuset is
1572          * undesirable. However, in order to preserve some of the semantics,
1573          * we fall back to check against current free page availability as
1574          * a best attempt and hopefully to minimize the impact of changing
1575          * semantics that cpuset has.
1576          */
1577         if (delta > 0) {
1578                 if (gather_surplus_pages(h, delta) < 0)
1579                         goto out;
1580
1581                 if (delta > cpuset_mems_nr(h->free_huge_pages_node)) {
1582                         return_unused_surplus_pages(h, delta);
1583                         goto out;
1584                 }
1585         }
1586
1587         ret = 0;
1588         if (delta < 0)
1589                 return_unused_surplus_pages(h, (unsigned long) -delta);
1590
1591 out:
1592         spin_unlock(&hugetlb_lock);
1593         return ret;
1594 }
1595
1596 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
1597 {
1598         struct resv_map *reservations = vma_resv_map(vma);
1599
1600         /*
1601          * This new VMA should share its siblings reservation map if present.
1602          * The VMA will only ever have a valid reservation map pointer where
1603          * it is being copied for another still existing VMA.  As that VMA
1604          * has a reference to the reservation map it cannot dissappear until
1605          * after this open call completes.  It is therefore safe to take a
1606          * new reference here without additional locking.
1607          */
1608         if (reservations)
1609                 kref_get(&reservations->refs);
1610 }
1611
1612 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
1613 {
1614         struct hstate *h = hstate_vma(vma);
1615         struct resv_map *reservations = vma_resv_map(vma);
1616         unsigned long reserve;
1617         unsigned long start;
1618         unsigned long end;
1619
1620         if (reservations) {
1621                 start = vma_hugecache_offset(h, vma, vma->vm_start);
1622                 end = vma_hugecache_offset(h, vma, vma->vm_end);
1623
1624                 reserve = (end - start) -
1625                         region_count(&reservations->regions, start, end);
1626
1627                 kref_put(&reservations->refs, resv_map_release);
1628
1629                 if (reserve) {
1630                         hugetlb_acct_memory(h, -reserve);
1631                         hugetlb_put_quota(vma->vm_file->f_mapping, reserve);
1632                 }
1633         }
1634 }
1635
1636 /*
1637  * We cannot handle pagefaults against hugetlb pages at all.  They cause
1638  * handle_mm_fault() to try to instantiate regular-sized pages in the
1639  * hugegpage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
1640  * this far.
1641  */
1642 static int hugetlb_vm_op_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1643 {
1644         BUG();
1645         return 0;
1646 }
1647
1648 struct vm_operations_struct hugetlb_vm_ops = {
1649         .fault = hugetlb_vm_op_fault,
1650         .open = hugetlb_vm_op_open,
1651         .close = hugetlb_vm_op_close,
1652 };
1653
1654 static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
1655                                 int writable)
1656 {
1657         pte_t entry;
1658
1659         if (writable) {
1660                 entry =
1661                     pte_mkwrite(pte_mkdirty(mk_pte(page, vma->vm_page_prot)));
1662         } else {
1663                 entry = huge_pte_wrprotect(mk_pte(page, vma->vm_page_prot));
1664         }
1665         entry = pte_mkyoung(entry);
1666         entry = pte_mkhuge(entry);
1667
1668         return entry;
1669 }
1670
1671 static void set_huge_ptep_writable(struct vm_area_struct *vma,
1672                                    unsigned long address, pte_t *ptep)
1673 {
1674         pte_t entry;
1675
1676         entry = pte_mkwrite(pte_mkdirty(huge_ptep_get(ptep)));
1677         if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1)) {
1678                 update_mmu_cache(vma, address, entry);
1679         }
1680 }
1681
1682
1683 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
1684                             struct vm_area_struct *vma)
1685 {
1686         pte_t *src_pte, *dst_pte, entry;
1687         struct page *ptepage;
1688         unsigned long addr;
1689         int cow;
1690         struct hstate *h = hstate_vma(vma);
1691         unsigned long sz = huge_page_size(h);
1692
1693         cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
1694
1695         for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
1696                 src_pte = huge_pte_offset(src, addr);
1697                 if (!src_pte)
1698                         continue;
1699                 dst_pte = huge_pte_alloc(dst, addr, sz);
1700                 if (!dst_pte)
1701                         goto nomem;
1702
1703                 /* If the pagetables are shared don't copy or take references */
1704                 if (dst_pte == src_pte)
1705                         continue;
1706
1707                 spin_lock(&dst->page_table_lock);
1708                 spin_lock_nested(&src->page_table_lock, SINGLE_DEPTH_NESTING);
1709                 if (!huge_pte_none(huge_ptep_get(src_pte))) {
1710                         if (cow)
1711                                 huge_ptep_set_wrprotect(src, addr, src_pte);
1712                         entry = huge_ptep_get(src_pte);
1713                         ptepage = pte_page(entry);
1714                         get_page(ptepage);
1715                         set_huge_pte_at(dst, addr, dst_pte, entry);
1716                 }
1717                 spin_unlock(&src->page_table_lock);
1718                 spin_unlock(&dst->page_table_lock);
1719         }
1720         return 0;
1721
1722 nomem:
1723         return -ENOMEM;
1724 }
1725
1726 void __unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
1727                             unsigned long end, struct page *ref_page)
1728 {
1729         struct mm_struct *mm = vma->vm_mm;
1730         unsigned long address;
1731         pte_t *ptep;
1732         pte_t pte;
1733         struct page *page;
1734         struct page *tmp;
1735         struct hstate *h = hstate_vma(vma);
1736         unsigned long sz = huge_page_size(h);
1737
1738         /*
1739          * A page gathering list, protected by per file i_mmap_lock. The
1740          * lock is used to avoid list corruption from multiple unmapping
1741          * of the same page since we are using page->lru.
1742          */
1743         LIST_HEAD(page_list);
1744
1745         WARN_ON(!is_vm_hugetlb_page(vma));
1746         BUG_ON(start & ~huge_page_mask(h));
1747         BUG_ON(end & ~huge_page_mask(h));
1748
1749         mmu_notifier_invalidate_range_start(mm, start, end);
1750         spin_lock(&mm->page_table_lock);
1751         for (address = start; address < end; address += sz) {
1752                 ptep = huge_pte_offset(mm, address);
1753                 if (!ptep)
1754                         continue;
1755
1756                 if (huge_pmd_unshare(mm, &address, ptep))
1757                         continue;
1758
1759                 /*
1760                  * If a reference page is supplied, it is because a specific
1761                  * page is being unmapped, not a range. Ensure the page we
1762                  * are about to unmap is the actual page of interest.
1763                  */
1764                 if (ref_page) {
1765                         pte = huge_ptep_get(ptep);
1766                         if (huge_pte_none(pte))
1767                                 continue;
1768                         page = pte_page(pte);
1769                         if (page != ref_page)
1770                                 continue;
1771
1772                         /*
1773                          * Mark the VMA as having unmapped its page so that
1774                          * future faults in this VMA will fail rather than
1775                          * looking like data was lost
1776                          */
1777                         set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
1778                 }
1779
1780                 pte = huge_ptep_get_and_clear(mm, address, ptep);
1781                 if (huge_pte_none(pte))
1782                         continue;
1783
1784                 page = pte_page(pte);
1785                 if (pte_dirty(pte))
1786                         set_page_dirty(page);
1787                 list_add(&page->lru, &page_list);
1788         }
1789         spin_unlock(&mm->page_table_lock);
1790         flush_tlb_range(vma, start, end);
1791         mmu_notifier_invalidate_range_end(mm, start, end);
1792         list_for_each_entry_safe(page, tmp, &page_list, lru) {
1793                 list_del(&page->lru);
1794                 put_page(page);
1795         }
1796 }
1797
1798 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
1799                           unsigned long end, struct page *ref_page)
1800 {
1801         spin_lock(&vma->vm_file->f_mapping->i_mmap_lock);
1802         __unmap_hugepage_range(vma, start, end, ref_page);
1803         spin_unlock(&vma->vm_file->f_mapping->i_mmap_lock);
1804 }
1805
1806 /*
1807  * This is called when the original mapper is failing to COW a MAP_PRIVATE
1808  * mappping it owns the reserve page for. The intention is to unmap the page
1809  * from other VMAs and let the children be SIGKILLed if they are faulting the
1810  * same region.
1811  */
1812 static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
1813                                 struct page *page, unsigned long address)
1814 {
1815         struct hstate *h = hstate_vma(vma);
1816         struct vm_area_struct *iter_vma;
1817         struct address_space *mapping;
1818         struct prio_tree_iter iter;
1819         pgoff_t pgoff;
1820
1821         /*
1822          * vm_pgoff is in PAGE_SIZE units, hence the different calculation
1823          * from page cache lookup which is in HPAGE_SIZE units.
1824          */
1825         address = address & huge_page_mask(h);
1826         pgoff = ((address - vma->vm_start) >> PAGE_SHIFT)
1827                 + (vma->vm_pgoff >> PAGE_SHIFT);
1828         mapping = (struct address_space *)page_private(page);
1829
1830         vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) {
1831                 /* Do not unmap the current VMA */
1832                 if (iter_vma == vma)
1833                         continue;
1834
1835                 /*
1836                  * Unmap the page from other VMAs without their own reserves.
1837                  * They get marked to be SIGKILLed if they fault in these
1838                  * areas. This is because a future no-page fault on this VMA
1839                  * could insert a zeroed page instead of the data existing
1840                  * from the time of fork. This would look like data corruption
1841                  */
1842                 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
1843                         unmap_hugepage_range(iter_vma,
1844                                 address, address + huge_page_size(h),
1845                                 page);
1846         }
1847
1848         return 1;
1849 }
1850
1851 static int hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
1852                         unsigned long address, pte_t *ptep, pte_t pte,
1853                         struct page *pagecache_page)
1854 {
1855         struct hstate *h = hstate_vma(vma);
1856         struct page *old_page, *new_page;
1857         int avoidcopy;
1858         int outside_reserve = 0;
1859
1860         old_page = pte_page(pte);
1861
1862 retry_avoidcopy:
1863         /* If no-one else is actually using this page, avoid the copy
1864          * and just make the page writable */
1865         avoidcopy = (page_count(old_page) == 1);
1866         if (avoidcopy) {
1867                 set_huge_ptep_writable(vma, address, ptep);
1868                 return 0;
1869         }
1870
1871         /*
1872          * If the process that created a MAP_PRIVATE mapping is about to
1873          * perform a COW due to a shared page count, attempt to satisfy
1874          * the allocation without using the existing reserves. The pagecache
1875          * page is used to determine if the reserve at this address was
1876          * consumed or not. If reserves were used, a partial faulted mapping
1877          * at the time of fork() could consume its reserves on COW instead
1878          * of the full address range.
1879          */
1880         if (!(vma->vm_flags & VM_SHARED) &&
1881                         is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
1882                         old_page != pagecache_page)
1883                 outside_reserve = 1;
1884
1885         page_cache_get(old_page);
1886         new_page = alloc_huge_page(vma, address, outside_reserve);
1887
1888         if (IS_ERR(new_page)) {
1889                 page_cache_release(old_page);
1890
1891                 /*
1892                  * If a process owning a MAP_PRIVATE mapping fails to COW,
1893                  * it is due to references held by a child and an insufficient
1894                  * huge page pool. To guarantee the original mappers
1895                  * reliability, unmap the page from child processes. The child
1896                  * may get SIGKILLed if it later faults.
1897                  */
1898                 if (outside_reserve) {
1899                         BUG_ON(huge_pte_none(pte));
1900                         if (unmap_ref_private(mm, vma, old_page, address)) {
1901                                 BUG_ON(page_count(old_page) != 1);
1902                                 BUG_ON(huge_pte_none(pte));
1903                                 goto retry_avoidcopy;
1904                         }
1905                         WARN_ON_ONCE(1);
1906                 }
1907
1908                 return -PTR_ERR(new_page);
1909         }
1910
1911         spin_unlock(&mm->page_table_lock);
1912         copy_huge_page(new_page, old_page, address, vma);
1913         __SetPageUptodate(new_page);
1914         spin_lock(&mm->page_table_lock);
1915
1916         ptep = huge_pte_offset(mm, address & huge_page_mask(h));
1917         if (likely(pte_same(huge_ptep_get(ptep), pte))) {
1918                 /* Break COW */
1919                 huge_ptep_clear_flush(vma, address, ptep);
1920                 set_huge_pte_at(mm, address, ptep,
1921                                 make_huge_pte(vma, new_page, 1));
1922                 /* Make the old page be freed below */
1923                 new_page = old_page;
1924         }
1925         page_cache_release(new_page);
1926         page_cache_release(old_page);
1927         return 0;
1928 }
1929
1930 /* Return the pagecache page at a given address within a VMA */
1931 static struct page *hugetlbfs_pagecache_page(struct hstate *h,
1932                         struct vm_area_struct *vma, unsigned long address)
1933 {
1934         struct address_space *mapping;
1935         pgoff_t idx;
1936
1937         mapping = vma->vm_file->f_mapping;
1938         idx = vma_hugecache_offset(h, vma, address);
1939
1940         return find_lock_page(mapping, idx);
1941 }
1942
1943 static int hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma,
1944                         unsigned long address, pte_t *ptep, int write_access)
1945 {
1946         struct hstate *h = hstate_vma(vma);
1947         int ret = VM_FAULT_SIGBUS;
1948         pgoff_t idx;
1949         unsigned long size;
1950         struct page *page;
1951         struct address_space *mapping;
1952         pte_t new_pte;
1953
1954         /*
1955          * Currently, we are forced to kill the process in the event the
1956          * original mapper has unmapped pages from the child due to a failed
1957          * COW. Warn that such a situation has occured as it may not be obvious
1958          */
1959         if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
1960                 printk(KERN_WARNING
1961                         "PID %d killed due to inadequate hugepage pool\n",
1962                         current->pid);
1963                 return ret;
1964         }
1965
1966         mapping = vma->vm_file->f_mapping;
1967         idx = vma_hugecache_offset(h, vma, address);
1968
1969         /*
1970          * Use page lock to guard against racing truncation
1971          * before we get page_table_lock.
1972          */
1973 retry:
1974         page = find_lock_page(mapping, idx);
1975         if (!page) {
1976                 size = i_size_read(mapping->host) >> huge_page_shift(h);
1977                 if (idx >= size)
1978                         goto out;
1979                 page = alloc_huge_page(vma, address, 0);
1980                 if (IS_ERR(page)) {
1981                         ret = -PTR_ERR(page);
1982                         goto out;
1983                 }
1984                 clear_huge_page(page, address, huge_page_size(h));
1985                 __SetPageUptodate(page);
1986
1987                 if (vma->vm_flags & VM_SHARED) {
1988                         int err;
1989                         struct inode *inode = mapping->host;
1990
1991                         err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
1992                         if (err) {
1993                                 put_page(page);
1994                                 if (err == -EEXIST)
1995                                         goto retry;
1996                                 goto out;
1997                         }
1998
1999                         spin_lock(&inode->i_lock);
2000                         inode->i_blocks += blocks_per_huge_page(h);
2001                         spin_unlock(&inode->i_lock);
2002                 } else
2003                         lock_page(page);
2004         }
2005
2006         /*
2007          * If we are going to COW a private mapping later, we examine the
2008          * pending reservations for this page now. This will ensure that
2009          * any allocations necessary to record that reservation occur outside
2010          * the spinlock.
2011          */
2012         if (write_access && !(vma->vm_flags & VM_SHARED))
2013                 if (vma_needs_reservation(h, vma, address) < 0) {
2014                         ret = VM_FAULT_OOM;
2015                         goto backout_unlocked;
2016                 }
2017
2018         spin_lock(&mm->page_table_lock);
2019         size = i_size_read(mapping->host) >> huge_page_shift(h);
2020         if (idx >= size)
2021                 goto backout;
2022
2023         ret = 0;
2024         if (!huge_pte_none(huge_ptep_get(ptep)))
2025                 goto backout;
2026
2027         new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
2028                                 && (vma->vm_flags & VM_SHARED)));
2029         set_huge_pte_at(mm, address, ptep, new_pte);
2030
2031         if (write_access && !(vma->vm_flags & VM_SHARED)) {
2032                 /* Optimization, do the COW without a second fault */
2033                 ret = hugetlb_cow(mm, vma, address, ptep, new_pte, page);
2034         }
2035
2036         spin_unlock(&mm->page_table_lock);
2037         unlock_page(page);
2038 out:
2039         return ret;
2040
2041 backout:
2042         spin_unlock(&mm->page_table_lock);
2043 backout_unlocked:
2044         unlock_page(page);
2045         put_page(page);
2046         goto out;
2047 }
2048
2049 int hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
2050                         unsigned long address, int write_access)
2051 {
2052         pte_t *ptep;
2053         pte_t entry;
2054         int ret;
2055         struct page *pagecache_page = NULL;
2056         static DEFINE_MUTEX(hugetlb_instantiation_mutex);
2057         struct hstate *h = hstate_vma(vma);
2058
2059         ptep = huge_pte_alloc(mm, address, huge_page_size(h));
2060         if (!ptep)
2061                 return VM_FAULT_OOM;
2062
2063         /*
2064          * Serialize hugepage allocation and instantiation, so that we don't
2065          * get spurious allocation failures if two CPUs race to instantiate
2066          * the same page in the page cache.
2067          */
2068         mutex_lock(&hugetlb_instantiation_mutex);
2069         entry = huge_ptep_get(ptep);
2070         if (huge_pte_none(entry)) {
2071                 ret = hugetlb_no_page(mm, vma, address, ptep, write_access);
2072                 goto out_mutex;
2073         }
2074
2075         ret = 0;
2076
2077         /*
2078          * If we are going to COW the mapping later, we examine the pending
2079          * reservations for this page now. This will ensure that any
2080          * allocations necessary to record that reservation occur outside the
2081          * spinlock. For private mappings, we also lookup the pagecache
2082          * page now as it is used to determine if a reservation has been
2083          * consumed.
2084          */
2085         if (write_access && !pte_write(entry)) {
2086                 if (vma_needs_reservation(h, vma, address) < 0) {
2087                         ret = VM_FAULT_OOM;
2088                         goto out_mutex;
2089                 }
2090
2091                 if (!(vma->vm_flags & VM_SHARED))
2092                         pagecache_page = hugetlbfs_pagecache_page(h,
2093                                                                 vma, address);
2094         }
2095
2096         spin_lock(&mm->page_table_lock);
2097         /* Check for a racing update before calling hugetlb_cow */
2098         if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
2099                 goto out_page_table_lock;
2100
2101
2102         if (write_access) {
2103                 if (!pte_write(entry)) {
2104                         ret = hugetlb_cow(mm, vma, address, ptep, entry,
2105                                                         pagecache_page);
2106                         goto out_page_table_lock;
2107                 }
2108                 entry = pte_mkdirty(entry);
2109         }
2110         entry = pte_mkyoung(entry);
2111         if (huge_ptep_set_access_flags(vma, address, ptep, entry, write_access))
2112                 update_mmu_cache(vma, address, entry);
2113
2114 out_page_table_lock:
2115         spin_unlock(&mm->page_table_lock);
2116
2117         if (pagecache_page) {
2118                 unlock_page(pagecache_page);
2119                 put_page(pagecache_page);
2120         }
2121
2122 out_mutex:
2123         mutex_unlock(&hugetlb_instantiation_mutex);
2124
2125         return ret;
2126 }
2127
2128 /* Can be overriden by architectures */
2129 __attribute__((weak)) struct page *
2130 follow_huge_pud(struct mm_struct *mm, unsigned long address,
2131                pud_t *pud, int write)
2132 {
2133         BUG();
2134         return NULL;
2135 }
2136
2137 static int huge_zeropage_ok(pte_t *ptep, int write, int shared)
2138 {
2139         if (!ptep || write || shared)
2140                 return 0;
2141         else
2142                 return huge_pte_none(huge_ptep_get(ptep));
2143 }
2144
2145 int follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
2146                         struct page **pages, struct vm_area_struct **vmas,
2147                         unsigned long *position, int *length, int i,
2148                         int write)
2149 {
2150         unsigned long pfn_offset;
2151         unsigned long vaddr = *position;
2152         int remainder = *length;
2153         struct hstate *h = hstate_vma(vma);
2154         int zeropage_ok = 0;
2155         int shared = vma->vm_flags & VM_SHARED;
2156
2157         spin_lock(&mm->page_table_lock);
2158         while (vaddr < vma->vm_end && remainder) {
2159                 pte_t *pte;
2160                 struct page *page;
2161
2162                 /*
2163                  * Some archs (sparc64, sh*) have multiple pte_ts to
2164                  * each hugepage.  We have to make * sure we get the
2165                  * first, for the page indexing below to work.
2166                  */
2167                 pte = huge_pte_offset(mm, vaddr & huge_page_mask(h));
2168                 if (huge_zeropage_ok(pte, write, shared))
2169                         zeropage_ok = 1;
2170
2171                 if (!pte ||
2172                     (huge_pte_none(huge_ptep_get(pte)) && !zeropage_ok) ||
2173                     (write && !pte_write(huge_ptep_get(pte)))) {
2174                         int ret;
2175
2176                         spin_unlock(&mm->page_table_lock);
2177                         ret = hugetlb_fault(mm, vma, vaddr, write);
2178                         spin_lock(&mm->page_table_lock);
2179                         if (!(ret & VM_FAULT_ERROR))
2180                                 continue;
2181
2182                         remainder = 0;
2183                         if (!i)
2184                                 i = -EFAULT;
2185                         break;
2186                 }
2187
2188                 pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
2189                 page = pte_page(huge_ptep_get(pte));
2190 same_page:
2191                 if (pages) {
2192                         if (zeropage_ok)
2193                                 pages[i] = ZERO_PAGE(0);
2194                         else
2195                                 pages[i] = mem_map_offset(page, pfn_offset);
2196                         get_page(pages[i]);
2197                 }
2198
2199                 if (vmas)
2200                         vmas[i] = vma;
2201
2202                 vaddr += PAGE_SIZE;
2203                 ++pfn_offset;
2204                 --remainder;
2205                 ++i;
2206                 if (vaddr < vma->vm_end && remainder &&
2207                                 pfn_offset < pages_per_huge_page(h)) {
2208                         /*
2209                          * We use pfn_offset to avoid touching the pageframes
2210                          * of this compound page.
2211                          */
2212                         goto same_page;
2213                 }
2214         }
2215         spin_unlock(&mm->page_table_lock);
2216         *length = remainder;
2217         *position = vaddr;
2218
2219         return i;
2220 }
2221
2222 void hugetlb_change_protection(struct vm_area_struct *vma,
2223                 unsigned long address, unsigned long end, pgprot_t newprot)
2224 {
2225         struct mm_struct *mm = vma->vm_mm;
2226         unsigned long start = address;
2227         pte_t *ptep;
2228         pte_t pte;
2229         struct hstate *h = hstate_vma(vma);
2230
2231         BUG_ON(address >= end);
2232         flush_cache_range(vma, address, end);
2233
2234         spin_lock(&vma->vm_file->f_mapping->i_mmap_lock);
2235         spin_lock(&mm->page_table_lock);
2236         for (; address < end; address += huge_page_size(h)) {
2237                 ptep = huge_pte_offset(mm, address);
2238                 if (!ptep)
2239                         continue;
2240                 if (huge_pmd_unshare(mm, &address, ptep))
2241                         continue;
2242                 if (!huge_pte_none(huge_ptep_get(ptep))) {
2243                         pte = huge_ptep_get_and_clear(mm, address, ptep);
2244                         pte = pte_mkhuge(pte_modify(pte, newprot));
2245                         set_huge_pte_at(mm, address, ptep, pte);
2246                 }
2247         }
2248         spin_unlock(&mm->page_table_lock);
2249         spin_unlock(&vma->vm_file->f_mapping->i_mmap_lock);
2250
2251         flush_tlb_range(vma, start, end);
2252 }
2253
2254 int hugetlb_reserve_pages(struct inode *inode,
2255                                         long from, long to,
2256                                         struct vm_area_struct *vma)
2257 {
2258         long ret, chg;
2259         struct hstate *h = hstate_inode(inode);
2260
2261         if (vma && vma->vm_flags & VM_NORESERVE)
2262                 return 0;
2263
2264         /*
2265          * Shared mappings base their reservation on the number of pages that
2266          * are already allocated on behalf of the file. Private mappings need
2267          * to reserve the full area even if read-only as mprotect() may be
2268          * called to make the mapping read-write. Assume !vma is a shm mapping
2269          */
2270         if (!vma || vma->vm_flags & VM_SHARED)
2271                 chg = region_chg(&inode->i_mapping->private_list, from, to);
2272         else {
2273                 struct resv_map *resv_map = resv_map_alloc();
2274                 if (!resv_map)
2275                         return -ENOMEM;
2276
2277                 chg = to - from;
2278
2279                 set_vma_resv_map(vma, resv_map);
2280                 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
2281         }
2282
2283         if (chg < 0)
2284                 return chg;
2285
2286         if (hugetlb_get_quota(inode->i_mapping, chg))
2287                 return -ENOSPC;
2288         ret = hugetlb_acct_memory(h, chg);
2289         if (ret < 0) {
2290                 hugetlb_put_quota(inode->i_mapping, chg);
2291                 return ret;
2292         }
2293         if (!vma || vma->vm_flags & VM_SHARED)
2294                 region_add(&inode->i_mapping->private_list, from, to);
2295         return 0;
2296 }
2297
2298 void hugetlb_unreserve_pages(struct inode *inode, long offset, long freed)
2299 {
2300         struct hstate *h = hstate_inode(inode);
2301         long chg = region_truncate(&inode->i_mapping->private_list, offset);
2302
2303         spin_lock(&inode->i_lock);
2304         inode->i_blocks -= blocks_per_huge_page(h);
2305         spin_unlock(&inode->i_lock);
2306
2307         hugetlb_put_quota(inode->i_mapping, (chg - freed));
2308         hugetlb_acct_memory(h, -(chg - freed));
2309 }