binder: split alloc->mutex to improve performance
v2 cover binder: split alloc->mutex to improve performance
Hi,
This is v2 of the binder alloc lock optimization. Thanks to Alice Ryhl for the thorough review of v1 [1].
v1 simply converted alloc->mutex to a spinlock, but Alice pointed out a race between page installation and shrinker's zap_vma_range() [2], and that busy-wait retry would deadlock with SCHED_FIFO threads [3].
v2 splits the lock into two:
- spinlock: protects buffer metadata (rb-trees, free_async_space, LRU operations) on the hot path (every binder transaction).
- install_mutex: serializes page installation and shrinker zap on the cold path only when pages are installed or reclaimed.
The install_mutex ensures pages[index]=NULL and zap_vma_range() are atomic to the install side, eliminating the race from v1. Since install_mutex serializes all installers, binder_page_lookup() (GUP) is no longer needed.
When binder_lru_freelist_del() finds a page already isolated by the shrinker (when list_lru_del returns false), it rolls back and returns -EAGAIN. The caller waits for the shrinker via mutex_lock/unlock on install_mutex, which is safe for SCHED_FIFO (sleeps instead of spins).
Performance (binderThroughputTest, Qualcomm SM8850, 2 workers, 10 runs):
mutex (baseline) spinlock + install_mutex
throughput: 27k-59k iter/s 81k-94k iter/s (~80% improvement) average: 0.031-0.068ms 0.020-0.023ms (~45% reduction) P99: 0.088-0.148ms 0.047-0.061ms (~55% reduction)
Tested under memory pressure (concurrent drop_caches) to exercise the install_mutex and shrinker paths. No regression compared to the pure spinlock approach in v1.
Changes since v1:
- Dropped the simple spinlock-only approach that had a race between page installation and shrinker zap (Alice)
- Added install_mutex to serialize page install and shrinker zap
- Removed binder_page_lookup() (GUP) since install_mutex serializes concurrent installers
- Handle list_lru_del() failure in binder_lru_freelist_del() with rollback and -EAGAIN, wait on install_mutex instead of busy-wait to avoid SCHED_FIFO deadlock (Alice)
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
Bo Zhang (2):
binder: switch alloc->mutex to spinlock for buffer metadata
binder: add install_mutex to serialize page install and shrinker zap
drivers/android/binder_alloc.c | 114 ++++++++++++++++++++++----------- drivers/android/binder_alloc.h | 11 ++-- 2 files changed, 85 insertions(+), 40 deletions(-)
Signature · 1 line
2.34.1
RFC PATCH v2 1/2 binder: switch alloc->mutex to spinlock for buffer metadata
The alloc->mutex is a highly contended lock on Android devices. When a low-priority task holds this mutex and sleeps, high-priority binder transactions are blocked, causing priority inversion and latency spikes.
Split the lock by converting alloc->mutex to a spinlock that only protects buffer metadata. This eliminates the sleeping and priority inversion on the hot path.
Page installation and shrinker zap serialization is handled separately by a dedicated install_mutex introduced in the next patch.
Performance (binderThroughputTest, SM8850, 2 workers, 10 runs):
mutex spinlock
throughput: 27k-59k iter/s 79k-84k iter/s average: 0.031-0.068ms 0.022-0.023ms P99: 0.088-0.148ms 0.050-0.062ms
--- drivers/android/binder_alloc.c | 36 +++++++++++++++++----------------- drivers/android/binder_alloc.h | 8 ++++---- 2 files changed, 22 insertions(+), 22 deletions(-)
drivers/android/binder_alloc.c +18 -18
@@ -169,7 +169,7 @@ static struct binder_buffer *binder_alloc_prepare_to_free_locked(struct binder_buffer *binder_alloc_prepare_to_free (struct binder_alloc *alloc,unsigned long user_ptr) { -guard (mutex)(&alloc->mutex); +guard (spinlock)(&alloc->lock);return binder_alloc_prepare_to_free_locked (alloc, user_ptr); }
@@ -676,10 +676,10 @@ struct binder_buffer *binder_alloc_new_buf(struct binder_alloc *alloc,if (!next)return ERR_PTR (-ENOMEM ); -mutex_lock (&alloc->mutex); +spin_lock (&alloc->lock); buffer =binder_alloc_new_buf_locked (alloc, next, size, is_async);if (IS_ERR (buffer)) { -mutex_unlock (&alloc->mutex); +spin_unlock (&alloc->lock); goto out; }
@@ -687,7 +687,7 @@ struct binder_buffer *binder_alloc_new_buf(struct binder_alloc *alloc, buffer->offsets_size = offsets_size; buffer->extra_buffers_size = extra_buffers_size; buffer->pid = current->tgid; -mutex_unlock (&alloc->mutex); +spin_unlock (&alloc->lock); ret =binder_install_buffer_pages (alloc, buffer, size);if (ret) {
@@ -872,9 +872,9 @@ void binder_alloc_free_buf(struct binder_alloc *alloc,binder_alloc_clear_buf (alloc, buffer); buffer->clear_on_free = false; } -mutex_lock (&alloc->mutex); +spin_lock (&alloc->lock);binder_free_buf_locked (alloc, buffer); -mutex_unlock (&alloc->mutex); +spin_unlock (&alloc->lock); }EXPORT_SYMBOL_IF_KUNIT (binder_alloc_free_buf);
@@ -967,7 +967,7 @@ void binder_alloc_deferred_release(struct binder_alloc *alloc)struct binder_buffer *buffer; buffers =0 ; -mutex_lock (&alloc->mutex); +spin_lock (&alloc->lock);BUG_ON (alloc->mapped);while ((n =rb_first (&alloc->allocated_buffers))) {
@@ -1018,7 +1018,7 @@ void binder_alloc_deferred_release(struct binder_alloc *alloc) page_count++; } } -mutex_unlock (&alloc->mutex); +spin_unlock (&alloc->lock);kvfree (alloc->pages);if (alloc->mm)mmdrop (alloc->mm);
@@ -1043,7 +1043,7 @@ void binder_alloc_print_allocated(struct seq_file *m,struct binder_buffer *buffer;struct rb_node *n; -guard (mutex)(&alloc->mutex); +guard (spinlock)(&alloc->lock);for (n =rb_first (&alloc->allocated_buffers); n; n =rb_next (n)) { buffer = rb_entry(n, struct binder_buffer, rb_node); seq_printf(m, " buffer %d: %lx size %zd:%zd:%zd %s\n",
@@ -1069,7 +1069,7 @@ void binder_alloc_print_pages(struct seq_file *m,int lru =0 ;int free =0 ; -mutex_lock (&alloc->mutex); +spin_lock (&alloc->lock);/* * Make sure the binder_alloc is fully initialized, otherwise we might * read inconsistent state.
@@ -1085,7 +1085,7 @@ void binder_alloc_print_pages(struct seq_file *m, lru++; } } -mutex_unlock (&alloc->mutex); +spin_unlock (&alloc->lock);seq_printf (m," pages: %d:%d:%d\n" , active, lru, free);seq_printf (m," pages high watermark: %zu\n" , alloc->pages_high); }
@@ -1101,7 +1101,7 @@ int binder_alloc_get_allocated_count(struct binder_alloc *alloc)struct rb_node *n;int count =0 ; -guard (mutex)(&alloc->mutex); +guard (spinlock)(&alloc->lock);for (n =rb_first (&alloc->allocated_buffers); n !=NULL ; n =rb_next (n)) count++;return count;
@@ -1161,8 +1161,8 @@ enum lru_status binder_alloc_free_page(struct list_head *item, vma =vma_lookup (mm, page_addr); } -if (!mutex_trylock (&alloc->mutex)) - goto err_get_alloc_mutex_failed; +if (!spin_trylock (&alloc->lock)) + goto err_get_alloc_lock_failed;/* * Since a binder_alloc can only be mapped once, we ensure
@@ -1180,6 +1180,7 @@ enum lru_status binder_alloc_free_page(struct list_head *item,trace_binder_unmap_kernel_end (alloc, index);list_lru_isolate (lru, item); +spin_unlock (&alloc->lock);spin_unlock (&lru->lock);if (vma) {
@@ -1190,7 +1191,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,trace_binder_unmap_user_end (alloc, index); } -mutex_unlock (&alloc->mutex);if (mm_locked)mmap_read_unlock (mm);else
@@ -1201,8 +1201,8 @@ enum lru_status binder_alloc_free_page(struct list_head *item,return LRU_REMOVED_RETRY ; err_invalid_vma: -mutex_unlock (&alloc->mutex); -err_get_alloc_mutex_failed: +spin_unlock (&alloc->lock); +err_get_alloc_lock_failed:if (mm_locked)mmap_read_unlock (mm);else
@@ -1235,7 +1235,7 @@ VISIBLE_IF_KUNIT void __binder_alloc_init(struct binder_alloc *alloc, alloc->pid = current->tgid; alloc->mm = current->mm;mmgrab (alloc->mm); -mutex_init (&alloc->mutex); +spin_lock_init (&alloc->lock);INIT_LIST_HEAD (&alloc->buffers); alloc->freelist = freelist; }
drivers/android/binder_alloc.h +4 -4
@@ -9,7 +9,7 @@#include <linux/rbtree.h> #include <linux/list.h> #include <linux/mm.h> -#include <linux/rtmutex.h> +#include <linux/spinlock.h> #include <linux/vmalloc.h> #include <linux/slab.h> #include <linux/list_lru.h>
@@ -80,7 +80,7 @@ static inline struct list_head *page_to_lru(struct page *p)/** * struct binder_alloc - per-binder proc state for binder allocator -* @mutex: protects binder_alloc fields +* @lock: protects binder_alloc fields * @mm: copy of task->mm (invariant after open) * @vm_start: base of per-proc address space mapped via mmap * @buffers: list of all buffers for this proc
@@ -105,7 +105,7 @@ static inline struct list_head *page_to_lru(struct page *p)* struct binder_buffer objects used to track the user buffers */ struct binder_alloc { -struct mutex mutex; +spinlock_t lock;struct mm_struct *mm;unsigned long vm_start;struct list_head buffers;
@@ -156,7 +156,7 @@ void binder_alloc_print_pages(struct seq_file *m,static inline size_t binder_alloc_get_free_async_space (struct binder_alloc *alloc) { -guard (mutex)(&alloc->mutex); +guard (spinlock)(&alloc->lock);return alloc->free_async_space; }
Signature · 1 line
2.34.1
Re: [RFC PATCH v2 1/2] binder: switch alloc->mutex to spinlock for buffer metadata
drivers/android/binder_alloc.c void binder_alloc_deferred_release(struct binder_alloc *alloc) · line 973
Quoted 9 lines · Bo Zhang
drivers/android/binder_alloc.c +1
-1@@ -967,7 +967,7 @@ void binder_alloc_deferred_release(struct binder_alloc *alloc)struct binder_buffer *buffer; buffers =0 ; -mutex_lock (&alloc->mutex); +spin_lock (&alloc->lock);BUG_ON (alloc->mapped);while ((n =rb_first (&alloc->allocated_buffers))) {
Sashiko says
"Does this conversion to a spinlock introduce an unbounded preemption latency regression during binder teardown?
Inside this spinlock-protected section, if a buffer is marked clear_on_free, binder_alloc_clear_buf() uses memset_page() to zero out up to 4MB of memory. Subsequently, the function also iterates over up to 1024 pages in the same locked section, calling binder_free_page() for each.
Could performing massive memory zeroing and over a thousand page frees while holding a spinlock disable preemption for multiple milliseconds, creating a latency spike on exit or crash?"
This behavior is not introduced by this series. It matches the original spinlock implementation in commit 7710e2cca32e ("binder: switch alloc->mutex to spinlock_t"), which was reviewed and merged upstream (later reverted for unrelated reasons in commit 8b52c7261e04).
binder_alloc_deferred_release() is a cold teardown path, executed only once when the binder proc is released (from binder_free_proc(), right before kfree(proc)). It is not the hot transaction path this series optimizes. At that point the proc has been detached and alloc->mapped is false, so there are no concurrent binder transactions.
I've kept it aligned with the previously-accepted spinlock version to keep this series focused on the lock split. Reducing teardown preemption latency, if desired, would be better addressed as a separate patch.
Bo
RFC PATCH v2 2/2 binder: add install_mutex to serialize page install and shrinker zap
In reply to Bo ZhangThe previous patch converted alloc->mutex to a spinlock for the hot path (buffer alloc/free). However, this leaves page installation and shrinker's zap_vma_range() unserialized, which can cause use-after-free as identified by Alice Ryhl.
Add a separate install_mutex to serialize page installation against the shrinker's page reclaim (pages[index]=NULL + zap_vma_range). This mutex is only contended on the cold path when pages need to be installed or reclaimed, not on the hot path.
Key changes:
- binder_install_single_page() holds install_mutex across the entire install sequence, eliminating the need for binder_page_lookup() (GUP) since concurrent installers are now serialized.
- The shrinker holds install_mutex across pages[index]=NULL and zap_vma_range(), making them atomic to the install side.
- binder_lru_freelist_del() returns -EAGAIN when list_lru_del() fails (shrinker already isolated the page), with rollback of any pages already removed from the LRU. The caller waits on install_mutex for the shrinker to finish, then retries.
- EBUSY from vm_insert_page() is handled defensively with -EAGAIN, though it should not occur under install_mutex serialization.
Performance with memory pressure (binderThroughputTest, SM8850, 2 workers, 10 runs, concurrent drop_caches) shows no regression from the install_mutex:
mutex (baseline) spinlock + install_mutex
throughput: 27k-59k iter/s 81k-94k iter/s average: 0.031-0.068ms 0.020-0.023ms P99: 0.088-0.148ms 0.047-0.061ms
--- drivers/android/binder_alloc.c | 75 ++++++++++++++++++++++++++-------- drivers/android/binder_alloc.h | 3 ++ 2 files changed, 60 insertions(+), 18 deletions(-)
drivers/android/binder_alloc.c +57 -18
@@ -325,24 +325,28 @@ static int binder_install_single_page(struct binder_alloc *alloc, goto out; } +mutex_lock (&alloc->install_mutex); + +/* Check again under install_mutex */ +if (binder_get_installed_page (alloc, index)) { +mutex_unlock (&alloc->install_mutex); +binder_free_page (page); + ret =0 ; + goto out; + } + ret =binder_page_insert (alloc, addr, page);switch (ret) {case -EBUSY :/* -* EBUSY is ok. Someone installed the pte first but the -* alloc->pages[index] has not been updated yet. Discard -* our page and look up the one already installed. +* This should not happen since install_mutex serializes +* all page installations and shrinker zaps. Handle it +* defensively by retrying. */ - ret =0 ;binder_free_page (page); - page =binder_page_lookup (alloc, addr); -if (!page) { -pr_err ("%d: failed to find page at offset %lx\n" , - alloc->pid, addr - alloc->vm_start); - ret = -ESRCH ; -break ; - } - fallthrough; +mutex_unlock (&alloc->install_mutex); + ret = -EAGAIN ; + goto out;case 0 :/* Mark page installation complete and safe to use */ binder_set_installed_page (alloc, index, page);
@@ -353,6 +357,8 @@ static int binder_install_single_page(struct binder_alloc *alloc, alloc->pid, __func__, addr - alloc->vm_start, ret);break ; } + +mutex_unlock (&alloc->install_mutex); out:mmput_async (alloc->mm);return ret;
@@ -377,8 +383,10 @@ static int binder_install_buffer_pages(struct binder_alloc *alloc,continue ;trace_binder_alloc_page_start (alloc, index); - +retry: ret =binder_install_single_page (alloc, index, page_addr); +if (ret == -EAGAIN ) + goto retry;if (ret)return ret;
@@ -389,7 +397,7 @@ static int binder_install_buffer_pages(struct binder_alloc *alloc, }/* The range of pages should exclude those shared with other buffers */ -static void binder_lru_freelist_del (struct binder_alloc *alloc, +static int binder_lru_freelist_del (struct binder_alloc *alloc,unsigned long start,unsigned long end) {unsigned long page_addr;
@@ -411,7 +419,16 @@ static void binder_lru_freelist_del(struct binder_alloc *alloc,page_to_lru (page),page_to_nid (page), NULL); -WARN_ON (!on_lru); +/* +* If !on_lru, the shrinker has already isolated this +* page and will reclaim it. Abort so the caller can +* retry after the shrinker finishes. +*/ +if (!on_lru) { +/* Rollback pages already removed from LRU */ +binder_lru_freelist_add (alloc, start, page_addr); +return -EAGAIN ; + }trace_binder_alloc_lru_end (alloc, index);continue ;
@@ -420,6 +437,8 @@ static void binder_lru_freelist_del(struct binder_alloc *alloc,if (index +1 > alloc->pages_high) alloc->pages_high = index +1 ; } + +return 0 ; }static void debug_no_space_locked (struct binder_alloc *alloc)
@@ -583,8 +602,12 @@ static struct binder_buffer *binder_alloc_new_buf_locked(*/ next_used_page = (buffer->user_data + buffer_size) &PAGE_MASK ; curr_last_page =PAGE_ALIGN (buffer->user_data + size); -binder_lru_freelist_del (alloc,PAGE_ALIGN (buffer->user_data), -min (next_used_page, curr_last_page)); +if (binder_lru_freelist_del (alloc,PAGE_ALIGN (buffer->user_data), +min (next_used_page, curr_last_page))) { +/* Shrinker is reclaiming a page we need. Undo and retry. */ + buffer =ERR_PTR (-EAGAIN ); + goto out; + }rb_erase (&buffer->rb_node, &alloc->free_buffers); buffer->free =0 ;
@@ -676,10 +699,21 @@ struct binder_buffer *binder_alloc_new_buf(struct binder_alloc *alloc,if (!next)return ERR_PTR (-ENOMEM ); +retry:spin_lock (&alloc->lock); buffer =binder_alloc_new_buf_locked (alloc, next, size, is_async);if (IS_ERR (buffer)) {spin_unlock (&alloc->lock); +if (PTR_ERR (buffer) == -EAGAIN ) { +/* +* Shrinker is reclaiming a page we need. +* Wait for it to finish by briefly acquiring +* install_mutex, then retry. +*/ +mutex_lock (&alloc->install_mutex); +mutex_unlock (&alloc->install_mutex); + goto retry; + } goto out; }
@@ -1175,7 +1209,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,trace_binder_unmap_kernel_start (alloc, index); page_to_free = alloc->pages[index]; -binder_set_installed_page (alloc, index,NULL );trace_binder_unmap_kernel_end (alloc, index);
@@ -1183,6 +1216,9 @@ enum lru_status binder_alloc_free_page(struct list_head *item,spin_unlock (&alloc->lock);spin_unlock (&lru->lock); +mutex_lock (&alloc->install_mutex); +binder_set_installed_page (alloc, index,NULL ); +if (vma) {trace_binder_unmap_user_start (alloc, index);
@@ -1191,6 +1227,8 @@ enum lru_status binder_alloc_free_page(struct list_head *item,trace_binder_unmap_user_end (alloc, index); } +mutex_unlock (&alloc->install_mutex); +if (mm_locked)mmap_read_unlock (mm);else
@@ -1236,6 +1274,7 @@ VISIBLE_IF_KUNIT void __binder_alloc_init(struct binder_alloc *alloc, alloc->mm = current->mm;mmgrab (alloc->mm);spin_lock_init (&alloc->lock); +mutex_init (&alloc->install_mutex);INIT_LIST_HEAD (&alloc->buffers); alloc->freelist = freelist; }
drivers/android/binder_alloc.h +3 -0
@@ -9,6 +9,7 @@#include <linux/rbtree.h> #include <linux/list.h> #include <linux/mm.h> +#include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/vmalloc.h> #include <linux/slab.h>
@@ -81,6 +82,7 @@ static inline struct list_head *page_to_lru(struct page *p)/** * struct binder_alloc - per-binder proc state for binder allocator * @lock: protects binder_alloc fields +* @install_mutex: serializes page installation and shrinker zap * @mm: copy of task->mm (invariant after open) * @vm_start: base of per-proc address space mapped via mmap * @buffers: list of all buffers for this proc
@@ -106,6 +108,7 @@ static inline struct list_head *page_to_lru(struct page *p)*/ struct binder_alloc {spinlock_t lock; +struct mutex install_mutex;struct mm_struct *mm;unsigned long vm_start;struct list_head buffers;
Signature · 1 line
2.34.1
Re: [RFC PATCH v2 2/2] binder: add install_mutex to serialize page install and shrinker zap
Thanks for the detailed review. Replying to the three points below.
1) ABBA deadlock between install_mutex and mmap_lock
Sashiko says
"Can this locking order cause an ABBA deadlock with the shrinker path? Here in binder_install_single_page(), alloc->install_mutex is acquired first, followed by memory locks (per-VMA read lock or mmap_read_lock) inside binder_page_insert(). However, in the shrinker callback binder_alloc_free_page(), the locks are acquired in the reverse order. If a concurrent writer is waiting on mmap_write_lock (which blocks new readers), could this inversion result in a deadlock?"
This is a real issue and I'll fix it in v3. The install side holds install_mutex and then falls back to a blocking mmap_read_lock(), while the shrinker holds mmap_lock and then takes install_mutex. With a writer pending on mmap_write_lock, the rwsem's writer-priority can turn this inversion into a deadlock.
The fix is to never block on mmap_lock while holding install_mutex. The mmap_lock fallback in binder_page_insert() becomes mmap_read_trylock(), and on contention it returns -EAGAIN. The caller then drops install_mutex and retries after waiting for mmap_lock to become available (without holding any binder lock), so the install side never holds install_mutex while blocked on mmap_lock. The per-VMA lock path is unaffected.
2) Potential infinite loop on -EBUSY
Sashiko says
"If vm_insert_page() persistently returns -EBUSY ... will this result in an infinite loop? Because the -EAGAIN return from binder_install_single_page() unconditionally jumps back to the retry label without sleeping or limiting the number of attempts, could this lead to a CPU lockup and local denial of service?"
Good catch. Under install_mutex the PTE should never be already populated, so -EBUSY is not expected. In v3 I'll stop treating -EBUSY as
retryable: it returns an error instead of -EAGAIN, so it can never loop. The -EAGAIN retry path is then only reached for genuine mmap_lock contention, where the retry waits on mmap_lock rather than busy-looping.
3) Use-after-free of the preallocated next buffer on retry
Sashiko says
"Does retrying on -EAGAIN here result in a use-after-free of the next buffer? ... the error path in binder_alloc_new_buf_locked() calls kfree(new_buffer) ... If we jump back to the retry label and pass the exact same freed pointer back into binder_alloc_new_buf_locked() ... Additionally, if the buffer was split prior to the -EAGAIN failure, the split is not rolled back."
You're right on both counts, thanks for catching this. In v3:
- binder_alloc_new_buf_locked() rolls back the split on the -EAGAIN path (rb_erase() + list_del() of the newly inserted free buffer), restoring the original free block.
- The preallocated 'next' buffer is (re)allocated inside the retry loop in binder_alloc_new_buf(), so a freed pointer is never reused.
I'll send v3 with all three fixes.
Bo