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