alarm.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #include "u.h"
  2. #include "lib.h"
  3. #include "mem.h"
  4. #include "dat.h"
  5. #include "fns.h"
  6. #include "io.h"
  7. #define MAXALARM 10
  8. Alarm alarmtab[MAXALARM];
  9. /*
  10. * Insert new into list after where
  11. */
  12. void
  13. insert(List **head, List *where, List *new)
  14. {
  15. if(where == 0){
  16. new->next = *head;
  17. *head = new;
  18. }else{
  19. new->next = where->next;
  20. where->next = new;
  21. }
  22. }
  23. /*
  24. * Delete old from list. where->next is known to be old.
  25. */
  26. void
  27. delete(List **head, List *where, List *old)
  28. {
  29. if(where == 0){
  30. *head = old->next;
  31. return;
  32. }
  33. where->next = old->next;
  34. }
  35. Alarm*
  36. newalarm(void)
  37. {
  38. int i;
  39. Alarm *a;
  40. for(i=0,a=alarmtab; i < nelem(alarmtab); i++,a++)
  41. if(a->busy==0 && a->f==0){
  42. a->f = 0;
  43. a->arg = 0;
  44. a->busy = 1;
  45. return a;
  46. }
  47. panic("newalarm");
  48. return 0; /* not reached */
  49. }
  50. Alarm*
  51. alarm(int ms, void (*f)(Alarm*), void *arg)
  52. {
  53. Alarm *a, *w, *pw;
  54. ulong s;
  55. if(ms < 0)
  56. ms = 0;
  57. s = splhi();
  58. a = newalarm();
  59. a->dt = MS2TK(ms);
  60. a->f = f;
  61. a->arg = arg;
  62. pw = 0;
  63. for(w=m->alarm; w; pw=w, w=w->next){
  64. if(w->dt <= a->dt){
  65. a->dt -= w->dt;
  66. continue;
  67. }
  68. w->dt -= a->dt;
  69. break;
  70. }
  71. insert(&m->alarm, pw, a);
  72. splx(s);
  73. return a;
  74. }
  75. void
  76. cancel(Alarm *a)
  77. {
  78. a->f = 0;
  79. }
  80. void
  81. alarminit(void)
  82. {
  83. }
  84. #define NA 10 /* alarms per clock tick */
  85. void
  86. checkalarms(void)
  87. {
  88. int i, n, s;
  89. Alarm *a;
  90. void (*f)(Alarm*);
  91. Alarm *alist[NA];
  92. s = splhi();
  93. a = m->alarm;
  94. if(a){
  95. for(n=0; a && a->dt<=0 && n<NA; n++){
  96. alist[n] = a;
  97. delete(&m->alarm, 0, a);
  98. a = m->alarm;
  99. }
  100. if(a)
  101. a->dt--;
  102. for(i = 0; i < n; i++){
  103. f = alist[i]->f; /* avoid race with cancel */
  104. if(f)
  105. (*f)(alist[i]);
  106. alist[i]->busy = 0;
  107. }
  108. }
  109. splx(s);
  110. }