condition.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright (c) 2013-2018 Richard Braun.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. *
  18. * Locking order : mutex -> sleep queue
  19. */
  20. #include <assert.h>
  21. #include <stdbool.h>
  22. #include <stddef.h>
  23. #include <stdint.h>
  24. #include <kern/condition.h>
  25. #include <kern/condition_types.h>
  26. #include <kern/mutex.h>
  27. #include <kern/sleepq.h>
  28. static int
  29. condition_wait_common(struct condition *condition, struct mutex *mutex,
  30. bool timed, uint64_t ticks)
  31. {
  32. struct sleepq *sleepq;
  33. int error;
  34. assert(mutex_locked(mutex));
  35. sleepq = sleepq_lend(condition, true);
  36. mutex_unlock(mutex);
  37. if (timed) {
  38. error = sleepq_timedwait(sleepq, "cond", ticks);
  39. } else {
  40. sleepq_wait(sleepq, "cond");
  41. error = 0;
  42. }
  43. sleepq_return(sleepq);
  44. mutex_lock(mutex);
  45. return error;
  46. }
  47. void
  48. condition_wait(struct condition *condition, struct mutex *mutex)
  49. {
  50. int error;
  51. error = condition_wait_common(condition, mutex, false, 0);
  52. assert(!error);
  53. }
  54. int
  55. condition_timedwait(struct condition *condition,
  56. struct mutex *mutex, uint64_t ticks)
  57. {
  58. return condition_wait_common(condition, mutex, true, ticks);
  59. }
  60. void
  61. condition_signal(struct condition *condition)
  62. {
  63. struct sleepq *sleepq;
  64. sleepq = sleepq_acquire(condition, true);
  65. if (sleepq == NULL) {
  66. return;
  67. }
  68. sleepq_signal(sleepq);
  69. sleepq_release(sleepq);
  70. }
  71. void
  72. condition_broadcast(struct condition *condition)
  73. {
  74. struct sleepq *sleepq;
  75. sleepq = sleepq_acquire(condition, true);
  76. if (sleepq == NULL) {
  77. return;
  78. }
  79. sleepq_broadcast(sleepq);
  80. sleepq_release(sleepq);
  81. }