[PATCH 0/2] mm/mprotect: avoid unnecessary TLB flushes

From: Nadav Amit
Date: Sun Sep 26 2021 - 00:32:02 EST

From: Nadav Amit <namit@xxxxxxxxxx>

This patch-set is based on a very small subset of an old RFC (see link
below), and intended to avoid TLB flushes when they are not necessary
architecturally. Specifically, memory-unprotect using userfaultfd
(i.e., using userfaultfd IOCTL) triggers a TLB flush when in fact no
architectural data, other than a software flag, is updated. This
overhead shows up in my development workload profiles.

Instead of tailoring a solution for this specific scenario, it is
arguably better to use this opportunity to consolidate the interfaces
that are used for TLB batching, avoid the open-coded
[inc|dec]_tlb_flush_pending() and use the tlb_[gather|finish]_mmu()
interface instead.

Avoiding the TLB flushes is done very conservatively (unlike the RFC):
1. According to x86 specifications no flushes are necessary on
permission promotion and changes to software bits.
2. Linux does not flush PTEs after the access bit is cleared.

I considered the feedback of Andy Lutomirski and Andrew Cooper for the
RFC regarding avoiding TLB invalidations when RW is cleared for clean
PTEs. Although the bugs they pointed out can be easily addressed, I am
concerned since I could not find specifications that explicitly clarify
this optimization is valid.


RFC -> v1:
* Do not skip TLB flushes when clearing RW on clean PTEs
* Do not defer huge PMD flush as it is already done inline

Link: https://lore.kernel.org/lkml/20210131001132.3368247-1-namit@xxxxxxxxxx/
Cc: Andrea Arcangeli <aarcange@xxxxxxxxxx>
Cc: Andrew Cooper <andrew.cooper3@xxxxxxxxxx>
Cc: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
Cc: Andy Lutomirski <luto@xxxxxxxxxx>
Cc: Dave Hansen <dave.hansen@xxxxxxxxxxxxxxx>
Cc: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
Cc: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
Cc: Will Deacon <will@xxxxxxxxxx>
Cc: Yu Zhao <yuzhao@xxxxxxxxxx>
Cc: Nick Piggin <npiggin@xxxxxxxxx>
Cc: x86@xxxxxxxxxx

Nadav Amit (2):
mm/mprotect: use mmu_gather
mm/mprotect: do not flush on permission promotion

arch/x86/include/asm/tlbflush.h | 40 ++++++++++++++++++++++++++
include/asm-generic/tlb.h | 4 +++
mm/mprotect.c | 51 +++++++++++++++++++--------------
3 files changed, 73 insertions(+), 22 deletions(-)