systohc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * This program is free software; you can redistribute it and/or modify it
  3. * under the terms of the GNU General Public License version 2 as published by
  4. * the Free Software Foundation.
  5. *
  6. */
  7. #include <linux/rtc.h>
  8. #include <linux/time.h>
  9. /**
  10. * rtc_set_ntp_time - Save NTP synchronized time to the RTC
  11. * @now: Current time of day
  12. * @target_nsec: pointer for desired now->tv_nsec value
  13. *
  14. * Replacement for the NTP platform function update_persistent_clock64
  15. * that stores time for later retrieval by rtc_hctosys.
  16. *
  17. * Returns 0 on successful RTC update, -ENODEV if a RTC update is not
  18. * possible at all, and various other -errno for specific temporary failure
  19. * cases.
  20. *
  21. * -EPROTO is returned if now.tv_nsec is not close enough to *target_nsec.
  22. *
  23. * If temporary failure is indicated the caller should try again 'soon'
  24. */
  25. int rtc_set_ntp_time(struct timespec64 now, unsigned long *target_nsec)
  26. {
  27. struct rtc_device *rtc;
  28. struct rtc_time tm;
  29. struct timespec64 to_set;
  30. int err = -ENODEV;
  31. bool ok;
  32. rtc = rtc_class_open(CONFIG_RTC_SYSTOHC_DEVICE);
  33. if (!rtc)
  34. goto out_err;
  35. if (!rtc->ops || (!rtc->ops->set_time && !rtc->ops->set_mmss64 &&
  36. !rtc->ops->set_mmss))
  37. goto out_close;
  38. /* Compute the value of tv_nsec we require the caller to supply in
  39. * now.tv_nsec. This is the value such that (now +
  40. * set_offset_nsec).tv_nsec == 0.
  41. */
  42. set_normalized_timespec64(&to_set, 0, -rtc->set_offset_nsec);
  43. *target_nsec = to_set.tv_nsec;
  44. /* The ntp code must call this with the correct value in tv_nsec, if
  45. * it does not we update target_nsec and return EPROTO to make the ntp
  46. * code try again later.
  47. */
  48. ok = rtc_tv_nsec_ok(rtc->set_offset_nsec, &to_set, &now);
  49. if (!ok) {
  50. err = -EPROTO;
  51. goto out_close;
  52. }
  53. rtc_time64_to_tm(to_set.tv_sec, &tm);
  54. /* rtc_hctosys exclusively uses UTC, so we call set_time here, not
  55. * set_mmss.
  56. */
  57. err = rtc_set_time(rtc, &tm);
  58. out_close:
  59. rtc_class_close(rtc);
  60. out_err:
  61. return err;
  62. }