zephyr_clock.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (C) 2024 Grenoble INP - ESISAR. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "platform_api_extension.h"
  6. #include "platform_api_vmcore.h"
  7. #include "libc_errno.h"
  8. #include <zephyr/kernel.h>
  9. /* Notes:
  10. * We are using the same implementation for __WASI_CLOCK_REALTIME and
  11. * __WASI_CLOCK_MONOTONIC, because it is a practical solution when there
  12. * is no RTC or external time source available.
  13. * The implementation is based on the Zephyr `k_cycle_get_32()` function or
  14. * the 64bits variant if available.
  15. * We could have used `k_uptime_get()` instead, but it is not as precise,
  16. * it has a millisecond resolution or depend on CONFIG_SYS_CLOCK_TICKS_PER_SEC.
  17. * Feel free to change the implementation if you have a better solution.
  18. * May look at
  19. * https://github.com/zephyrproject-rtos/zephyr/blob/main/lib/posix/options/clock.c
  20. * for reference.
  21. */
  22. #define NANOSECONDS_PER_SECOND 1000000000ULL
  23. __wasi_errno_t
  24. os_clock_res_get(__wasi_clockid_t clock_id, __wasi_timestamp_t *resolution)
  25. {
  26. switch (clock_id) {
  27. case __WASI_CLOCK_PROCESS_CPUTIME_ID:
  28. case __WASI_CLOCK_THREAD_CPUTIME_ID:
  29. return __WASI_ENOTSUP;
  30. case __WASI_CLOCK_REALTIME:
  31. case __WASI_CLOCK_MONOTONIC:
  32. *resolution =
  33. NANOSECONDS_PER_SECOND / CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC;
  34. return __WASI_ESUCCESS;
  35. default:
  36. return __WASI_EINVAL;
  37. }
  38. }
  39. __wasi_errno_t
  40. os_clock_time_get(__wasi_clockid_t clock_id, __wasi_timestamp_t precision,
  41. __wasi_timestamp_t *time)
  42. {
  43. (void)precision;
  44. switch (clock_id) {
  45. case __WASI_CLOCK_PROCESS_CPUTIME_ID:
  46. case __WASI_CLOCK_THREAD_CPUTIME_ID:
  47. return __WASI_ENOTSUP;
  48. case __WASI_CLOCK_REALTIME:
  49. case __WASI_CLOCK_MONOTONIC:
  50. #ifdef CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER
  51. *time = k_cycle_get_64();
  52. #else
  53. *time = k_cycle_get_32();
  54. #endif
  55. return __WASI_ESUCCESS;
  56. default:
  57. return __WASI_EINVAL;
  58. }
  59. }