efd78527ad1ee62159d8955069756fdaddf893a1
[powerpc.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 unsigned long max_huge_pages;
28 static struct list_head hugepage_freelists[MAX_NUMNODES];
29 static unsigned int nr_huge_pages_node[MAX_NUMNODES];
30 static unsigned int free_huge_pages_node[MAX_NUMNODES];
31 static unsigned int surplus_huge_pages_node[MAX_NUMNODES];
32 static gfp_t htlb_alloc_mask = GFP_HIGHUSER;
33 unsigned long hugepages_treat_as_movable;
34 int hugetlb_dynamic_pool;
35
36 /*
37  * Protects updates to hugepage_freelists, nr_huge_pages, and free_huge_pages
38  */
39 static DEFINE_SPINLOCK(hugetlb_lock);
40
41 static void clear_huge_page(struct page *page, unsigned long addr)
42 {
43         int i;
44
45         might_sleep();
46         for (i = 0; i < (HPAGE_SIZE/PAGE_SIZE); i++) {
47                 cond_resched();
48                 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
49         }
50 }
51
52 static void copy_huge_page(struct page *dst, struct page *src,
53                            unsigned long addr, struct vm_area_struct *vma)
54 {
55         int i;
56
57         might_sleep();
58         for (i = 0; i < HPAGE_SIZE/PAGE_SIZE; i++) {
59                 cond_resched();
60                 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
61         }
62 }
63
64 static void enqueue_huge_page(struct page *page)
65 {
66         int nid = page_to_nid(page);
67         list_add(&page->lru, &hugepage_freelists[nid]);
68         free_huge_pages++;
69         free_huge_pages_node[nid]++;
70 }
71
72 static struct page *dequeue_huge_page(struct vm_area_struct *vma,
73                                 unsigned long address)
74 {
75         int nid;
76         struct page *page = NULL;
77         struct mempolicy *mpol;
78         struct zonelist *zonelist = huge_zonelist(vma, address,
79                                         htlb_alloc_mask, &mpol);
80         struct zone **z;
81
82         for (z = zonelist->zones; *z; z++) {
83                 nid = zone_to_nid(*z);
84                 if (cpuset_zone_allowed_softwall(*z, htlb_alloc_mask) &&
85                     !list_empty(&hugepage_freelists[nid])) {
86                         page = list_entry(hugepage_freelists[nid].next,
87                                           struct page, lru);
88                         list_del(&page->lru);
89                         free_huge_pages--;
90                         free_huge_pages_node[nid]--;
91                         if (vma && vma->vm_flags & VM_MAYSHARE)
92                                 resv_huge_pages--;
93                         break;
94                 }
95         }
96         mpol_free(mpol);        /* unref if mpol !NULL */
97         return page;
98 }
99
100 static void update_and_free_page(struct page *page)
101 {
102         int i;
103         nr_huge_pages--;
104         nr_huge_pages_node[page_to_nid(page)]--;
105         for (i = 0; i < (HPAGE_SIZE / PAGE_SIZE); i++) {
106                 page[i].flags &= ~(1 << PG_locked | 1 << PG_error | 1 << PG_referenced |
107                                 1 << PG_dirty | 1 << PG_active | 1 << PG_reserved |
108                                 1 << PG_private | 1<< PG_writeback);
109         }
110         set_compound_page_dtor(page, NULL);
111         set_page_refcounted(page);
112         __free_pages(page, HUGETLB_PAGE_ORDER);
113 }
114
115 static void free_huge_page(struct page *page)
116 {
117         int nid = page_to_nid(page);
118
119         BUG_ON(page_count(page));
120         INIT_LIST_HEAD(&page->lru);
121
122         spin_lock(&hugetlb_lock);
123         if (surplus_huge_pages_node[nid]) {
124                 update_and_free_page(page);
125                 surplus_huge_pages--;
126                 surplus_huge_pages_node[nid]--;
127         } else {
128                 enqueue_huge_page(page);
129         }
130         spin_unlock(&hugetlb_lock);
131 }
132
133 /*
134  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
135  * balanced by operating on them in a round-robin fashion.
136  * Returns 1 if an adjustment was made.
137  */
138 static int adjust_pool_surplus(int delta)
139 {
140         static int prev_nid;
141         int nid = prev_nid;
142         int ret = 0;
143
144         VM_BUG_ON(delta != -1 && delta != 1);
145         do {
146                 nid = next_node(nid, node_online_map);
147                 if (nid == MAX_NUMNODES)
148                         nid = first_node(node_online_map);
149
150                 /* To shrink on this node, there must be a surplus page */
151                 if (delta < 0 && !surplus_huge_pages_node[nid])
152                         continue;
153                 /* Surplus cannot exceed the total number of pages */
154                 if (delta > 0 && surplus_huge_pages_node[nid] >=
155                                                 nr_huge_pages_node[nid])
156                         continue;
157
158                 surplus_huge_pages += delta;
159                 surplus_huge_pages_node[nid] += delta;
160                 ret = 1;
161                 break;
162         } while (nid != prev_nid);
163
164         prev_nid = nid;
165         return ret;
166 }
167
168 static int alloc_fresh_huge_page(void)
169 {
170         static int prev_nid;
171         struct page *page;
172         int nid;
173
174         /*
175          * Copy static prev_nid to local nid, work on that, then copy it
176          * back to prev_nid afterwards: otherwise there's a window in which
177          * a racer might pass invalid nid MAX_NUMNODES to alloc_pages_node.
178          * But we don't need to use a spin_lock here: it really doesn't
179          * matter if occasionally a racer chooses the same nid as we do.
180          */
181         nid = next_node(prev_nid, node_online_map);
182         if (nid == MAX_NUMNODES)
183                 nid = first_node(node_online_map);
184         prev_nid = nid;
185
186         page = alloc_pages_node(nid, htlb_alloc_mask|__GFP_COMP|__GFP_NOWARN,
187                                         HUGETLB_PAGE_ORDER);
188         if (page) {
189                 set_compound_page_dtor(page, free_huge_page);
190                 spin_lock(&hugetlb_lock);
191                 nr_huge_pages++;
192                 nr_huge_pages_node[page_to_nid(page)]++;
193                 spin_unlock(&hugetlb_lock);
194                 put_page(page); /* free it into the hugepage allocator */
195                 return 1;
196         }
197         return 0;
198 }
199
200 static struct page *alloc_buddy_huge_page(struct vm_area_struct *vma,
201                                                 unsigned long address)
202 {
203         struct page *page;
204
205         /* Check if the dynamic pool is enabled */
206         if (!hugetlb_dynamic_pool)
207                 return NULL;
208
209         page = alloc_pages(htlb_alloc_mask|__GFP_COMP|__GFP_NOWARN,
210                                         HUGETLB_PAGE_ORDER);
211         if (page) {
212                 set_compound_page_dtor(page, free_huge_page);
213                 spin_lock(&hugetlb_lock);
214                 nr_huge_pages++;
215                 nr_huge_pages_node[page_to_nid(page)]++;
216                 surplus_huge_pages++;
217                 surplus_huge_pages_node[page_to_nid(page)]++;
218                 spin_unlock(&hugetlb_lock);
219         }
220
221         return page;
222 }
223
224 /*
225  * Increase the hugetlb pool such that it can accomodate a reservation
226  * of size 'delta'.
227  */
228 static int gather_surplus_pages(int delta)
229 {
230         struct list_head surplus_list;
231         struct page *page, *tmp;
232         int ret, i;
233         int needed, allocated;
234
235         needed = (resv_huge_pages + delta) - free_huge_pages;
236         if (needed <= 0)
237                 return 0;
238
239         allocated = 0;
240         INIT_LIST_HEAD(&surplus_list);
241
242         ret = -ENOMEM;
243 retry:
244         spin_unlock(&hugetlb_lock);
245         for (i = 0; i < needed; i++) {
246                 page = alloc_buddy_huge_page(NULL, 0);
247                 if (!page) {
248                         /*
249                          * We were not able to allocate enough pages to
250                          * satisfy the entire reservation so we free what
251                          * we've allocated so far.
252                          */
253                         spin_lock(&hugetlb_lock);
254                         needed = 0;
255                         goto free;
256                 }
257
258                 list_add(&page->lru, &surplus_list);
259         }
260         allocated += needed;
261
262         /*
263          * After retaking hugetlb_lock, we need to recalculate 'needed'
264          * because either resv_huge_pages or free_huge_pages may have changed.
265          */
266         spin_lock(&hugetlb_lock);
267         needed = (resv_huge_pages + delta) - (free_huge_pages + allocated);
268         if (needed > 0)
269                 goto retry;
270
271         /*
272          * The surplus_list now contains _at_least_ the number of extra pages
273          * needed to accomodate the reservation.  Add the appropriate number
274          * of pages to the hugetlb pool and free the extras back to the buddy
275          * allocator.
276          */
277         needed += allocated;
278         ret = 0;
279 free:
280         list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
281                 list_del(&page->lru);
282                 if ((--needed) >= 0)
283                         enqueue_huge_page(page);
284                 else
285                         update_and_free_page(page);
286         }
287
288         return ret;
289 }
290
291 /*
292  * When releasing a hugetlb pool reservation, any surplus pages that were
293  * allocated to satisfy the reservation must be explicitly freed if they were
294  * never used.
295  */
296 void return_unused_surplus_pages(unsigned long unused_resv_pages)
297 {
298         static int nid = -1;
299         struct page *page;
300         unsigned long nr_pages;
301
302         nr_pages = min(unused_resv_pages, surplus_huge_pages);
303
304         while (nr_pages) {
305                 nid = next_node(nid, node_online_map);
306                 if (nid == MAX_NUMNODES)
307                         nid = first_node(node_online_map);
308
309                 if (!surplus_huge_pages_node[nid])
310                         continue;
311
312                 if (!list_empty(&hugepage_freelists[nid])) {
313                         page = list_entry(hugepage_freelists[nid].next,
314                                           struct page, lru);
315                         list_del(&page->lru);
316                         update_and_free_page(page);
317                         free_huge_pages--;
318                         free_huge_pages_node[nid]--;
319                         surplus_huge_pages--;
320                         surplus_huge_pages_node[nid]--;
321                         nr_pages--;
322                 }
323         }
324 }
325
326 static struct page *alloc_huge_page(struct vm_area_struct *vma,
327                                     unsigned long addr)
328 {
329         struct page *page = NULL;
330         int use_reserved_page = vma->vm_flags & VM_MAYSHARE;
331
332         spin_lock(&hugetlb_lock);
333         if (!use_reserved_page && (free_huge_pages <= resv_huge_pages))
334                 goto fail;
335
336         page = dequeue_huge_page(vma, addr);
337         if (!page)
338                 goto fail;
339
340         spin_unlock(&hugetlb_lock);
341         set_page_refcounted(page);
342         return page;
343
344 fail:
345         spin_unlock(&hugetlb_lock);
346
347         /*
348          * Private mappings do not use reserved huge pages so the allocation
349          * may have failed due to an undersized hugetlb pool.  Try to grab a
350          * surplus huge page from the buddy allocator.
351          */
352         if (!use_reserved_page)
353                 page = alloc_buddy_huge_page(vma, addr);
354
355         return page;
356 }
357
358 static int __init hugetlb_init(void)
359 {
360         unsigned long i;
361
362         if (HPAGE_SHIFT == 0)
363                 return 0;
364
365         for (i = 0; i < MAX_NUMNODES; ++i)
366                 INIT_LIST_HEAD(&hugepage_freelists[i]);
367
368         for (i = 0; i < max_huge_pages; ++i) {
369                 if (!alloc_fresh_huge_page())
370                         break;
371         }
372         max_huge_pages = free_huge_pages = nr_huge_pages = i;
373         printk("Total HugeTLB memory allocated, %ld\n", free_huge_pages);
374         return 0;
375 }
376 module_init(hugetlb_init);
377
378 static int __init hugetlb_setup(char *s)
379 {
380         if (sscanf(s, "%lu", &max_huge_pages) <= 0)
381                 max_huge_pages = 0;
382         return 1;
383 }
384 __setup("hugepages=", hugetlb_setup);
385
386 static unsigned int cpuset_mems_nr(unsigned int *array)
387 {
388         int node;
389         unsigned int nr = 0;
390
391         for_each_node_mask(node, cpuset_current_mems_allowed)
392                 nr += array[node];
393
394         return nr;
395 }
396
397 #ifdef CONFIG_SYSCTL
398 #ifdef CONFIG_HIGHMEM
399 static void try_to_free_low(unsigned long count)
400 {
401         int i;
402
403         for (i = 0; i < MAX_NUMNODES; ++i) {
404                 struct page *page, *next;
405                 list_for_each_entry_safe(page, next, &hugepage_freelists[i], lru) {
406                         if (PageHighMem(page))
407                                 continue;
408                         list_del(&page->lru);
409                         update_and_free_page(page);
410                         free_huge_pages--;
411                         free_huge_pages_node[page_to_nid(page)]--;
412                         if (count >= nr_huge_pages)
413                                 return;
414                 }
415         }
416 }
417 #else
418 static inline void try_to_free_low(unsigned long count)
419 {
420 }
421 #endif
422
423 #define persistent_huge_pages (nr_huge_pages - surplus_huge_pages)
424 static unsigned long set_max_huge_pages(unsigned long count)
425 {
426         unsigned long min_count, ret;
427
428         /*
429          * Increase the pool size
430          * First take pages out of surplus state.  Then make up the
431          * remaining difference by allocating fresh huge pages.
432          */
433         spin_lock(&hugetlb_lock);
434         while (surplus_huge_pages && count > persistent_huge_pages) {
435                 if (!adjust_pool_surplus(-1))
436                         break;
437         }
438
439         while (count > persistent_huge_pages) {
440                 int ret;
441                 /*
442                  * If this allocation races such that we no longer need the
443                  * page, free_huge_page will handle it by freeing the page
444                  * and reducing the surplus.
445                  */
446                 spin_unlock(&hugetlb_lock);
447                 ret = alloc_fresh_huge_page();
448                 spin_lock(&hugetlb_lock);
449                 if (!ret)
450                         goto out;
451
452         }
453         if (count >= persistent_huge_pages)
454                 goto out;
455
456         /*
457          * Decrease the pool size
458          * First return free pages to the buddy allocator (being careful
459          * to keep enough around to satisfy reservations).  Then place
460          * pages into surplus state as needed so the pool will shrink
461          * to the desired size as pages become free.
462          */
463         min_count = max(count, resv_huge_pages);
464         try_to_free_low(min_count);
465         while (min_count < persistent_huge_pages) {
466                 struct page *page = dequeue_huge_page(NULL, 0);
467                 if (!page)
468                         break;
469                 update_and_free_page(page);
470         }
471         while (count < persistent_huge_pages) {
472                 if (!adjust_pool_surplus(1))
473                         break;
474         }
475 out:
476         ret = persistent_huge_pages;
477         spin_unlock(&hugetlb_lock);
478         return ret;
479 }
480
481 int hugetlb_sysctl_handler(struct ctl_table *table, int write,
482                            struct file *file, void __user *buffer,
483                            size_t *length, loff_t *ppos)
484 {
485         proc_doulongvec_minmax(table, write, file, buffer, length, ppos);
486         max_huge_pages = set_max_huge_pages(max_huge_pages);
487         return 0;
488 }
489
490 int hugetlb_treat_movable_handler(struct ctl_table *table, int write,
491                         struct file *file, void __user *buffer,
492                         size_t *length, loff_t *ppos)
493 {
494         proc_dointvec(table, write, file, buffer, length, ppos);
495         if (hugepages_treat_as_movable)
496                 htlb_alloc_mask = GFP_HIGHUSER_MOVABLE;
497         else
498                 htlb_alloc_mask = GFP_HIGHUSER;
499         return 0;
500 }
501
502 #endif /* CONFIG_SYSCTL */
503
504 int hugetlb_report_meminfo(char *buf)
505 {
506         return sprintf(buf,
507                         "HugePages_Total: %5lu\n"
508                         "HugePages_Free:  %5lu\n"
509                         "HugePages_Rsvd:  %5lu\n"
510                         "HugePages_Surp:  %5lu\n"
511                         "Hugepagesize:    %5lu kB\n",
512                         nr_huge_pages,
513                         free_huge_pages,
514                         resv_huge_pages,
515                         surplus_huge_pages,
516                         HPAGE_SIZE/1024);
517 }
518
519 int hugetlb_report_node_meminfo(int nid, char *buf)
520 {
521         return sprintf(buf,
522                 "Node %d HugePages_Total: %5u\n"
523                 "Node %d HugePages_Free:  %5u\n",
524                 nid, nr_huge_pages_node[nid],
525                 nid, free_huge_pages_node[nid]);
526 }
527
528 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
529 unsigned long hugetlb_total_pages(void)
530 {
531         return nr_huge_pages * (HPAGE_SIZE / PAGE_SIZE);
532 }
533
534 /*
535  * We cannot handle pagefaults against hugetlb pages at all.  They cause
536  * handle_mm_fault() to try to instantiate regular-sized pages in the
537  * hugegpage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
538  * this far.
539  */
540 static int hugetlb_vm_op_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
541 {
542         BUG();
543         return 0;
544 }
545
546 struct vm_operations_struct hugetlb_vm_ops = {
547         .fault = hugetlb_vm_op_fault,
548 };
549
550 static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
551                                 int writable)
552 {
553         pte_t entry;
554
555         if (writable) {
556                 entry =
557                     pte_mkwrite(pte_mkdirty(mk_pte(page, vma->vm_page_prot)));
558         } else {
559                 entry = pte_wrprotect(mk_pte(page, vma->vm_page_prot));
560         }
561         entry = pte_mkyoung(entry);
562         entry = pte_mkhuge(entry);
563
564         return entry;
565 }
566
567 static void set_huge_ptep_writable(struct vm_area_struct *vma,
568                                    unsigned long address, pte_t *ptep)
569 {
570         pte_t entry;
571
572         entry = pte_mkwrite(pte_mkdirty(*ptep));
573         if (ptep_set_access_flags(vma, address, ptep, entry, 1)) {
574                 update_mmu_cache(vma, address, entry);
575         }
576 }
577
578
579 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
580                             struct vm_area_struct *vma)
581 {
582         pte_t *src_pte, *dst_pte, entry;
583         struct page *ptepage;
584         unsigned long addr;
585         int cow;
586
587         cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
588
589         for (addr = vma->vm_start; addr < vma->vm_end; addr += HPAGE_SIZE) {
590                 src_pte = huge_pte_offset(src, addr);
591                 if (!src_pte)
592                         continue;
593                 dst_pte = huge_pte_alloc(dst, addr);
594                 if (!dst_pte)
595                         goto nomem;
596                 spin_lock(&dst->page_table_lock);
597                 spin_lock(&src->page_table_lock);
598                 if (!pte_none(*src_pte)) {
599                         if (cow)
600                                 ptep_set_wrprotect(src, addr, src_pte);
601                         entry = *src_pte;
602                         ptepage = pte_page(entry);
603                         get_page(ptepage);
604                         set_huge_pte_at(dst, addr, dst_pte, entry);
605                 }
606                 spin_unlock(&src->page_table_lock);
607                 spin_unlock(&dst->page_table_lock);
608         }
609         return 0;
610
611 nomem:
612         return -ENOMEM;
613 }
614
615 void __unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
616                             unsigned long end)
617 {
618         struct mm_struct *mm = vma->vm_mm;
619         unsigned long address;
620         pte_t *ptep;
621         pte_t pte;
622         struct page *page;
623         struct page *tmp;
624         /*
625          * A page gathering list, protected by per file i_mmap_lock. The
626          * lock is used to avoid list corruption from multiple unmapping
627          * of the same page since we are using page->lru.
628          */
629         LIST_HEAD(page_list);
630
631         WARN_ON(!is_vm_hugetlb_page(vma));
632         BUG_ON(start & ~HPAGE_MASK);
633         BUG_ON(end & ~HPAGE_MASK);
634
635         spin_lock(&mm->page_table_lock);
636         for (address = start; address < end; address += HPAGE_SIZE) {
637                 ptep = huge_pte_offset(mm, address);
638                 if (!ptep)
639                         continue;
640
641                 if (huge_pmd_unshare(mm, &address, ptep))
642                         continue;
643
644                 pte = huge_ptep_get_and_clear(mm, address, ptep);
645                 if (pte_none(pte))
646                         continue;
647
648                 page = pte_page(pte);
649                 if (pte_dirty(pte))
650                         set_page_dirty(page);
651                 list_add(&page->lru, &page_list);
652         }
653         spin_unlock(&mm->page_table_lock);
654         flush_tlb_range(vma, start, end);
655         list_for_each_entry_safe(page, tmp, &page_list, lru) {
656                 list_del(&page->lru);
657                 put_page(page);
658         }
659 }
660
661 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
662                           unsigned long end)
663 {
664         /*
665          * It is undesirable to test vma->vm_file as it should be non-null
666          * for valid hugetlb area. However, vm_file will be NULL in the error
667          * cleanup path of do_mmap_pgoff. When hugetlbfs ->mmap method fails,
668          * do_mmap_pgoff() nullifies vma->vm_file before calling this function
669          * to clean up. Since no pte has actually been setup, it is safe to
670          * do nothing in this case.
671          */
672         if (vma->vm_file) {
673                 spin_lock(&vma->vm_file->f_mapping->i_mmap_lock);
674                 __unmap_hugepage_range(vma, start, end);
675                 spin_unlock(&vma->vm_file->f_mapping->i_mmap_lock);
676         }
677 }
678
679 static int hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
680                         unsigned long address, pte_t *ptep, pte_t pte)
681 {
682         struct page *old_page, *new_page;
683         int avoidcopy;
684
685         old_page = pte_page(pte);
686
687         /* If no-one else is actually using this page, avoid the copy
688          * and just make the page writable */
689         avoidcopy = (page_count(old_page) == 1);
690         if (avoidcopy) {
691                 set_huge_ptep_writable(vma, address, ptep);
692                 return 0;
693         }
694
695         page_cache_get(old_page);
696         new_page = alloc_huge_page(vma, address);
697
698         if (!new_page) {
699                 page_cache_release(old_page);
700                 return VM_FAULT_OOM;
701         }
702
703         spin_unlock(&mm->page_table_lock);
704         copy_huge_page(new_page, old_page, address, vma);
705         spin_lock(&mm->page_table_lock);
706
707         ptep = huge_pte_offset(mm, address & HPAGE_MASK);
708         if (likely(pte_same(*ptep, pte))) {
709                 /* Break COW */
710                 set_huge_pte_at(mm, address, ptep,
711                                 make_huge_pte(vma, new_page, 1));
712                 /* Make the old page be freed below */
713                 new_page = old_page;
714         }
715         page_cache_release(new_page);
716         page_cache_release(old_page);
717         return 0;
718 }
719
720 static int hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma,
721                         unsigned long address, pte_t *ptep, int write_access)
722 {
723         int ret = VM_FAULT_SIGBUS;
724         unsigned long idx;
725         unsigned long size;
726         struct page *page;
727         struct address_space *mapping;
728         pte_t new_pte;
729
730         mapping = vma->vm_file->f_mapping;
731         idx = ((address - vma->vm_start) >> HPAGE_SHIFT)
732                 + (vma->vm_pgoff >> (HPAGE_SHIFT - PAGE_SHIFT));
733
734         /*
735          * Use page lock to guard against racing truncation
736          * before we get page_table_lock.
737          */
738 retry:
739         page = find_lock_page(mapping, idx);
740         if (!page) {
741                 size = i_size_read(mapping->host) >> HPAGE_SHIFT;
742                 if (idx >= size)
743                         goto out;
744                 if (hugetlb_get_quota(mapping))
745                         goto out;
746                 page = alloc_huge_page(vma, address);
747                 if (!page) {
748                         hugetlb_put_quota(mapping);
749                         ret = VM_FAULT_OOM;
750                         goto out;
751                 }
752                 clear_huge_page(page, address);
753
754                 if (vma->vm_flags & VM_SHARED) {
755                         int err;
756
757                         err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
758                         if (err) {
759                                 put_page(page);
760                                 hugetlb_put_quota(mapping);
761                                 if (err == -EEXIST)
762                                         goto retry;
763                                 goto out;
764                         }
765                 } else
766                         lock_page(page);
767         }
768
769         spin_lock(&mm->page_table_lock);
770         size = i_size_read(mapping->host) >> HPAGE_SHIFT;
771         if (idx >= size)
772                 goto backout;
773
774         ret = 0;
775         if (!pte_none(*ptep))
776                 goto backout;
777
778         new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
779                                 && (vma->vm_flags & VM_SHARED)));
780         set_huge_pte_at(mm, address, ptep, new_pte);
781
782         if (write_access && !(vma->vm_flags & VM_SHARED)) {
783                 /* Optimization, do the COW without a second fault */
784                 ret = hugetlb_cow(mm, vma, address, ptep, new_pte);
785         }
786
787         spin_unlock(&mm->page_table_lock);
788         unlock_page(page);
789 out:
790         return ret;
791
792 backout:
793         spin_unlock(&mm->page_table_lock);
794         hugetlb_put_quota(mapping);
795         unlock_page(page);
796         put_page(page);
797         goto out;
798 }
799
800 int hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
801                         unsigned long address, int write_access)
802 {
803         pte_t *ptep;
804         pte_t entry;
805         int ret;
806         static DEFINE_MUTEX(hugetlb_instantiation_mutex);
807
808         ptep = huge_pte_alloc(mm, address);
809         if (!ptep)
810                 return VM_FAULT_OOM;
811
812         /*
813          * Serialize hugepage allocation and instantiation, so that we don't
814          * get spurious allocation failures if two CPUs race to instantiate
815          * the same page in the page cache.
816          */
817         mutex_lock(&hugetlb_instantiation_mutex);
818         entry = *ptep;
819         if (pte_none(entry)) {
820                 ret = hugetlb_no_page(mm, vma, address, ptep, write_access);
821                 mutex_unlock(&hugetlb_instantiation_mutex);
822                 return ret;
823         }
824
825         ret = 0;
826
827         spin_lock(&mm->page_table_lock);
828         /* Check for a racing update before calling hugetlb_cow */
829         if (likely(pte_same(entry, *ptep)))
830                 if (write_access && !pte_write(entry))
831                         ret = hugetlb_cow(mm, vma, address, ptep, entry);
832         spin_unlock(&mm->page_table_lock);
833         mutex_unlock(&hugetlb_instantiation_mutex);
834
835         return ret;
836 }
837
838 int follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
839                         struct page **pages, struct vm_area_struct **vmas,
840                         unsigned long *position, int *length, int i)
841 {
842         unsigned long pfn_offset;
843         unsigned long vaddr = *position;
844         int remainder = *length;
845
846         spin_lock(&mm->page_table_lock);
847         while (vaddr < vma->vm_end && remainder) {
848                 pte_t *pte;
849                 struct page *page;
850
851                 /*
852                  * Some archs (sparc64, sh*) have multiple pte_ts to
853                  * each hugepage.  We have to make * sure we get the
854                  * first, for the page indexing below to work.
855                  */
856                 pte = huge_pte_offset(mm, vaddr & HPAGE_MASK);
857
858                 if (!pte || pte_none(*pte)) {
859                         int ret;
860
861                         spin_unlock(&mm->page_table_lock);
862                         ret = hugetlb_fault(mm, vma, vaddr, 0);
863                         spin_lock(&mm->page_table_lock);
864                         if (!(ret & VM_FAULT_ERROR))
865                                 continue;
866
867                         remainder = 0;
868                         if (!i)
869                                 i = -EFAULT;
870                         break;
871                 }
872
873                 pfn_offset = (vaddr & ~HPAGE_MASK) >> PAGE_SHIFT;
874                 page = pte_page(*pte);
875 same_page:
876                 if (pages) {
877                         get_page(page);
878                         pages[i] = page + pfn_offset;
879                 }
880
881                 if (vmas)
882                         vmas[i] = vma;
883
884                 vaddr += PAGE_SIZE;
885                 ++pfn_offset;
886                 --remainder;
887                 ++i;
888                 if (vaddr < vma->vm_end && remainder &&
889                                 pfn_offset < HPAGE_SIZE/PAGE_SIZE) {
890                         /*
891                          * We use pfn_offset to avoid touching the pageframes
892                          * of this compound page.
893                          */
894                         goto same_page;
895                 }
896         }
897         spin_unlock(&mm->page_table_lock);
898         *length = remainder;
899         *position = vaddr;
900
901         return i;
902 }
903
904 void hugetlb_change_protection(struct vm_area_struct *vma,
905                 unsigned long address, unsigned long end, pgprot_t newprot)
906 {
907         struct mm_struct *mm = vma->vm_mm;
908         unsigned long start = address;
909         pte_t *ptep;
910         pte_t pte;
911
912         BUG_ON(address >= end);
913         flush_cache_range(vma, address, end);
914
915         spin_lock(&vma->vm_file->f_mapping->i_mmap_lock);
916         spin_lock(&mm->page_table_lock);
917         for (; address < end; address += HPAGE_SIZE) {
918                 ptep = huge_pte_offset(mm, address);
919                 if (!ptep)
920                         continue;
921                 if (huge_pmd_unshare(mm, &address, ptep))
922                         continue;
923                 if (!pte_none(*ptep)) {
924                         pte = huge_ptep_get_and_clear(mm, address, ptep);
925                         pte = pte_mkhuge(pte_modify(pte, newprot));
926                         set_huge_pte_at(mm, address, ptep, pte);
927                 }
928         }
929         spin_unlock(&mm->page_table_lock);
930         spin_unlock(&vma->vm_file->f_mapping->i_mmap_lock);
931
932         flush_tlb_range(vma, start, end);
933 }
934
935 struct file_region {
936         struct list_head link;
937         long from;
938         long to;
939 };
940
941 static long region_add(struct list_head *head, long f, long t)
942 {
943         struct file_region *rg, *nrg, *trg;
944
945         /* Locate the region we are either in or before. */
946         list_for_each_entry(rg, head, link)
947                 if (f <= rg->to)
948                         break;
949
950         /* Round our left edge to the current segment if it encloses us. */
951         if (f > rg->from)
952                 f = rg->from;
953
954         /* Check for and consume any regions we now overlap with. */
955         nrg = rg;
956         list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
957                 if (&rg->link == head)
958                         break;
959                 if (rg->from > t)
960                         break;
961
962                 /* If this area reaches higher then extend our area to
963                  * include it completely.  If this is not the first area
964                  * which we intend to reuse, free it. */
965                 if (rg->to > t)
966                         t = rg->to;
967                 if (rg != nrg) {
968                         list_del(&rg->link);
969                         kfree(rg);
970                 }
971         }
972         nrg->from = f;
973         nrg->to = t;
974         return 0;
975 }
976
977 static long region_chg(struct list_head *head, long f, long t)
978 {
979         struct file_region *rg, *nrg;
980         long chg = 0;
981
982         /* Locate the region we are before or in. */
983         list_for_each_entry(rg, head, link)
984                 if (f <= rg->to)
985                         break;
986
987         /* If we are below the current region then a new region is required.
988          * Subtle, allocate a new region at the position but make it zero
989          * size such that we can guarentee to record the reservation. */
990         if (&rg->link == head || t < rg->from) {
991                 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
992                 if (nrg == 0)
993                         return -ENOMEM;
994                 nrg->from = f;
995                 nrg->to   = f;
996                 INIT_LIST_HEAD(&nrg->link);
997                 list_add(&nrg->link, rg->link.prev);
998
999                 return t - f;
1000         }
1001
1002         /* Round our left edge to the current segment if it encloses us. */
1003         if (f > rg->from)
1004                 f = rg->from;
1005         chg = t - f;
1006
1007         /* Check for and consume any regions we now overlap with. */
1008         list_for_each_entry(rg, rg->link.prev, link) {
1009                 if (&rg->link == head)
1010                         break;
1011                 if (rg->from > t)
1012                         return chg;
1013
1014                 /* We overlap with this area, if it extends futher than
1015                  * us then we must extend ourselves.  Account for its
1016                  * existing reservation. */
1017                 if (rg->to > t) {
1018                         chg += rg->to - t;
1019                         t = rg->to;
1020                 }
1021                 chg -= rg->to - rg->from;
1022         }
1023         return chg;
1024 }
1025
1026 static long region_truncate(struct list_head *head, long end)
1027 {
1028         struct file_region *rg, *trg;
1029         long chg = 0;
1030
1031         /* Locate the region we are either in or before. */
1032         list_for_each_entry(rg, head, link)
1033                 if (end <= rg->to)
1034                         break;
1035         if (&rg->link == head)
1036                 return 0;
1037
1038         /* If we are in the middle of a region then adjust it. */
1039         if (end > rg->from) {
1040                 chg = rg->to - end;
1041                 rg->to = end;
1042                 rg = list_entry(rg->link.next, typeof(*rg), link);
1043         }
1044
1045         /* Drop any remaining regions. */
1046         list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
1047                 if (&rg->link == head)
1048                         break;
1049                 chg += rg->to - rg->from;
1050                 list_del(&rg->link);
1051                 kfree(rg);
1052         }
1053         return chg;
1054 }
1055
1056 static int hugetlb_acct_memory(long delta)
1057 {
1058         int ret = -ENOMEM;
1059
1060         spin_lock(&hugetlb_lock);
1061         /*
1062          * When cpuset is configured, it breaks the strict hugetlb page
1063          * reservation as the accounting is done on a global variable. Such
1064          * reservation is completely rubbish in the presence of cpuset because
1065          * the reservation is not checked against page availability for the
1066          * current cpuset. Application can still potentially OOM'ed by kernel
1067          * with lack of free htlb page in cpuset that the task is in.
1068          * Attempt to enforce strict accounting with cpuset is almost
1069          * impossible (or too ugly) because cpuset is too fluid that
1070          * task or memory node can be dynamically moved between cpusets.
1071          *
1072          * The change of semantics for shared hugetlb mapping with cpuset is
1073          * undesirable. However, in order to preserve some of the semantics,
1074          * we fall back to check against current free page availability as
1075          * a best attempt and hopefully to minimize the impact of changing
1076          * semantics that cpuset has.
1077          */
1078         if (delta > 0) {
1079                 if (gather_surplus_pages(delta) < 0)
1080                         goto out;
1081
1082                 if (delta > cpuset_mems_nr(free_huge_pages_node))
1083                         goto out;
1084         }
1085
1086         ret = 0;
1087         resv_huge_pages += delta;
1088         if (delta < 0)
1089                 return_unused_surplus_pages((unsigned long) -delta);
1090
1091 out:
1092         spin_unlock(&hugetlb_lock);
1093         return ret;
1094 }
1095
1096 int hugetlb_reserve_pages(struct inode *inode, long from, long to)
1097 {
1098         long ret, chg;
1099
1100         chg = region_chg(&inode->i_mapping->private_list, from, to);
1101         if (chg < 0)
1102                 return chg;
1103
1104         ret = hugetlb_acct_memory(chg);
1105         if (ret < 0)
1106                 return ret;
1107         region_add(&inode->i_mapping->private_list, from, to);
1108         return 0;
1109 }
1110
1111 void hugetlb_unreserve_pages(struct inode *inode, long offset, long freed)
1112 {
1113         long chg = region_truncate(&inode->i_mapping->private_list, offset);
1114         hugetlb_acct_memory(freed - chg);
1115 }