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 , mTimeSyncCallback(nullptr)
66 , mTimeSyncCallbackContext(nullptr)
67 , mTimer(aInstance, HandleTimeout)
68 , mCurrentStatus(OT_NETWORK_TIME_UNSYNCHRONIZED)
69 {
70 CheckAndHandleChanges(false);
71 }
72
GetTime(uint64_t & aNetworkTime) const73 otNetworkTimeStatus TimeSync::GetTime(uint64_t &aNetworkTime) const
74 {
75 aNetworkTime = static_cast<uint64_t>(static_cast<int64_t>(otPlatTimeGet()) + mNetworkTimeOffset);
76
77 return mCurrentStatus;
78 }
79
HandleTimeSyncMessage(const Message & aMessage)80 void TimeSync::HandleTimeSyncMessage(const Message &aMessage)
81 {
82 const int64_t origNetworkTimeOffset = mNetworkTimeOffset;
83 int8_t timeSyncSeqDelta;
84
85 VerifyOrExit(aMessage.GetTimeSyncSeq() != OT_TIME_SYNC_INVALID_SEQ);
86
87 timeSyncSeqDelta = static_cast<int8_t>(aMessage.GetTimeSyncSeq() - mTimeSyncSeq);
88
89 if (mTimeSyncSeq != OT_TIME_SYNC_INVALID_SEQ && timeSyncSeqDelta < 0)
90 {
91 // An older time sync sequence was received. This indicates that there is a device that still needs to be
92 // synchronized with the current sequence, so forward it.
93 mTimeSyncRequired = true;
94
95 LogInfo("Older time sync seq received:%u. Forwarding current seq:%u", aMessage.GetTimeSyncSeq(), mTimeSyncSeq);
96 }
97 else if (Get<Mle::MleRouter>().IsLeader() && timeSyncSeqDelta > 0)
98 {
99 // Another device is forwarding a later time sync sequence, perhaps because it merged from a different
100 // partition. The leader is authoritative, so ensure all devices synchronize to the time being seeded by this
101 // leader instead.
102 mTimeSyncSeq = aMessage.GetTimeSyncSeq() + 1;
103 mTimeSyncRequired = true;
104
105 LogInfo("Newer time sync seq:%u received by leader. Setting current seq to:%u and forwarding",
106 aMessage.GetTimeSyncSeq(), mTimeSyncSeq);
107 }
108 else if (!Get<Mle::MleRouter>().IsLeader())
109 {
110 // For all devices aside from the leader, update network time in following three cases:
111 // 1. During first attach.
112 // 2. Already attached, and a newer time sync sequence was received.
113 // 3. During reattach or migration process.
114 if (mTimeSyncSeq == OT_TIME_SYNC_INVALID_SEQ || timeSyncSeqDelta > 0 || Get<Mle::MleRouter>().IsDetached())
115 {
116 // Update network time and forward it.
117 mLastTimeSyncReceived = TimerMilli::GetNow();
118 mTimeSyncSeq = aMessage.GetTimeSyncSeq();
119 mNetworkTimeOffset = aMessage.GetNetworkTimeOffset();
120 mTimeSyncRequired = true;
121
122 LogInfo("Newer time sync seq:%u received. Forwarding", mTimeSyncSeq);
123
124 // Only notify listeners of an update for network time offset jumps of more than
125 // OPENTHREAD_CONFIG_TIME_SYNC_JUMP_NOTIF_MIN_US but notify listeners regardless if the status changes.
126 CheckAndHandleChanges(ABS(mNetworkTimeOffset - origNetworkTimeOffset) >=
127 OPENTHREAD_CONFIG_TIME_SYNC_JUMP_NOTIF_MIN_US);
128 }
129 }
130
131 exit:
132 return;
133 }
134
IncrementTimeSyncSeq(void)135 void TimeSync::IncrementTimeSyncSeq(void)
136 {
137 if (++mTimeSyncSeq == OT_TIME_SYNC_INVALID_SEQ)
138 {
139 ++mTimeSyncSeq;
140 }
141 }
142
NotifyTimeSyncCallback(void)143 void TimeSync::NotifyTimeSyncCallback(void)
144 {
145 if (mTimeSyncCallback != nullptr)
146 {
147 mTimeSyncCallback(mTimeSyncCallbackContext);
148 }
149 }
150
151 #if OPENTHREAD_FTD
ProcessTimeSync(void)152 void TimeSync::ProcessTimeSync(void)
153 {
154 if (Get<Mle::MleRouter>().IsLeader() &&
155 (TimerMilli::GetNow() - mLastTimeSyncSent > Time::SecToMsec(mTimeSyncPeriod)))
156 {
157 IncrementTimeSyncSeq();
158 mTimeSyncRequired = true;
159
160 LogInfo("Leader seeding new time sync seq:%u", mTimeSyncSeq);
161 }
162
163 if (mTimeSyncRequired)
164 {
165 VerifyOrExit(Get<Mle::MleRouter>().SendTimeSync() == kErrorNone);
166
167 mLastTimeSyncSent = TimerMilli::GetNow();
168 mTimeSyncRequired = false;
169 }
170
171 exit:
172 return;
173 }
174 #endif // OPENTHREAD_FTD
175
HandleNotifierEvents(Events aEvents)176 void TimeSync::HandleNotifierEvents(Events aEvents)
177 {
178 bool stateChanged = false;
179
180 if (aEvents.Contains(kEventThreadRoleChanged))
181 {
182 stateChanged = true;
183 }
184
185 if (aEvents.Contains(kEventThreadPartitionIdChanged) && !Get<Mle::MleRouter>().IsLeader())
186 {
187 // Partition has changed. Accept any network time currently being seeded on the new partition
188 // and don't attempt to forward the currently held network time from the previous partition.
189 mTimeSyncSeq = OT_TIME_SYNC_INVALID_SEQ;
190 mTimeSyncRequired = false;
191
192 // Network time status will become OT_NETWORK_TIME_UNSYNCHRONIZED because no network time has yet been received
193 // on the new partition.
194 mLastTimeSyncReceived.SetValue(0);
195
196 stateChanged = true;
197
198 LogInfo("Resetting time sync seq, partition changed");
199 }
200
201 if (stateChanged)
202 {
203 CheckAndHandleChanges(false);
204 }
205 }
206
HandleTimeout(void)207 void TimeSync::HandleTimeout(void)
208 {
209 CheckAndHandleChanges(false);
210 }
211
HandleTimeout(Timer & aTimer)212 void TimeSync::HandleTimeout(Timer &aTimer)
213 {
214 aTimer.Get<TimeSync>().HandleTimeout();
215 }
216
CheckAndHandleChanges(bool aTimeUpdated)217 void TimeSync::CheckAndHandleChanges(bool aTimeUpdated)
218 {
219 otNetworkTimeStatus networkTimeStatus = OT_NETWORK_TIME_SYNCHRONIZED;
220 const uint32_t resyncNeededThresholdMs = 2 * Time::SecToMsec(mTimeSyncPeriod);
221 const uint32_t timeSyncLastSyncMs = TimerMilli::GetNow() - mLastTimeSyncReceived;
222
223 mTimer.Stop();
224
225 switch (Get<Mle::MleRouter>().GetRole())
226 {
227 case Mle::kRoleDisabled:
228 case Mle::kRoleDetached:
229 networkTimeStatus = OT_NETWORK_TIME_UNSYNCHRONIZED;
230 LogInfo("Time sync status UNSYNCHRONIZED as role:DISABLED/DETACHED");
231 break;
232
233 case Mle::kRoleChild:
234 case Mle::kRoleRouter:
235 if (mLastTimeSyncReceived.GetValue() == 0)
236 {
237 // Haven't yet received any time sync
238 networkTimeStatus = OT_NETWORK_TIME_UNSYNCHRONIZED;
239 LogInfo("Time sync status UNSYNCHRONIZED as mLastTimeSyncReceived:0");
240 }
241 else if (timeSyncLastSyncMs > resyncNeededThresholdMs)
242 {
243 // The device hasn’t received time sync for more than two periods time.
244 networkTimeStatus = OT_NETWORK_TIME_RESYNC_NEEDED;
245 LogInfo("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%u > resyncNeededThresholdMs:%u",
246 timeSyncLastSyncMs, resyncNeededThresholdMs);
247 }
248 else
249 {
250 // Schedule a check 1 millisecond after two periods of time
251 OT_ASSERT(resyncNeededThresholdMs >= timeSyncLastSyncMs);
252 mTimer.Start(resyncNeededThresholdMs - timeSyncLastSyncMs + 1);
253 LogInfo("Time sync status SYNCHRONIZED");
254 }
255 break;
256
257 case Mle::kRoleLeader:
258 LogInfo("Time sync status SYNCHRONIZED as role:LEADER");
259 break;
260 }
261
262 if (networkTimeStatus != mCurrentStatus || aTimeUpdated)
263 {
264 mCurrentStatus = networkTimeStatus;
265
266 NotifyTimeSyncCallback();
267 }
268 }
269
270 } // namespace ot
271
272 #endif // OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
273