completion.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * Complete implementation in Device Drivers
  3. */
  4. #include <rthw.h>
  5. #include <rtthread.h>
  6. #include <rtdevice.h>
  7. #define RT_COMPLETED 1
  8. #define RT_UNCOMPLETED 0
  9. void rt_completion_init(struct rt_completion* completion)
  10. {
  11. rt_base_t level;
  12. RT_ASSERT(completion != RT_NULL);
  13. level = rt_hw_interrupt_disable();
  14. completion->flag = RT_UNCOMPLETED;
  15. rt_list_init(&completion->suspended_list);
  16. rt_hw_interrupt_enable(level);
  17. }
  18. rt_err_t rt_completion_wait(struct rt_completion* completion, rt_int32_t timeout)
  19. {
  20. rt_err_t result;
  21. rt_base_t level;
  22. rt_thread_t thread;
  23. RT_ASSERT(completion != RT_NULL);
  24. result = RT_EOK;
  25. thread = rt_thread_self();
  26. level = rt_hw_interrupt_disable();
  27. if (completion->flag != RT_COMPLETED)
  28. {
  29. /* only one thread can suspend on complete */
  30. RT_ASSERT(rt_list_isempty(&(completion->suspended_list)));
  31. if (timeout == 0)
  32. {
  33. result = -RT_ETIMEOUT;
  34. goto __exit;
  35. }
  36. else
  37. {
  38. /* reset thread error number */
  39. thread->error = RT_EOK;
  40. /* suspend thread */
  41. rt_thread_suspend(thread);
  42. /* add to suspended list */
  43. rt_list_insert_before(&(completion->suspended_list), &(thread->tlist));
  44. /* current context checking */
  45. RT_DEBUG_NOT_IN_INTERRUPT;
  46. /* start timer */
  47. if (timeout > 0)
  48. {
  49. /* reset the timeout of thread timer and start it */
  50. rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &timeout);
  51. rt_timer_start(&(thread->thread_timer));
  52. }
  53. /* enable interrupt */
  54. rt_hw_interrupt_enable(level);
  55. /* do schedule */
  56. rt_schedule();
  57. /* thread is waked up */
  58. result = thread->error;
  59. level = rt_hw_interrupt_disable();
  60. /* clean completed flag */
  61. completion->flag = RT_UNCOMPLETED;
  62. }
  63. }
  64. __exit:
  65. rt_hw_interrupt_enable(level);
  66. return result;
  67. }
  68. void rt_completion_done(struct rt_completion* completion)
  69. {
  70. rt_base_t level;
  71. RT_ASSERT(completion != RT_NULL);
  72. level = rt_hw_interrupt_disable();
  73. completion->flag = RT_COMPLETED;
  74. if (!rt_list_isempty(&(completion->suspended_list)))
  75. {
  76. /* there is one thread in suspended list */
  77. struct rt_thread *thread;
  78. /* get thread entry */
  79. thread = rt_list_entry(completion->suspended_list.next, struct rt_thread, tlist);
  80. /* resume it */
  81. rt_thread_resume(thread);
  82. rt_hw_interrupt_enable(level);
  83. /* perform a schedule */
  84. rt_schedule();
  85. }
  86. else
  87. {
  88. rt_hw_interrupt_enable(level);
  89. }
  90. }