timer.c 2.4 KB

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