1 /*
2 * Copyright (c) 2018, The OpenThread Authors.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. Neither the name of the copyright holder nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /**
30 * @file
31 * This file implements OpenThread Time Synchronization Service.
32 */
33
34 #include "openthread-core-config.h"
35
36 #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
37
38 #include "time_sync_service.hpp"
39
40 #include <openthread/platform/alarm-micro.h>
41 #include <openthread/platform/alarm-milli.h>
42 #include <openthread/platform/time.h>
43
44 #include "common/instance.hpp"
45 #include "common/locator_getters.hpp"
46 #include "common/log.hpp"
47
48 #define ABS(value) (((value) >= 0) ? (value) : -(value))
49
50 namespace ot {
51
52 RegisterLogModule("TimeSync");
53
TimeSync(Instance & aInstance)54 TimeSync::TimeSync(Instance &aInstance)
55 : InstanceLocator(aInstance)
56 , mTimeSyncRequired(false)
57 , mTimeSyncSeq(OT_TIME_SYNC_INVALID_SEQ)
58 , mTimeSyncPeriod(OPENTHREAD_CONFIG_TIME_SYNC_PERIOD)
59 , mXtalThreshold(OPENTHREAD_CONFIG_TIME_SYNC_XTAL_THRESHOLD)
60 #if OPENTHREAD_FTD
61 , mLastTimeSyncSent(0)
62 #endif
63 , mLastTimeSyncReceived(0)
64 , mNetworkTimeOffset(0)
65 , mTimer(aInstance)
66 , mCurrentStatus(kUnsynchronized)
67 {
68 CheckAndHandleChanges(false);
69 }
70
GetTime(uint64_t & aNetworkTime) const71 TimeSync::Status TimeSync::GetTime(uint64_t &aNetworkTime) const
72 {
73 aNetworkTime = static_cast<uint64_t>(static_cast<int64_t>(otPlatTimeGet()) + mNetworkTimeOffset);
74
75 return mCurrentStatus;
76 }
77
HandleTimeSyncMessage(const Message & aMessage)78 void TimeSync::HandleTimeSyncMessage(const Message &aMessage)
79 {
80 const int64_t origNetworkTimeOffset = mNetworkTimeOffset;
81 int8_t timeSyncSeqDelta;
82
83 VerifyOrExit(aMessage.GetTimeSyncSeq() != OT_TIME_SYNC_INVALID_SEQ);
84
85 timeSyncSeqDelta = static_cast<int8_t>(aMessage.GetTimeSyncSeq() - mTimeSyncSeq);
86
87 if (mTimeSyncSeq != OT_TIME_SYNC_INVALID_SEQ && timeSyncSeqDelta < 0)
88 {
89 // An older time sync sequence was received. This indicates that there is a device that still needs to be
90 // synchronized with the current sequence, so forward it.
91 mTimeSyncRequired = true;
92
93 LogInfo("Older time sync seq received:%u. Forwarding current seq:%u", aMessage.GetTimeSyncSeq(), mTimeSyncSeq);
94 }
95 else if (Get<Mle::MleRouter>().IsLeader() && timeSyncSeqDelta > 0)
96 {
97 // Another device is forwarding a later time sync sequence, perhaps because it merged from a different
98 // partition. The leader is authoritative, so ensure all devices synchronize to the time being seeded by this
99 // leader instead.
100 mTimeSyncSeq = aMessage.GetTimeSyncSeq() + 1;
101 mTimeSyncRequired = true;
102
103 LogInfo("Newer time sync seq:%u received by leader. Setting current seq to:%u and forwarding",
104 aMessage.GetTimeSyncSeq(), mTimeSyncSeq);
105 }
106 else if (!Get<Mle::MleRouter>().IsLeader())
107 {
108 // For all devices aside from the leader, update network time in following three cases:
109 // 1. During first attach.
110 // 2. Already attached, and a newer time sync sequence was received.
111 // 3. During reattach or migration process.
112 if (mTimeSyncSeq == OT_TIME_SYNC_INVALID_SEQ || timeSyncSeqDelta > 0 || Get<Mle::MleRouter>().IsDetached())
113 {
114 // Update network time and forward it.
115 mLastTimeSyncReceived = TimerMilli::GetNow();
116 mTimeSyncSeq = aMessage.GetTimeSyncSeq();
117 mNetworkTimeOffset = aMessage.GetNetworkTimeOffset();
118 mTimeSyncRequired = true;
119
120 LogInfo("Newer time sync seq:%u received. Forwarding", mTimeSyncSeq);
121
122 // Only notify listeners of an update for network time offset jumps of more than
123 // OPENTHREAD_CONFIG_TIME_SYNC_JUMP_NOTIF_MIN_US but notify listeners regardless if the status changes.
124 CheckAndHandleChanges(ABS(mNetworkTimeOffset - origNetworkTimeOffset) >=
125 OPENTHREAD_CONFIG_TIME_SYNC_JUMP_NOTIF_MIN_US);
126 }
127 }
128
129 exit:
130 return;
131 }
132
IncrementTimeSyncSeq(void)133 void TimeSync::IncrementTimeSyncSeq(void)
134 {
135 if (++mTimeSyncSeq == OT_TIME_SYNC_INVALID_SEQ)
136 {
137 ++mTimeSyncSeq;
138 }
139 }
140
NotifyTimeSyncCallback(void)141 void TimeSync::NotifyTimeSyncCallback(void) { mTimeSyncCallback.InvokeIfSet(); }
142
143 #if OPENTHREAD_FTD
ProcessTimeSync(void)144 void TimeSync::ProcessTimeSync(void)
145 {
146 if (Get<Mle::MleRouter>().IsLeader() &&
147 (TimerMilli::GetNow() - mLastTimeSyncSent > Time::SecToMsec(mTimeSyncPeriod)))
148 {
149 IncrementTimeSyncSeq();
150 mTimeSyncRequired = true;
151
152 LogInfo("Leader seeding new time sync seq:%u", mTimeSyncSeq);
153 }
154
155 if (mTimeSyncRequired)
156 {
157 VerifyOrExit(Get<Mle::MleRouter>().SendTimeSync() == kErrorNone);
158
159 mLastTimeSyncSent = TimerMilli::GetNow();
160 mTimeSyncRequired = false;
161 }
162
163 exit:
164 return;
165 }
166 #endif // OPENTHREAD_FTD
167
HandleNotifierEvents(Events aEvents)168 void TimeSync::HandleNotifierEvents(Events aEvents)
169 {
170 bool stateChanged = false;
171
172 if (aEvents.Contains(kEventThreadRoleChanged))
173 {
174 stateChanged = true;
175 }
176
177 if (aEvents.Contains(kEventThreadPartitionIdChanged) && !Get<Mle::MleRouter>().IsLeader())
178 {
179 // Partition has changed. Accept any network time currently being seeded on the new partition
180 // and don't attempt to forward the currently held network time from the previous partition.
181 mTimeSyncSeq = OT_TIME_SYNC_INVALID_SEQ;
182 mTimeSyncRequired = false;
183
184 // Network time status will become kUnsychronized because no network time has yet been received
185 // on the new partition.
186 mLastTimeSyncReceived.SetValue(0);
187
188 stateChanged = true;
189
190 LogInfo("Resetting time sync seq, partition changed");
191 }
192
193 if (stateChanged)
194 {
195 CheckAndHandleChanges(false);
196 }
197 }
198
HandleTimeout(void)199 void TimeSync::HandleTimeout(void) { CheckAndHandleChanges(false); }
200
CheckAndHandleChanges(bool aTimeUpdated)201 void TimeSync::CheckAndHandleChanges(bool aTimeUpdated)
202 {
203 Status networkTimeStatus = kSynchronized;
204 const uint32_t resyncNeededThresholdMs = 2 * Time::SecToMsec(mTimeSyncPeriod);
205 const uint32_t timeSyncLastSyncMs = TimerMilli::GetNow() - mLastTimeSyncReceived;
206
207 mTimer.Stop();
208
209 switch (Get<Mle::MleRouter>().GetRole())
210 {
211 case Mle::kRoleDisabled:
212 case Mle::kRoleDetached:
213 networkTimeStatus = kUnsynchronized;
214 LogInfo("Time sync status UNSYNCHRONIZED as role:DISABLED/DETACHED");
215 break;
216
217 case Mle::kRoleChild:
218 case Mle::kRoleRouter:
219 if (mLastTimeSyncReceived.GetValue() == 0)
220 {
221 // Haven't yet received any time sync
222 networkTimeStatus = kUnsynchronized;
223 LogInfo("Time sync status UNSYNCHRONIZED as mLastTimeSyncReceived:0");
224 }
225 else if (timeSyncLastSyncMs > resyncNeededThresholdMs)
226 {
227 // The device hasn’t received time sync for more than two periods time.
228 networkTimeStatus = kResyncNeeded;
229 LogInfo("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%lu > resyncNeededThresholdMs:%lu",
230 ToUlong(timeSyncLastSyncMs), ToUlong(resyncNeededThresholdMs));
231 }
232 else
233 {
234 // Schedule a check 1 millisecond after two periods of time
235 OT_ASSERT(resyncNeededThresholdMs >= timeSyncLastSyncMs);
236 mTimer.Start(resyncNeededThresholdMs - timeSyncLastSyncMs + 1);
237 LogInfo("Time sync status SYNCHRONIZED");
238 }
239 break;
240
241 case Mle::kRoleLeader:
242 LogInfo("Time sync status SYNCHRONIZED as role:LEADER");
243 break;
244 }
245
246 if (networkTimeStatus != mCurrentStatus || aTimeUpdated)
247 {
248 mCurrentStatus = networkTimeStatus;
249
250 NotifyTimeSyncCallback();
251 }
252 }
253
254 } // namespace ot
255
256 #endif // OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
257