mm: use clear_page_mlock() in page_remove_rmap()
[platform/adaptation/renesas_rcar/renesas_kernel.git] / mm / mlock.c
1 /*
2  *      linux/mm/mlock.c
3  *
4  *  (C) Copyright 1995 Linus Torvalds
5  *  (C) Copyright 2002 Christoph Hellwig
6  */
7
8 #include <linux/capability.h>
9 #include <linux/mman.h>
10 #include <linux/mm.h>
11 #include <linux/swap.h>
12 #include <linux/swapops.h>
13 #include <linux/pagemap.h>
14 #include <linux/mempolicy.h>
15 #include <linux/syscalls.h>
16 #include <linux/sched.h>
17 #include <linux/export.h>
18 #include <linux/rmap.h>
19 #include <linux/mmzone.h>
20 #include <linux/hugetlb.h>
21
22 #include "internal.h"
23
24 int can_do_mlock(void)
25 {
26         if (capable(CAP_IPC_LOCK))
27                 return 1;
28         if (rlimit(RLIMIT_MEMLOCK) != 0)
29                 return 1;
30         return 0;
31 }
32 EXPORT_SYMBOL(can_do_mlock);
33
34 /*
35  * Mlocked pages are marked with PageMlocked() flag for efficient testing
36  * in vmscan and, possibly, the fault path; and to support semi-accurate
37  * statistics.
38  *
39  * An mlocked page [PageMlocked(page)] is unevictable.  As such, it will
40  * be placed on the LRU "unevictable" list, rather than the [in]active lists.
41  * The unevictable list is an LRU sibling list to the [in]active lists.
42  * PageUnevictable is set to indicate the unevictable state.
43  *
44  * When lazy mlocking via vmscan, it is important to ensure that the
45  * vma's VM_LOCKED status is not concurrently being modified, otherwise we
46  * may have mlocked a page that is being munlocked. So lazy mlock must take
47  * the mmap_sem for read, and verify that the vma really is locked
48  * (see mm/rmap.c).
49  */
50
51 /*
52  *  LRU accounting for clear_page_mlock()
53  */
54 void clear_page_mlock(struct page *page)
55 {
56         if (!TestClearPageMlocked(page))
57                 return;
58
59         dec_zone_page_state(page, NR_MLOCK);
60         count_vm_event(UNEVICTABLE_PGCLEARED);
61         if (!isolate_lru_page(page)) {
62                 putback_lru_page(page);
63         } else {
64                 /*
65                  * We lost the race. the page already moved to evictable list.
66                  */
67                 if (PageUnevictable(page))
68                         count_vm_event(UNEVICTABLE_PGSTRANDED);
69         }
70 }
71
72 /*
73  * Mark page as mlocked if not already.
74  * If page on LRU, isolate and putback to move to unevictable list.
75  */
76 void mlock_vma_page(struct page *page)
77 {
78         BUG_ON(!PageLocked(page));
79
80         if (!TestSetPageMlocked(page)) {
81                 inc_zone_page_state(page, NR_MLOCK);
82                 count_vm_event(UNEVICTABLE_PGMLOCKED);
83                 if (!isolate_lru_page(page))
84                         putback_lru_page(page);
85         }
86 }
87
88 /**
89  * munlock_vma_page - munlock a vma page
90  * @page - page to be unlocked
91  *
92  * called from munlock()/munmap() path with page supposedly on the LRU.
93  * When we munlock a page, because the vma where we found the page is being
94  * munlock()ed or munmap()ed, we want to check whether other vmas hold the
95  * page locked so that we can leave it on the unevictable lru list and not
96  * bother vmscan with it.  However, to walk the page's rmap list in
97  * try_to_munlock() we must isolate the page from the LRU.  If some other
98  * task has removed the page from the LRU, we won't be able to do that.
99  * So we clear the PageMlocked as we might not get another chance.  If we
100  * can't isolate the page, we leave it for putback_lru_page() and vmscan
101  * [page_referenced()/try_to_unmap()] to deal with.
102  */
103 void munlock_vma_page(struct page *page)
104 {
105         BUG_ON(!PageLocked(page));
106
107         if (TestClearPageMlocked(page)) {
108                 dec_zone_page_state(page, NR_MLOCK);
109                 if (!isolate_lru_page(page)) {
110                         int ret = SWAP_AGAIN;
111
112                         /*
113                          * Optimization: if the page was mapped just once,
114                          * that's our mapping and we don't need to check all the
115                          * other vmas.
116                          */
117                         if (page_mapcount(page) > 1)
118                                 ret = try_to_munlock(page);
119                         /*
120                          * did try_to_unlock() succeed or punt?
121                          */
122                         if (ret != SWAP_MLOCK)
123                                 count_vm_event(UNEVICTABLE_PGMUNLOCKED);
124
125                         putback_lru_page(page);
126                 } else {
127                         /*
128                          * Some other task has removed the page from the LRU.
129                          * putback_lru_page() will take care of removing the
130                          * page from the unevictable list, if necessary.
131                          * vmscan [page_referenced()] will move the page back
132                          * to the unevictable list if some other vma has it
133                          * mlocked.
134                          */
135                         if (PageUnevictable(page))
136                                 count_vm_event(UNEVICTABLE_PGSTRANDED);
137                         else
138                                 count_vm_event(UNEVICTABLE_PGMUNLOCKED);
139                 }
140         }
141 }
142
143 /**
144  * __mlock_vma_pages_range() -  mlock a range of pages in the vma.
145  * @vma:   target vma
146  * @start: start address
147  * @end:   end address
148  *
149  * This takes care of making the pages present too.
150  *
151  * return 0 on success, negative error code on error.
152  *
153  * vma->vm_mm->mmap_sem must be held for at least read.
154  */
155 static long __mlock_vma_pages_range(struct vm_area_struct *vma,
156                                     unsigned long start, unsigned long end,
157                                     int *nonblocking)
158 {
159         struct mm_struct *mm = vma->vm_mm;
160         unsigned long addr = start;
161         int nr_pages = (end - start) / PAGE_SIZE;
162         int gup_flags;
163
164         VM_BUG_ON(start & ~PAGE_MASK);
165         VM_BUG_ON(end   & ~PAGE_MASK);
166         VM_BUG_ON(start < vma->vm_start);
167         VM_BUG_ON(end   > vma->vm_end);
168         VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
169
170         gup_flags = FOLL_TOUCH | FOLL_MLOCK;
171         /*
172          * We want to touch writable mappings with a write fault in order
173          * to break COW, except for shared mappings because these don't COW
174          * and we would not want to dirty them for nothing.
175          */
176         if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
177                 gup_flags |= FOLL_WRITE;
178
179         /*
180          * We want mlock to succeed for regions that have any permissions
181          * other than PROT_NONE.
182          */
183         if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
184                 gup_flags |= FOLL_FORCE;
185
186         return __get_user_pages(current, mm, addr, nr_pages, gup_flags,
187                                 NULL, NULL, nonblocking);
188 }
189
190 /*
191  * convert get_user_pages() return value to posix mlock() error
192  */
193 static int __mlock_posix_error_return(long retval)
194 {
195         if (retval == -EFAULT)
196                 retval = -ENOMEM;
197         else if (retval == -ENOMEM)
198                 retval = -EAGAIN;
199         return retval;
200 }
201
202 /**
203  * mlock_vma_pages_range() - mlock pages in specified vma range.
204  * @vma - the vma containing the specfied address range
205  * @start - starting address in @vma to mlock
206  * @end   - end address [+1] in @vma to mlock
207  *
208  * For mmap()/mremap()/expansion of mlocked vma.
209  *
210  * return 0 on success for "normal" vmas.
211  *
212  * return number of pages [> 0] to be removed from locked_vm on success
213  * of "special" vmas.
214  */
215 long mlock_vma_pages_range(struct vm_area_struct *vma,
216                         unsigned long start, unsigned long end)
217 {
218         int nr_pages = (end - start) / PAGE_SIZE;
219         BUG_ON(!(vma->vm_flags & VM_LOCKED));
220
221         /*
222          * filter unlockable vmas
223          */
224         if (vma->vm_flags & (VM_IO | VM_PFNMAP))
225                 goto no_mlock;
226
227         if (!((vma->vm_flags & VM_DONTEXPAND) ||
228                         is_vm_hugetlb_page(vma) ||
229                         vma == get_gate_vma(current->mm))) {
230
231                 __mlock_vma_pages_range(vma, start, end, NULL);
232
233                 /* Hide errors from mmap() and other callers */
234                 return 0;
235         }
236
237         /*
238          * User mapped kernel pages or huge pages:
239          * make these pages present to populate the ptes, but
240          * fall thru' to reset VM_LOCKED--no need to unlock, and
241          * return nr_pages so these don't get counted against task's
242          * locked limit.  huge pages are already counted against
243          * locked vm limit.
244          */
245         make_pages_present(start, end);
246
247 no_mlock:
248         vma->vm_flags &= ~VM_LOCKED;    /* and don't come back! */
249         return nr_pages;                /* error or pages NOT mlocked */
250 }
251
252 /*
253  * munlock_vma_pages_range() - munlock all pages in the vma range.'
254  * @vma - vma containing range to be munlock()ed.
255  * @start - start address in @vma of the range
256  * @end - end of range in @vma.
257  *
258  *  For mremap(), munmap() and exit().
259  *
260  * Called with @vma VM_LOCKED.
261  *
262  * Returns with VM_LOCKED cleared.  Callers must be prepared to
263  * deal with this.
264  *
265  * We don't save and restore VM_LOCKED here because pages are
266  * still on lru.  In unmap path, pages might be scanned by reclaim
267  * and re-mlocked by try_to_{munlock|unmap} before we unmap and
268  * free them.  This will result in freeing mlocked pages.
269  */
270 void munlock_vma_pages_range(struct vm_area_struct *vma,
271                              unsigned long start, unsigned long end)
272 {
273         unsigned long addr;
274
275         lru_add_drain();
276         vma->vm_flags &= ~VM_LOCKED;
277
278         for (addr = start; addr < end; addr += PAGE_SIZE) {
279                 struct page *page;
280                 /*
281                  * Although FOLL_DUMP is intended for get_dump_page(),
282                  * it just so happens that its special treatment of the
283                  * ZERO_PAGE (returning an error instead of doing get_page)
284                  * suits munlock very well (and if somehow an abnormal page
285                  * has sneaked into the range, we won't oops here: great).
286                  */
287                 page = follow_page(vma, addr, FOLL_GET | FOLL_DUMP);
288                 if (page && !IS_ERR(page)) {
289                         lock_page(page);
290                         munlock_vma_page(page);
291                         unlock_page(page);
292                         put_page(page);
293                 }
294                 cond_resched();
295         }
296 }
297
298 /*
299  * mlock_fixup  - handle mlock[all]/munlock[all] requests.
300  *
301  * Filters out "special" vmas -- VM_LOCKED never gets set for these, and
302  * munlock is a no-op.  However, for some special vmas, we go ahead and
303  * populate the ptes via make_pages_present().
304  *
305  * For vmas that pass the filters, merge/split as appropriate.
306  */
307 static int mlock_fixup(struct vm_area_struct *vma, struct vm_area_struct **prev,
308         unsigned long start, unsigned long end, vm_flags_t newflags)
309 {
310         struct mm_struct *mm = vma->vm_mm;
311         pgoff_t pgoff;
312         int nr_pages;
313         int ret = 0;
314         int lock = !!(newflags & VM_LOCKED);
315
316         if (newflags == vma->vm_flags || (vma->vm_flags & VM_SPECIAL) ||
317             is_vm_hugetlb_page(vma) || vma == get_gate_vma(current->mm))
318                 goto out;       /* don't set VM_LOCKED,  don't count */
319
320         pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
321         *prev = vma_merge(mm, *prev, start, end, newflags, vma->anon_vma,
322                           vma->vm_file, pgoff, vma_policy(vma));
323         if (*prev) {
324                 vma = *prev;
325                 goto success;
326         }
327
328         if (start != vma->vm_start) {
329                 ret = split_vma(mm, vma, start, 1);
330                 if (ret)
331                         goto out;
332         }
333
334         if (end != vma->vm_end) {
335                 ret = split_vma(mm, vma, end, 0);
336                 if (ret)
337                         goto out;
338         }
339
340 success:
341         /*
342          * Keep track of amount of locked VM.
343          */
344         nr_pages = (end - start) >> PAGE_SHIFT;
345         if (!lock)
346                 nr_pages = -nr_pages;
347         mm->locked_vm += nr_pages;
348
349         /*
350          * vm_flags is protected by the mmap_sem held in write mode.
351          * It's okay if try_to_unmap_one unmaps a page just after we
352          * set VM_LOCKED, __mlock_vma_pages_range will bring it back.
353          */
354
355         if (lock)
356                 vma->vm_flags = newflags;
357         else
358                 munlock_vma_pages_range(vma, start, end);
359
360 out:
361         *prev = vma;
362         return ret;
363 }
364
365 static int do_mlock(unsigned long start, size_t len, int on)
366 {
367         unsigned long nstart, end, tmp;
368         struct vm_area_struct * vma, * prev;
369         int error;
370
371         VM_BUG_ON(start & ~PAGE_MASK);
372         VM_BUG_ON(len != PAGE_ALIGN(len));
373         end = start + len;
374         if (end < start)
375                 return -EINVAL;
376         if (end == start)
377                 return 0;
378         vma = find_vma(current->mm, start);
379         if (!vma || vma->vm_start > start)
380                 return -ENOMEM;
381
382         prev = vma->vm_prev;
383         if (start > vma->vm_start)
384                 prev = vma;
385
386         for (nstart = start ; ; ) {
387                 vm_flags_t newflags;
388
389                 /* Here we know that  vma->vm_start <= nstart < vma->vm_end. */
390
391                 newflags = vma->vm_flags | VM_LOCKED;
392                 if (!on)
393                         newflags &= ~VM_LOCKED;
394
395                 tmp = vma->vm_end;
396                 if (tmp > end)
397                         tmp = end;
398                 error = mlock_fixup(vma, &prev, nstart, tmp, newflags);
399                 if (error)
400                         break;
401                 nstart = tmp;
402                 if (nstart < prev->vm_end)
403                         nstart = prev->vm_end;
404                 if (nstart >= end)
405                         break;
406
407                 vma = prev->vm_next;
408                 if (!vma || vma->vm_start != nstart) {
409                         error = -ENOMEM;
410                         break;
411                 }
412         }
413         return error;
414 }
415
416 static int do_mlock_pages(unsigned long start, size_t len, int ignore_errors)
417 {
418         struct mm_struct *mm = current->mm;
419         unsigned long end, nstart, nend;
420         struct vm_area_struct *vma = NULL;
421         int locked = 0;
422         int ret = 0;
423
424         VM_BUG_ON(start & ~PAGE_MASK);
425         VM_BUG_ON(len != PAGE_ALIGN(len));
426         end = start + len;
427
428         for (nstart = start; nstart < end; nstart = nend) {
429                 /*
430                  * We want to fault in pages for [nstart; end) address range.
431                  * Find first corresponding VMA.
432                  */
433                 if (!locked) {
434                         locked = 1;
435                         down_read(&mm->mmap_sem);
436                         vma = find_vma(mm, nstart);
437                 } else if (nstart >= vma->vm_end)
438                         vma = vma->vm_next;
439                 if (!vma || vma->vm_start >= end)
440                         break;
441                 /*
442                  * Set [nstart; nend) to intersection of desired address
443                  * range with the first VMA. Also, skip undesirable VMA types.
444                  */
445                 nend = min(end, vma->vm_end);
446                 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
447                         continue;
448                 if (nstart < vma->vm_start)
449                         nstart = vma->vm_start;
450                 /*
451                  * Now fault in a range of pages. __mlock_vma_pages_range()
452                  * double checks the vma flags, so that it won't mlock pages
453                  * if the vma was already munlocked.
454                  */
455                 ret = __mlock_vma_pages_range(vma, nstart, nend, &locked);
456                 if (ret < 0) {
457                         if (ignore_errors) {
458                                 ret = 0;
459                                 continue;       /* continue at next VMA */
460                         }
461                         ret = __mlock_posix_error_return(ret);
462                         break;
463                 }
464                 nend = nstart + ret * PAGE_SIZE;
465                 ret = 0;
466         }
467         if (locked)
468                 up_read(&mm->mmap_sem);
469         return ret;     /* 0 or negative error code */
470 }
471
472 SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
473 {
474         unsigned long locked;
475         unsigned long lock_limit;
476         int error = -ENOMEM;
477
478         if (!can_do_mlock())
479                 return -EPERM;
480
481         lru_add_drain_all();    /* flush pagevec */
482
483         down_write(&current->mm->mmap_sem);
484         len = PAGE_ALIGN(len + (start & ~PAGE_MASK));
485         start &= PAGE_MASK;
486
487         locked = len >> PAGE_SHIFT;
488         locked += current->mm->locked_vm;
489
490         lock_limit = rlimit(RLIMIT_MEMLOCK);
491         lock_limit >>= PAGE_SHIFT;
492
493         /* check against resource limits */
494         if ((locked <= lock_limit) || capable(CAP_IPC_LOCK))
495                 error = do_mlock(start, len, 1);
496         up_write(&current->mm->mmap_sem);
497         if (!error)
498                 error = do_mlock_pages(start, len, 0);
499         return error;
500 }
501
502 SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len)
503 {
504         int ret;
505
506         down_write(&current->mm->mmap_sem);
507         len = PAGE_ALIGN(len + (start & ~PAGE_MASK));
508         start &= PAGE_MASK;
509         ret = do_mlock(start, len, 0);
510         up_write(&current->mm->mmap_sem);
511         return ret;
512 }
513
514 static int do_mlockall(int flags)
515 {
516         struct vm_area_struct * vma, * prev = NULL;
517         unsigned int def_flags = 0;
518
519         if (flags & MCL_FUTURE)
520                 def_flags = VM_LOCKED;
521         current->mm->def_flags = def_flags;
522         if (flags == MCL_FUTURE)
523                 goto out;
524
525         for (vma = current->mm->mmap; vma ; vma = prev->vm_next) {
526                 vm_flags_t newflags;
527
528                 newflags = vma->vm_flags | VM_LOCKED;
529                 if (!(flags & MCL_CURRENT))
530                         newflags &= ~VM_LOCKED;
531
532                 /* Ignore errors */
533                 mlock_fixup(vma, &prev, vma->vm_start, vma->vm_end, newflags);
534         }
535 out:
536         return 0;
537 }
538
539 SYSCALL_DEFINE1(mlockall, int, flags)
540 {
541         unsigned long lock_limit;
542         int ret = -EINVAL;
543
544         if (!flags || (flags & ~(MCL_CURRENT | MCL_FUTURE)))
545                 goto out;
546
547         ret = -EPERM;
548         if (!can_do_mlock())
549                 goto out;
550
551         if (flags & MCL_CURRENT)
552                 lru_add_drain_all();    /* flush pagevec */
553
554         down_write(&current->mm->mmap_sem);
555
556         lock_limit = rlimit(RLIMIT_MEMLOCK);
557         lock_limit >>= PAGE_SHIFT;
558
559         ret = -ENOMEM;
560         if (!(flags & MCL_CURRENT) || (current->mm->total_vm <= lock_limit) ||
561             capable(CAP_IPC_LOCK))
562                 ret = do_mlockall(flags);
563         up_write(&current->mm->mmap_sem);
564         if (!ret && (flags & MCL_CURRENT)) {
565                 /* Ignore errors */
566                 do_mlock_pages(0, TASK_SIZE, 1);
567         }
568 out:
569         return ret;
570 }
571
572 SYSCALL_DEFINE0(munlockall)
573 {
574         int ret;
575
576         down_write(&current->mm->mmap_sem);
577         ret = do_mlockall(0);
578         up_write(&current->mm->mmap_sem);
579         return ret;
580 }
581
582 /*
583  * Objects with different lifetime than processes (SHM_LOCK and SHM_HUGETLB
584  * shm segments) get accounted against the user_struct instead.
585  */
586 static DEFINE_SPINLOCK(shmlock_user_lock);
587
588 int user_shm_lock(size_t size, struct user_struct *user)
589 {
590         unsigned long lock_limit, locked;
591         int allowed = 0;
592
593         locked = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
594         lock_limit = rlimit(RLIMIT_MEMLOCK);
595         if (lock_limit == RLIM_INFINITY)
596                 allowed = 1;
597         lock_limit >>= PAGE_SHIFT;
598         spin_lock(&shmlock_user_lock);
599         if (!allowed &&
600             locked + user->locked_shm > lock_limit && !capable(CAP_IPC_LOCK))
601                 goto out;
602         get_uid(user);
603         user->locked_shm += locked;
604         allowed = 1;
605 out:
606         spin_unlock(&shmlock_user_lock);
607         return allowed;
608 }
609
610 void user_shm_unlock(size_t size, struct user_struct *user)
611 {
612         spin_lock(&shmlock_user_lock);
613         user->locked_shm -= (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
614         spin_unlock(&shmlock_user_lock);
615         free_uid(user);
616 }