timer.c 2.6 KB

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