timer.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "timer.h"
  2. #include <common/kprint.h>
  3. #include <exception/softirq.h>
  4. #include <mm/slab.h>
  5. void test_timer()
  6. {
  7. printk_color(ORANGE, BLACK, "(test_timer)");
  8. }
  9. void timer_init()
  10. {
  11. timer_jiffies = 0;
  12. timer_func_init(&timer_func_head, NULL, NULL, -1UL);
  13. register_softirq(0, &do_timer_softirq, NULL);
  14. struct timer_func_list_t *tmp = (struct timer_func_list_t *)kmalloc(sizeof(struct timer_func_list_t), 0);
  15. timer_func_init(tmp, &test_timer, NULL, 5);
  16. timer_func_add(tmp);
  17. kdebug("timer func initialized.");
  18. }
  19. void do_timer_softirq(void *data)
  20. {
  21. struct timer_func_list_t *tmp = container_of(list_next(&timer_func_head.list), struct timer_func_list_t, list);
  22. while ((!list_empty(&timer_func_head.list)) && (tmp->expire_jiffies <= timer_jiffies))
  23. {
  24. timer_func_del(tmp);
  25. tmp->func(tmp->data);
  26. kfree(tmp);
  27. tmp = container_of(list_next(&timer_func_head.list), struct timer_func_list_t, list);
  28. }
  29. printk_color(ORANGE, BLACK, "(HPET%ld)", timer_jiffies);
  30. }
  31. /**
  32. * @brief 初始化定时功能
  33. *
  34. * @param timer_func 队列结构体
  35. * @param func 定时功能处理函数
  36. * @param expire_jiffies 定时时长
  37. */
  38. void timer_func_init(struct timer_func_list_t *timer_func, void (*func)(void *data), void *data, uint64_t expire_jiffies)
  39. {
  40. list_init(&timer_func->list);
  41. timer_func->func = func;
  42. timer_func->data = data,
  43. timer_func->expire_jiffies = timer_jiffies + expire_jiffies;
  44. }
  45. /**
  46. * @brief 将定时功能添加到列表中
  47. *
  48. * @param timer_func 待添加的定时功能
  49. */
  50. void timer_func_add(struct timer_func_list_t *timer_func)
  51. {
  52. struct timer_func_list_t *tmp = container_of(list_next(&timer_func_head.list), struct timer_func_list_t, list);
  53. if (list_empty(&timer_func_head.list) == false)
  54. while (tmp->expire_jiffies < timer_func->expire_jiffies)
  55. tmp = container_of(list_next(&tmp->list), struct timer_func_list_t, list);
  56. list_add(&tmp->list, &(timer_func->list));
  57. }
  58. /**
  59. * @brief 将定时功能从列表中删除
  60. *
  61. * @param timer_func
  62. */
  63. void timer_func_del(struct timer_func_list_t *timer_func)
  64. {
  65. list_del(&timer_func->list);
  66. }