timer.c 2.3 KB

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