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