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