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>
9 #include <asm/pgtable.h>
12 * Hash based on the pmd of addr if configured with MMU, which provides a good
13 * hit rate for workloads with spatial locality. Otherwise, use pages.
16 #define VMACACHE_SHIFT PMD_SHIFT
18 #define VMACACHE_SHIFT PAGE_SHIFT
20 #define VMACACHE_HASH(addr) ((addr >> VMACACHE_SHIFT) & VMACACHE_MASK)
23 * This task may be accessing a foreign mm via (for example)
24 * get_user_pages()->find_vma(). The vmacache is task-local and this
25 * task's vmacache pertains to a different mm (ie, its own). There is
26 * nothing we can do here.
28 * Also handle the case where a kernel thread has adopted this mm via use_mm().
29 * That kernel thread's vmacache is not applicable to this mm.
31 static inline bool vmacache_valid_mm(struct mm_struct *mm)
33 return current->mm == mm && !(current->flags & PF_KTHREAD);
36 void vmacache_update(unsigned long addr, struct vm_area_struct *newvma)
38 if (vmacache_valid_mm(newvma->vm_mm))
39 current->vmacache.vmas[VMACACHE_HASH(addr)] = newvma;
42 static bool vmacache_valid(struct mm_struct *mm)
44 struct task_struct *curr;
46 if (!vmacache_valid_mm(mm))
50 if (mm->vmacache_seqnum != curr->vmacache.seqnum) {
52 * First attempt will always be invalid, initialize
53 * the new cache for this task here.
55 curr->vmacache.seqnum = mm->vmacache_seqnum;
62 struct vm_area_struct *vmacache_find(struct mm_struct *mm, unsigned long addr)
64 int idx = VMACACHE_HASH(addr);
67 count_vm_vmacache_event(VMACACHE_FIND_CALLS);
69 if (!vmacache_valid(mm))
72 for (i = 0; i < VMACACHE_SIZE; i++) {
73 struct vm_area_struct *vma = current->vmacache.vmas[idx];
76 #ifdef CONFIG_DEBUG_VM_VMACACHE
77 if (WARN_ON_ONCE(vma->vm_mm != mm))
80 if (vma->vm_start <= addr && vma->vm_end > addr) {
81 count_vm_vmacache_event(VMACACHE_FIND_HITS);
85 if (++idx == VMACACHE_SIZE)
93 struct vm_area_struct *vmacache_find_exact(struct mm_struct *mm,
97 int idx = VMACACHE_HASH(start);
100 count_vm_vmacache_event(VMACACHE_FIND_CALLS);
102 if (!vmacache_valid(mm))
105 for (i = 0; i < VMACACHE_SIZE; i++) {
106 struct vm_area_struct *vma = current->vmacache.vmas[idx];
108 if (vma && vma->vm_start == start && vma->vm_end == end) {
109 count_vm_vmacache_event(VMACACHE_FIND_HITS);
112 if (++idx == VMACACHE_SIZE)