A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
wall-clock-synchronizer.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2008 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
8
9#include "log.h"
10
11#include <chrono>
12#include <condition_variable>
13#include <mutex>
14
15/**
16 * @file
17 * @ingroup realtime
18 * ns3::WallClockSynchronizer implementation.
19 */
20
21namespace ns3
22{
23
24NS_LOG_COMPONENT_DEFINE("WallClockSynchronizer");
25
27
30{
31 static TypeId tid =
32 TypeId("ns3::WallClockSynchronizer").SetParent<Synchronizer>().SetGroupName("Core");
33 return tid;
34}
35
37{
38 NS_LOG_FUNCTION(this);
39 //
40 // In Linux, the basic timekeeping unit is derived from a variable called HZ
41 // HZ is the frequency in hertz of the system timer. The system timer fires
42 // every 1/HZ seconds and a counter, called the jiffies counter is incremented
43 // at each tick. The time between ticks is called a jiffy (American slang for
44 // a short period of time). The ticking of the jiffies counter is how the
45 // the kernel tells time.
46 //
47 // Now, the shortest time the kernel can sleep is one jiffy since a timer
48 // has to be set to expire and trigger the process to be made ready. The
49 // Posix clock CLOCK_REALTIME is defined as a 1/HZ clock, so by doing a
50 // clock_getres () on the realtime clock we can infer the scheduler quantum
51 // and the minimimum sleep time for the system. This is most certainly NOT
52 // going to be one nanosecond even though clock_nanosleep () pretends it is.
53 //
54 // The reason this number is important is that we are going to schedule lots
55 // of waits for less time than a jiffy. The clock_nanosleep function is
56 // going to guarantee that it will sleep for AT LEAST the time specified.
57 // The least time that it will sleep is a jiffy.
58 //
59 // In order to deal with this, we are going to do a spin-wait if the simulator
60 // requires a delay less than a jiffy. This is on the order of one millisecond
61 // (999848 ns) on the ns-regression machine.
62 //
63 // If the underlying OS does not support posix clocks, we'll just assume a
64 // one millisecond quantum and deal with this as best we can
65
66 m_jiffy = std::chrono::system_clock::period::num * std::nano::den /
67 std::chrono::system_clock::period::den;
68 NS_LOG_INFO("Jiffy is " << m_jiffy << " ns");
69}
70
75
76bool
78{
79 NS_LOG_FUNCTION(this);
80 return true;
81}
82
83uint64_t
89
90void
92{
93 NS_LOG_FUNCTION(this << ns);
94 //
95 // In order to make sure we're really locking the simulation time to some
96 // wall-clock time, we need to be able to compare that simulation time to
97 // that wall-clock time. The wall clock will have been running for some
98 // long time and will probably have a huge count of nanoseconds in it. We
99 // save the real time away so we can subtract it from "now" later and get
100 // a count of nanoseconds in real time since the simulation started.
101 //
103 NS_LOG_INFO("origin = " << m_realtimeOriginNano);
104}
105
106int64_t
108{
109 NS_LOG_FUNCTION(this << ns);
110 //
111 // In order to make sure we're really locking the simulation time to some
112 // wall-clock time, we need to be able to compare that simulation time to
113 // that wall-clock time. In DoSetOrigin we saved the real time at the start
114 // of the simulation away. This is the place where we subtract it from "now"
115 // to a count of nanoseconds in real time since the simulation started. We
116 // then subtract the current real time in normalized nanoseconds we just got
117 // from the normalized simulation time in nanoseconds that is passed in as
118 // the parameter ns. We return an integer difference, but in reality all of
119 // the mechanisms that cause wall-clock to simulator time drift cause events
120 // to be late. That means that the wall-clock will be higher than the
121 // simulation time and drift will be positive. I would be astonished to
122 // see a negative drift, but the possibility is admitted for other
123 // implementations; and we'll use the ability to report an early result in
124 // DoSynchronize below.
125 //
126 uint64_t nsNow = GetNormalizedRealtime();
127
128 if (nsNow > ns)
129 {
130 //
131 // Real time (nsNow) is larger/later than the simulator time (ns). We are
132 // behind real time and the difference (drift) is positive.
133 //
134 return (int64_t)(nsNow - ns);
135 }
136 else
137 {
138 //
139 // Real time (nsNow) is smaller/earlier than the simulator time (ns). We are
140 // ahead of real time and the difference (drift) is negative.
141 //
142 return -(int64_t)(ns - nsNow);
143 }
144}
145
146bool
147WallClockSynchronizer::DoSynchronize(uint64_t nsCurrent, uint64_t nsDelay)
148{
149 NS_LOG_FUNCTION(this << nsCurrent << nsDelay);
150 //
151 // This is the belly of the beast. We have received two parameters from the
152 // simulator proper -- a current simulation time (nsCurrent) and a simulation
153 // time to delay which identifies the time the next event is supposed to fire.
154 //
155 // The first thing we need to do is to (try and) correct for any realtime
156 // drift that has happened in the system. In this implementation, we realize
157 // that all mechanisms for drift will cause the drift to be such that the
158 // realtime is greater than the simulation time. This typically happens when
159 // our process is put to sleep for a given time, but actually sleeps for
160 // longer. So, what we want to do is to "catch up" to realtime and delay for
161 // less time than we are actually asked to delay. DriftCorrect will return a
162 // number from 0 to nsDelay corresponding to the amount of catching-up we
163 // need to do. If we are more than nsDelay behind, we do not wait at all.
164 //
165 // Note that it will be impossible to catch up if the amount of drift is
166 // cumulatively greater than the amount of delay between events. The method
167 // GetDrift () is available to clients of the syncrhonizer to keep track of
168 // the cumulative drift. The client can assert if the drift gets out of
169 // hand, print warning messages, or just ignore the situation and hope it will
170 // go away.
171 //
172 uint64_t ns = DriftCorrect(nsCurrent, nsDelay);
173 NS_LOG_INFO("Synchronize ns = " << ns);
174 //
175 // Once we've decided on how long we need to delay, we need to split this
176 // time into sleep waits and busy waits. The reason for this is described
177 // in the comments for the constructor where jiffies and jiffy resolution is
178 // explained.
179 //
180 // Here, I'll just say that we need that the jiffy is the minimum resolution
181 // of the system clock. It can only sleep in blocks of time equal to a jiffy.
182 // If we want to be more accurate than a jiffy (we do) then we need to sleep
183 // for some number of jiffies and then busy wait for any leftover time.
184 //
185 uint64_t numberJiffies = ns / m_jiffy;
186 NS_LOG_INFO("Synchronize numberJiffies = " << numberJiffies);
187 //
188 // This is where the real world interjects its very ugly head. The code
189 // immediately below reflects the fact that a sleep is actually quite probably
190 // going to end up sleeping for some number of jiffies longer than you wanted.
191 // This is because your system is going to be off doing other unimportant
192 // stuff during that extra time like running file systems and networks. What
193 // we want to do is to ask the system to sleep enough less than the requested
194 // delay so that it comes back early most of the time (coming back early is
195 // fine, coming back late is bad). If we can convince the system to come back
196 // early (most of the time), then we can busy-wait until the requested
197 // completion time actually comes around (most of the time).
198 //
199 // The tradeoff here is, of course, that the less time we spend sleeping, the
200 // more accurately we will sync up; but the more CPU time we will spend busy
201 // waiting (doing nothing).
202 //
203 // I'm not really sure about this number -- a boss of mine once said, "pick
204 // a number and it'll be wrong." But this works for now.
205 //
206 // \todo Hardcoded tunable parameter below.
207 //
208 if (numberJiffies > 3)
209 {
210 NS_LOG_INFO("SleepWait for " << numberJiffies * m_jiffy << " ns");
211 NS_LOG_INFO("SleepWait until " << nsCurrent + numberJiffies * m_jiffy << " ns");
212 //
213 // SleepWait is interruptible. If it returns true it meant that the sleep
214 // went until the end. If it returns false, it means that the sleep was
215 // interrupted by a Signal. In this case, we need to return and let the
216 // simulator re-evaluate what to do.
217 //
218 if (!SleepWait((numberJiffies - 3) * m_jiffy))
219 {
220 NS_LOG_INFO("SleepWait interrupted");
221 return false;
222 }
223 }
224 NS_LOG_INFO("Done with SleepWait");
225 //
226 // We asked the system to sleep for some number of jiffies, but that doesn't
227 // mean we actually did. Let's re-evaluate what we need to do here. Maybe
228 // we're already late. Probably the "real" delay time left has little to do
229 // with what we would calculate it to be naively.
230 //
231 // We are now at some Realtime. The important question now is not, "what
232 // would we calculate in a mathematicians paradise," it is, "how many
233 // nanoseconds do we need to busy-wait until we get to the Realtime that
234 // corresponds to nsCurrent + nsDelay (in simulation time). We have a handy
235 // function to do just that -- we ask for the time the realtime clock has
236 // drifted away from the simulation clock. That's our answer. If the drift
237 // is negative, we're early and we need to busy wait for that number of
238 // nanoseconds. The place were we want to be is described by the parameters
239 // we were passed by the simulator.
240 //
241 int64_t nsDrift = DoGetDrift(nsCurrent + nsDelay);
242 //
243 // If the drift is positive, we are already late and we need to just bail out
244 // of here as fast as we can. Return true to indicate that the requested time
245 // has, in fact, passed.
246 //
247 if (nsDrift >= 0)
248 {
249 NS_LOG_INFO("Back from SleepWait: IML8 " << nsDrift);
250 return true;
251 }
252 //
253 // There are some number of nanoseconds left over and we need to wait until
254 // the time defined by nsDrift. We'll do a SpinWait since the usual case
255 // will be that we are doing this Spinwait after we've gotten a rough delay
256 // using the SleepWait above. If SpinWait completes to the end, it will
257 // return true; if it is interrupted by a signal it will return false.
258 //
259 NS_LOG_INFO("SpinWait until " << nsCurrent + nsDelay);
260 return SpinWait(nsCurrent + nsDelay);
261}
262
263void
265{
266 NS_LOG_FUNCTION(this);
267
268 std::unique_lock<std::mutex> lock(m_mutex);
269 m_condition = true;
270
271 // Manual unlocking is done before notifying, to avoid waking up
272 // the waiting thread only to block again (see notify_one for details).
273 // Reference: https://en.cppreference.com/w/cpp/thread/condition_variable
274 lock.unlock();
275 m_conditionVariable.notify_one();
276}
277
278void
280{
281 NS_LOG_FUNCTION(this << cond);
282 m_condition = cond;
283}
284
285void
291
292uint64_t
298
299bool
301{
302 NS_LOG_FUNCTION(this << ns);
303 // We just sit here and spin, wasting CPU cycles until we get to the right
304 // time or are told to leave.
305 for (;;)
306 {
307 if (GetNormalizedRealtime() >= ns)
308 {
309 return true;
310 }
311 if (m_condition)
312 {
313 return false;
314 }
315 }
316 // Quiet compiler
317 return true;
318}
319
320bool
322{
323 NS_LOG_FUNCTION(this << ns);
324
325 std::unique_lock<std::mutex> lock(m_mutex);
326 bool finishedWaiting =
327 m_conditionVariable.wait_for(lock,
328 std::chrono::nanoseconds(ns), // Timeout
329 [this]() { return m_condition; }); // Wait condition
330
331 return finishedWaiting;
332}
333
334uint64_t
335WallClockSynchronizer::DriftCorrect(uint64_t nsNow, uint64_t nsDelay)
336{
337 NS_LOG_FUNCTION(this << nsNow << nsDelay);
338 int64_t drift = DoGetDrift(nsNow);
339 //
340 // If we're running late, drift will be positive and we need to correct by
341 // delaying for less time. If we're early for some bizarre reason, we don't
342 // do anything since we'll almost instantly self-correct.
343 //
344 if (drift < 0)
345 {
346 return nsDelay;
347 }
348 //
349 // If we've drifted out of sync by less than the requested delay, then just
350 // subtract the drift from the delay and fix up the drift in one go. If we
351 // have more drift than delay, then we just play catch up as fast as possible
352 // by not delaying at all.
353 //
354 auto correction = (uint64_t)drift;
355 if (correction <= nsDelay)
356 {
357 return nsDelay - correction;
358 }
359 else
360 {
361 return 0;
362 }
363}
364
365uint64_t
367{
368 NS_LOG_FUNCTION(this);
369 auto now = std::chrono::system_clock::now().time_since_epoch();
370 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
371}
372
373uint64_t
379
380} // namespace ns3
uint64_t m_realtimeOriginNano
The real time, in ns, when SetOrigin was called.
Synchronizer()
Constructor.
a unique identifier for an interface.
Definition type-id.h:49
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:999
Class used for synchronizing the simulation events to a real-time "wall clock" using Posix clock func...
uint64_t GetNormalizedRealtime()
Get the current normalized real time, in ns.
int64_t DoGetDrift(uint64_t ns) override
Get the drift between the real time clock used to synchronize the simulation and the current simulati...
bool SleepWait(uint64_t ns)
Put our process to sleep for some number of nanoseconds.
void DoEventStart() override
Record the normalized real time at which the current event is starting execution.
bool DoSynchronize(uint64_t nsCurrent, uint64_t nsDelay) override
Wait until the real time is in sync with the specified simulation time.
void DoSetOrigin(uint64_t ns) override
Establish a correspondence between a simulation time and a wall-clock (real) time.
uint64_t m_jiffy
Size of the system clock tick, as reported by clock_getres, in ns.
void DoSignal() override
Tell a possible simulator thread waiting in the DoSynchronize method that an event has happened which...
uint64_t DoGetCurrentRealtime() override
Retrieve the value of the origin of the underlying normalized wall clock time in Time resolution unit...
static TypeId GetTypeId()
Get the registered TypeId for this class.
bool m_condition
The condition state.
void DoSetCondition(bool cond) override
Set the condition variable to tell a possible simulator thread waiting in the Synchronize method that...
uint64_t m_nsEventStart
Time recorded by DoEventStart.
bool SpinWait(uint64_t ns)
Do a busy-wait until the normalized realtime equals the argument or the condition variable becomes tr...
std::condition_variable m_conditionVariable
Condition variable for thread synchronizer.
uint64_t GetRealtime()
Get the current absolute real time (in ns since the epoch).
~WallClockSynchronizer() override
Destructor.
bool DoRealtime() override
Return true if this synchronizer is actually synchronizing to a realtime clock.
uint64_t DoEventEnd() override
Return the amount of real time elapsed since the last call to EventStart.
uint64_t DriftCorrect(uint64_t nsNow, uint64_t nsDelay)
Compute a correction to the nominal delay to account for realtime drift since the last DoSynchronize.
std::mutex m_mutex
Mutex controlling access to the condition variable.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:194
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:267
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Debug message logging.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
ns3::WallClockSynchronizer declaration.