162306a36Sopenharmony_ci/* SPDX-License-Identifier: GPL-2.0 */ 262306a36Sopenharmony_ci#ifndef PERF_SHARDED_MUTEX_H 362306a36Sopenharmony_ci#define PERF_SHARDED_MUTEX_H 462306a36Sopenharmony_ci 562306a36Sopenharmony_ci#include "mutex.h" 662306a36Sopenharmony_ci#include "hashmap.h" 762306a36Sopenharmony_ci 862306a36Sopenharmony_ci/* 962306a36Sopenharmony_ci * In a situation where a lock is needed per object, having a mutex can be 1062306a36Sopenharmony_ci * relatively memory expensive (40 bytes on x86-64). If the object can be 1162306a36Sopenharmony_ci * constantly hashed, a sharded mutex is an alternative global pool of mutexes 1262306a36Sopenharmony_ci * where the mutex is looked up from a hash value. This can lead to collisions 1362306a36Sopenharmony_ci * if the number of shards isn't large enough. 1462306a36Sopenharmony_ci */ 1562306a36Sopenharmony_cistruct sharded_mutex { 1662306a36Sopenharmony_ci /* mutexes array is 1<<cap_bits in size. */ 1762306a36Sopenharmony_ci unsigned int cap_bits; 1862306a36Sopenharmony_ci struct mutex mutexes[]; 1962306a36Sopenharmony_ci}; 2062306a36Sopenharmony_ci 2162306a36Sopenharmony_cistruct sharded_mutex *sharded_mutex__new(size_t num_shards); 2262306a36Sopenharmony_civoid sharded_mutex__delete(struct sharded_mutex *sm); 2362306a36Sopenharmony_ci 2462306a36Sopenharmony_cistatic inline struct mutex *sharded_mutex__get_mutex(struct sharded_mutex *sm, size_t hash) 2562306a36Sopenharmony_ci{ 2662306a36Sopenharmony_ci return &sm->mutexes[hash_bits(hash, sm->cap_bits)]; 2762306a36Sopenharmony_ci} 2862306a36Sopenharmony_ci 2962306a36Sopenharmony_ci#endif /* PERF_SHARDED_MUTEX_H */ 30