kmutex.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Copyright (C) 2017 Free Software Foundation, Inc.
  2. Contributed by Agustina Arzille <avarzille@riseup.net>, 2017.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either
  6. version 2 of the license, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public
  12. License along with this program; if not, see
  13. <http://www.gnu.org/licenses/>.
  14. */
  15. #include <kern/kmutex.h>
  16. #include <kern/atomic.h>
  17. #include <kern/sched_prim.h>
  18. #include <kern/thread.h>
  19. void kmutex_init (struct kmutex *mtxp)
  20. {
  21. mtxp->state = KMUTEX_AVAIL;
  22. simple_lock_init (&mtxp->lock);
  23. }
  24. kern_return_t kmutex_lock (struct kmutex *mtxp, boolean_t interruptible)
  25. {
  26. check_simple_locks ();
  27. if (atomic_cas_acq (&mtxp->state, KMUTEX_AVAIL, KMUTEX_LOCKED))
  28. /* Unowned mutex - We're done. */
  29. return (KERN_SUCCESS);
  30. /* The mutex is locked. We may have to sleep. */
  31. simple_lock (&mtxp->lock);
  32. if (atomic_swap_acq (&mtxp->state, KMUTEX_CONTENDED) == KMUTEX_AVAIL)
  33. {
  34. /* The mutex was released in-between. */
  35. simple_unlock (&mtxp->lock);
  36. return (KERN_SUCCESS);
  37. }
  38. /* Sleep and check the result value of the waiting, in order to
  39. * inform our caller if we were interrupted or not. Note that
  40. * we don't need to set again the mutex state. The owner will
  41. * handle that in every case. */
  42. thread_sleep ((event_t)mtxp, (simple_lock_t)&mtxp->lock, interruptible);
  43. return (current_thread()->wait_result == THREAD_AWAKENED ?
  44. KERN_SUCCESS : KERN_INTERRUPTED);
  45. }
  46. kern_return_t kmutex_trylock (struct kmutex *mtxp)
  47. {
  48. return (atomic_cas_acq (&mtxp->state, KMUTEX_AVAIL, KMUTEX_LOCKED) ?
  49. KERN_SUCCESS : KERN_FAILURE);
  50. }
  51. void kmutex_unlock (struct kmutex *mtxp)
  52. {
  53. if (atomic_cas_rel (&mtxp->state, KMUTEX_LOCKED, KMUTEX_AVAIL))
  54. /* No waiters - We're done. */
  55. return;
  56. simple_lock (&mtxp->lock);
  57. if (!thread_wakeup_one ((event_t)mtxp))
  58. /* Any threads that were waiting on this mutex were
  59. * interrupted and left - Reset the mutex state. */
  60. mtxp->state = KMUTEX_AVAIL;
  61. simple_unlock (&mtxp->lock);
  62. }