1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2014 Davidlohr Bueso.
5 #include <linux/sched/signal.h>
6 #include <linux/sched/task.h>
8 #include <linux/vmacache.h>
11 * Hash based on the pmd of addr if configured with MMU, which provides a good
12 * hit rate for workloads with spatial locality. Otherwise, use pages.
15 #define VMACACHE_SHIFT PMD_SHIFT
17 #define VMACACHE_SHIFT PAGE_SHIFT
19 #define VMACACHE_HASH(addr) ((addr >> VMACACHE_SHIFT) & VMACACHE_MASK)
22 * This task may be accessing a foreign mm via (for example)
23 * get_user_pages()->find_vma(). The vmacache is task-local and this
24 * task's vmacache pertains to a different mm (ie, its own). There is
25 * nothing we can do here.
27 * Also handle the case where a kernel thread has adopted this mm via
28 * kthread_use_mm(). That kernel thread's vmacache is not applicable to this mm.
30 static inline bool vmacache_valid_mm(struct mm_struct *mm)
32 return current->mm == mm && !(current->flags & PF_KTHREAD);
35 void vmacache_update(unsigned long addr, struct vm_area_struct *newvma)
37 if (vmacache_valid_mm(newvma->vm_mm))
38 current->vmacache.vmas[VMACACHE_HASH(addr)] = newvma;
41 static bool vmacache_valid(struct mm_struct *mm)
43 struct task_struct *curr;
45 if (!vmacache_valid_mm(mm))
49 if (mm->vmacache_seqnum != curr->vmacache.seqnum) {
51 * First attempt will always be invalid, initialize
52 * the new cache for this task here.
54 curr->vmacache.seqnum = mm->vmacache_seqnum;
61 struct vm_area_struct *vmacache_find(struct mm_struct *mm, unsigned long addr)
63 int idx = VMACACHE_HASH(addr);
66 count_vm_vmacache_event(VMACACHE_FIND_CALLS);
68 if (!vmacache_valid(mm))
71 for (i = 0; i < VMACACHE_SIZE; i++) {
72 struct vm_area_struct *vma = current->vmacache.vmas[idx];
75 #ifdef CONFIG_DEBUG_VM_VMACACHE
76 if (WARN_ON_ONCE(vma->vm_mm != mm))
79 if (vma->vm_start <= addr && vma->vm_end > addr) {
80 count_vm_vmacache_event(VMACACHE_FIND_HITS);
84 if (++idx == VMACACHE_SIZE)
92 struct vm_area_struct *vmacache_find_exact(struct mm_struct *mm,
96 int idx = VMACACHE_HASH(start);
99 count_vm_vmacache_event(VMACACHE_FIND_CALLS);
101 if (!vmacache_valid(mm))
104 for (i = 0; i < VMACACHE_SIZE; i++) {
105 struct vm_area_struct *vma = current->vmacache.vmas[idx];
107 if (vma && vma->vm_start == start && vma->vm_end == end) {
108 count_vm_vmacache_event(VMACACHE_FIND_HITS);
111 if (++idx == VMACACHE_SIZE)