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