mutex.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef _LIBLOCKDEP_MUTEX_H
  3. #define _LIBLOCKDEP_MUTEX_H
  4. #include <pthread.h>
  5. #include "common.h"
  6. struct liblockdep_pthread_mutex {
  7. pthread_mutex_t mutex;
  8. struct lockdep_map dep_map;
  9. };
  10. typedef struct liblockdep_pthread_mutex liblockdep_pthread_mutex_t;
  11. #define LIBLOCKDEP_PTHREAD_MUTEX_INITIALIZER(mtx) \
  12. (const struct liblockdep_pthread_mutex) { \
  13. .mutex = PTHREAD_MUTEX_INITIALIZER, \
  14. .dep_map = STATIC_LOCKDEP_MAP_INIT(#mtx, &((&(mtx))->dep_map)), \
  15. }
  16. static inline int __mutex_init(liblockdep_pthread_mutex_t *lock,
  17. const char *name,
  18. struct lock_class_key *key,
  19. const pthread_mutexattr_t *__mutexattr)
  20. {
  21. lockdep_init_map(&lock->dep_map, name, key, 0);
  22. return pthread_mutex_init(&lock->mutex, __mutexattr);
  23. }
  24. #define liblockdep_pthread_mutex_init(mutex, mutexattr) \
  25. ({ \
  26. static struct lock_class_key __key; \
  27. \
  28. __mutex_init((mutex), #mutex, &__key, (mutexattr)); \
  29. })
  30. static inline int liblockdep_pthread_mutex_lock(liblockdep_pthread_mutex_t *lock)
  31. {
  32. lock_acquire(&lock->dep_map, 0, 0, 0, 1, NULL, (unsigned long)_RET_IP_);
  33. return pthread_mutex_lock(&lock->mutex);
  34. }
  35. static inline int liblockdep_pthread_mutex_unlock(liblockdep_pthread_mutex_t *lock)
  36. {
  37. lock_release(&lock->dep_map, 0, (unsigned long)_RET_IP_);
  38. return pthread_mutex_unlock(&lock->mutex);
  39. }
  40. static inline int liblockdep_pthread_mutex_trylock(liblockdep_pthread_mutex_t *lock)
  41. {
  42. lock_acquire(&lock->dep_map, 0, 1, 0, 1, NULL, (unsigned long)_RET_IP_);
  43. return pthread_mutex_trylock(&lock->mutex) == 0 ? 1 : 0;
  44. }
  45. static inline int liblockdep_pthread_mutex_destroy(liblockdep_pthread_mutex_t *lock)
  46. {
  47. return pthread_mutex_destroy(&lock->mutex);
  48. }
  49. #ifdef __USE_LIBLOCKDEP
  50. #define pthread_mutex_t liblockdep_pthread_mutex_t
  51. #define pthread_mutex_init liblockdep_pthread_mutex_init
  52. #define pthread_mutex_lock liblockdep_pthread_mutex_lock
  53. #define pthread_mutex_unlock liblockdep_pthread_mutex_unlock
  54. #define pthread_mutex_trylock liblockdep_pthread_mutex_trylock
  55. #define pthread_mutex_destroy liblockdep_pthread_mutex_destroy
  56. #endif
  57. #endif