time.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (C) 2000 - 2007 Jeff Dike (jdike{addtoit,linux.intel}.com)
  3. * Licensed under the GPL
  4. */
  5. #include <stddef.h>
  6. #include <errno.h>
  7. #include <signal.h>
  8. #include <time.h>
  9. #include <sys/time.h>
  10. #include "kern_constants.h"
  11. #include "os.h"
  12. #include "user.h"
  13. int set_interval(void)
  14. {
  15. int usec = UM_USEC_PER_SEC / UM_HZ;
  16. struct itimerval interval = ((struct itimerval) { { 0, usec },
  17. { 0, usec } });
  18. if (setitimer(ITIMER_VIRTUAL, &interval, NULL) == -1)
  19. return -errno;
  20. return 0;
  21. }
  22. int timer_one_shot(int ticks)
  23. {
  24. unsigned long usec = ticks * UM_USEC_PER_SEC / UM_HZ;
  25. unsigned long sec = usec / UM_USEC_PER_SEC;
  26. struct itimerval interval;
  27. usec %= UM_USEC_PER_SEC;
  28. interval = ((struct itimerval) { { 0, 0 }, { sec, usec } });
  29. if (setitimer(ITIMER_VIRTUAL, &interval, NULL) == -1)
  30. return -errno;
  31. return 0;
  32. }
  33. /**
  34. * timeval_to_ns - Convert timeval to nanoseconds
  35. * @ts: pointer to the timeval variable to be converted
  36. *
  37. * Returns the scalar nanosecond representation of the timeval
  38. * parameter.
  39. *
  40. * Ripped from linux/time.h because it's a kernel header, and thus
  41. * unusable from here.
  42. */
  43. static inline long long timeval_to_ns(const struct timeval *tv)
  44. {
  45. return ((long long) tv->tv_sec * UM_NSEC_PER_SEC) +
  46. tv->tv_usec * UM_NSEC_PER_USEC;
  47. }
  48. long long disable_timer(void)
  49. {
  50. struct itimerval time = ((struct itimerval) { { 0, 0 }, { 0, 0 } });
  51. if(setitimer(ITIMER_VIRTUAL, &time, &time) < 0)
  52. printk(UM_KERN_ERR "disable_timer - setitimer failed, "
  53. "errno = %d\n", errno);
  54. return timeval_to_ns(&time.it_value);
  55. }
  56. long long os_nsecs(void)
  57. {
  58. struct timeval tv;
  59. gettimeofday(&tv, NULL);
  60. return timeval_to_ns(&tv);
  61. }
  62. extern void alarm_handler(int sig, struct sigcontext *sc);
  63. void idle_sleep(unsigned long long nsecs)
  64. {
  65. struct timespec ts = { .tv_sec = nsecs / UM_NSEC_PER_SEC,
  66. .tv_nsec = nsecs % UM_NSEC_PER_SEC };
  67. if (nanosleep(&ts, &ts) == 0)
  68. alarm_handler(SIGVTALRM, NULL);
  69. }