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