A Discrete-Event Network Simulator
API
wall-clock-synchronizer.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2008 University of Washington
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation;
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */
18 
19 
20 #include <ctime> // clock_t
21 #include <sys/time.h> // gettimeofday
22  // clock_getres: glibc < 2.17, link with librt
23 
24 #include "log.h"
25 #include "system-condition.h"
26 
28 
35 namespace ns3 {
36 
37 NS_LOG_COMPONENT_DEFINE ("WallClockSynchronizer");
38 
39 NS_OBJECT_ENSURE_REGISTERED (WallClockSynchronizer);
40 
41 TypeId
43 {
44  static TypeId tid = TypeId ("ns3::WallClockSynchronizer")
46  ;
47  return tid;
48 }
49 
51 {
52  NS_LOG_FUNCTION (this);
53 //
54 // In Linux, the basic timekeeping unit is derived from a variable called HZ
55 // HZ is the frequency in hertz of the system timer. The system timer fires
56 // every 1/HZ seconds and a counter, called the jiffies counter is incremented
57 // at each tick. The time between ticks is called a jiffy (American slang for
58 // a short period of time). The ticking of the jiffies counter is how the
59 // the kernel tells time.
60 //
61 // Now, the shortest time the kernel can sleep is one jiffy since a timer
62 // has to be set to expire and trigger the process to be made ready. The
63 // Posix clock CLOCK_REALTIME is defined as a 1/HZ clock, so by doing a
64 // clock_getres () on the realtime clock we can infer the scheduler quantum
65 // and the minimimum sleep time for the system. This is most certainly NOT
66 // going to be one nanosecond even though clock_nanosleep () pretends it is.
67 //
68 // The reason this number is important is that we are going to schedule lots
69 // of waits for less time than a jiffy. The clock_nanosleep function is
70 // going to guarantee that it will sleep for AT LEAST the time specified.
71 // The least time that it will sleep is a jiffy.
72 //
73 // In order to deal with this, we are going to do a spin-wait if the simulator
74 // requires a delay less than a jiffy. This is on the order of one millisecond
75 // (999848 ns) on the ns-regression machine.
76 //
77 // If the underlying OS does not support posix clocks, we'll just assume a
78 // one millisecond quantum and deal with this as best we can
79 
80 #ifdef CLOCK_REALTIME
81  struct timespec ts;
82  clock_getres (CLOCK_REALTIME, &ts);
83  m_jiffy = ts.tv_sec * NS_PER_SEC + ts.tv_nsec;
84  NS_LOG_INFO ("Jiffy is " << m_jiffy << " ns");
85 #else
86  m_jiffy = 1000000;
87 #endif
88 }
89 
91 {
92  NS_LOG_FUNCTION (this);
93 }
94 
95 bool
97 {
98  NS_LOG_FUNCTION (this);
99  return true;
100 }
101 
102 uint64_t
104 {
105  NS_LOG_FUNCTION (this);
106  return GetNormalizedRealtime ();
107 }
108 
109 void
111 {
112  NS_LOG_FUNCTION (this << ns);
113 //
114 // In order to make sure we're really locking the simulation time to some
115 // wall-clock time, we need to be able to compare that simulation time to
116 // that wall-clock time. The wall clock will have been running for some
117 // long time and will probably have a huge count of nanoseconds in it. We
118 // save the real time away so we can subtract it from "now" later and get
119 // a count of nanoseconds in real time since the simulation started.
120 //
122  NS_LOG_INFO ("origin = " << m_realtimeOriginNano);
123 }
124 
125 int64_t
127 {
128  NS_LOG_FUNCTION (this << ns);
129 //
130 // In order to make sure we're really locking the simulation time to some
131 // wall-clock time, we need to be able to compare that simulation time to
132 // that wall-clock time. In DoSetOrigin we saved the real time at the start
133 // of the simulation away. This is the place where we subtract it from "now"
134 // to a count of nanoseconds in real time since the simulation started. We
135 // then subtract the current real time in normalized nanoseconds we just got
136 // from the normalized simulation time in nanoseconds that is passed in as
137 // the parameter ns. We return an integer difference, but in reality all of
138 // the mechanisms that cause wall-clock to simuator time drift cause events
139 // to be late. That means that the wall-clock will be higher than the
140 // simulation time and drift will be positive. I would be astonished to
141 // see a negative drift, but the possibility is admitted for other
142 // implementations; and we'll use the ability to report an early result in
143 // DoSynchronize below.
144 //
145  uint64_t nsNow = GetNormalizedRealtime ();
146 
147  if (nsNow > ns)
148  {
149 //
150 // Real time (nsNow) is larger/later than the simulator time (ns). We are
151 // behind real time and the difference (drift) is positive.
152 //
153  return (int64_t)(nsNow - ns);
154  }
155  else
156  {
157 //
158 // Real time (nsNow) is smaller/earlier than the simulator time (ns). We are
159 // ahead of real time and the difference (drift) is negative.
160 //
161  return -(int64_t)(ns - nsNow);
162  }
163 }
164 
165 bool
166 WallClockSynchronizer::DoSynchronize (uint64_t nsCurrent, uint64_t nsDelay)
167 {
168  NS_LOG_FUNCTION (this << nsCurrent << nsDelay);
169 //
170 // This is the belly of the beast. We have received two parameters from the
171 // simulator proper -- a current simulation time (nsCurrent) and a simulation
172 // time to delay which identifies the time the next event is supposed to fire.
173 //
174 // The first thing we need to do is to (try and) correct for any realtime
175 // drift that has happened in the system. In this implementation, we realize
176 // that all mechanisms for drift will cause the drift to be such that the
177 // realtime is greater than the simulation time. This typically happens when
178 // our process is put to sleep for a given time, but actually sleeps for
179 // longer. So, what we want to do is to "catch up" to realtime and delay for
180 // less time than we are actually asked to delay. DriftCorrect will return a
181 // number from 0 to nsDelay corresponding to the amount of catching-up we
182 // need to do. If we are more than nsDelay behind, we do not wait at all.
183 //
184 // Note that it will be impossible to catch up if the amount of drift is
185 // cumulatively greater than the amount of delay between events. The method
186 // GetDrift () is available to clients of the syncrhonizer to keep track of
187 // the cumulative drift. The client can assert if the drift gets out of
188 // hand, print warning messages, or just ignore the situation and hope it will
189 // go away.
190 //
191  uint64_t ns = DriftCorrect (nsCurrent, nsDelay);
192  NS_LOG_INFO ("Synchronize ns = " << ns);
193 //
194 // Once we've decided on how long we need to delay, we need to split this
195 // time into sleep waits and busy waits. The reason for this is described
196 // in the comments for the constructor where jiffies and jiffy resolution is
197 // explained.
198 //
199 // Here, I'll just say that we need that the jiffy is the minimum resolution
200 // of the system clock. It can only sleep in blocks of time equal to a jiffy.
201 // If we want to be more accurate than a jiffy (we do) then we need to sleep
202 // for some number of jiffies and then busy wait for any leftover time.
203 //
204  uint64_t numberJiffies = ns / m_jiffy;
205  NS_LOG_INFO ("Synchronize numberJiffies = " << numberJiffies);
206 //
207 // This is where the real world interjects its very ugly head. The code
208 // immediately below reflects the fact that a sleep is actually quite probably
209 // going to end up sleeping for some number of jiffies longer than you wanted.
210 // This is because your system is going to be off doing other unimportant
211 // stuff during that extra time like running file systems and networks. What
212 // we want to do is to ask the system to sleep enough less than the requested
213 // delay so that it comes back early most of the time (coming back early is
214 // fine, coming back late is bad). If we can convince the system to come back
215 // early (most of the time), then we can busy-wait until the requested
216 // completion time actually comes around (most of the time).
217 //
218 // The tradeoff here is, of course, that the less time we spend sleeping, the
219 // more accurately we will sync up; but the more CPU time we will spend busy
220 // waiting (doing nothing).
221 //
222 // I'm not really sure about this number -- a boss of mine once said, "pick
223 // a number and it'll be wrong." But this works for now.
224 //
225 // \todo Hardcoded tunable parameter below.
226 //
227  if (numberJiffies > 3)
228  {
229  NS_LOG_INFO ("SleepWait for " << numberJiffies * m_jiffy << " ns");
230  NS_LOG_INFO ("SleepWait until " << nsCurrent + numberJiffies * m_jiffy
231  << " ns");
232 //
233 // SleepWait is interruptible. If it returns true it meant that the sleep
234 // went until the end. If it returns false, it means that the sleep was
235 // interrupted by a Signal. In this case, we need to return and let the
236 // simulator re-evaluate what to do.
237 //
238  if (SleepWait ((numberJiffies - 3) * m_jiffy) == false)
239  {
240  NS_LOG_INFO ("SleepWait interrupted");
241  return false;
242  }
243  }
244  NS_LOG_INFO ("Done with SleepWait");
245 //
246 // We asked the system to sleep for some number of jiffies, but that doesn't
247 // mean we actually did. Let's re-evaluate what we need to do here. Maybe
248 // we're already late. Probably the "real" delay time left has little to do
249 // with what we would calculate it to be naively.
250 //
251 // We are now at some Realtime. The important question now is not, "what
252 // would we calculate in a mathematicians paradise," it is, "how many
253 // nanoseconds do we need to busy-wait until we get to the Realtime that
254 // corresponds to nsCurrent + nsDelay (in simulation time). We have a handy
255 // function to do just that -- we ask for the time the realtime clock has
256 // drifted away from the simulation clock. That's our answer. If the drift
257 // is negative, we're early and we need to busy wait for that number of
258 // nanoseconds. The place were we want to be is described by the parameters
259 // we were passed by the simulator.
260 //
261  int64_t nsDrift = DoGetDrift (nsCurrent + nsDelay);
262 //
263 // If the drift is positive, we are already late and we need to just bail out
264 // of here as fast as we can. Return true to indicate that the requested time
265 // has, in fact, passed.
266 //
267  if (nsDrift >= 0)
268  {
269  NS_LOG_INFO ("Back from SleepWait: IML8 " << nsDrift);
270  return true;
271  }
272 //
273 // There are some number of nanoseconds left over and we need to wait until
274 // the time defined by nsDrift. We'll do a SpinWait since the usual case
275 // will be that we are doing this Spinwait after we've gotten a rough delay
276 // using the SleepWait above. If SpinWait completes to the end, it will
277 // return true; if it is interrupted by a signal it will return false.
278 //
279  NS_LOG_INFO ("SpinWait until " << nsCurrent + nsDelay);
280  return SpinWait (nsCurrent + nsDelay);
281 }
282 
283 void
285 {
286  NS_LOG_FUNCTION (this);
287 
288  m_condition.SetCondition (true);
289  m_condition.Signal ();
290 }
291 
292 void
294 {
295  NS_LOG_FUNCTION (this << cond);
296  m_condition.SetCondition (cond);
297 }
298 
299 void
301 {
302  NS_LOG_FUNCTION (this);
304 }
305 
306 uint64_t
308 {
309  NS_LOG_FUNCTION (this);
311 }
312 
313 bool
315 {
316  NS_LOG_FUNCTION (this << ns);
317 // We just sit here and spin, wasting CPU cycles until we get to the right
318 // time or are told to leave.
319  for (;;)
320  {
321  if (GetNormalizedRealtime () >= ns)
322  {
323  return true;
324  }
325  if (m_condition.GetCondition ())
326  {
327  return false;
328  }
329  }
330 // Quiet compiler
331  return true;
332 }
333 
334 bool
336 {
337  NS_LOG_FUNCTION (this << ns);
338  return m_condition.TimedWait (ns);
339 }
340 
341 uint64_t
342 WallClockSynchronizer::DriftCorrect (uint64_t nsNow, uint64_t nsDelay)
343 {
344  NS_LOG_FUNCTION (this << nsNow << nsDelay);
345  int64_t drift = DoGetDrift (nsNow);
346 //
347 // If we're running late, drift will be positive and we need to correct by
348 // delaying for less time. If we're early for some bizarre reason, we don't
349 // do anything since we'll almost instantly self-correct.
350 //
351  if (drift < 0)
352  {
353  return nsDelay;
354  }
355 //
356 // If we've drifted out of sync by less than the requested delay, then just
357 // subtract the drift from the delay and fix up the drift in one go. If we
358 // have more drift than delay, then we just play catch up as fast as possible
359 // by not delaying at all.
360 //
361  uint64_t correction = (uint64_t)drift;
362  if (correction <= nsDelay)
363  {
364  return nsDelay - correction;
365  }
366  else
367  {
368  return 0;
369  }
370 }
371 
372 uint64_t
374 {
375  NS_LOG_FUNCTION (this);
376  struct timeval tvNow;
377  gettimeofday (&tvNow, NULL);
378  return TimevalToNs (&tvNow);
379 }
380 
381 uint64_t
383 {
384  NS_LOG_FUNCTION (this);
385  return GetRealtime () - m_realtimeOriginNano;
386 }
387 
388 void
389 WallClockSynchronizer::NsToTimeval (int64_t ns, struct timeval *tv)
390 {
391  NS_LOG_FUNCTION (this << ns << tv);
392  NS_ASSERT ((ns % US_PER_NS) == 0);
393  tv->tv_sec = ns / NS_PER_SEC;
394  tv->tv_usec = (ns % NS_PER_SEC) / US_PER_NS;
395 }
396 
397 uint64_t
399 {
400  NS_LOG_FUNCTION (this << tv);
401  uint64_t nsResult = tv->tv_sec * NS_PER_SEC + tv->tv_usec * US_PER_NS;
402  NS_ASSERT ((nsResult % US_PER_NS) == 0);
403  return nsResult;
404 }
405 
406 void
408  struct timeval *tv1,
409  struct timeval *tv2,
410  struct timeval *result)
411 {
412  NS_LOG_FUNCTION (this << tv1 << tv2 << result);
413  result->tv_sec = tv1->tv_sec + tv2->tv_sec;
414  result->tv_usec = tv1->tv_usec + tv2->tv_usec;
415  if (result->tv_usec > (int64_t)US_PER_SEC)
416  {
417  ++result->tv_sec;
418  result->tv_usec %= US_PER_SEC;
419  }
420 }
421 
422 } // namespace ns3
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by "...
uint64_t m_jiffy
Size of the system clock tick, as reported by clock_getres, in ns.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:44
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:61
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:201
System-independent thread conditional wait.
uint64_t TimevalToNs(struct timeval *tv)
Convert a timeval to absolute time, in ns.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:244
static const uint64_t NS_PER_SEC
Conversion constant between ns and s.
uint64_t m_nsEventStart
Time recorded by DoEventStart.
void Signal(void)
Release one thread if waiting for the condition to be true.
bool SleepWait(uint64_t ns)
Put our process to sleep for some number of nanoseconds.
static const uint64_t US_PER_NS
Conversion constant between μs and ns.
uint64_t GetRealtime(void)
Get the current absolute real time (in ns since the epoch).
virtual int64_t DoGetDrift(uint64_t ns)
Get the drift between the real time clock used to synchronize the simulation and the current simulati...
virtual bool DoRealtime(void)
Return true if this synchronizer is actually synchronizing to a realtime clock.
ns3::WallClockSynchronizer declaration.
void SetCondition(bool condition)
Set the value of the underlying condition.
virtual uint64_t DoGetCurrentRealtime(void)
Retrieve the value of the origin of the underlying normalized wall clock time in Time resolution unit...
virtual bool DoSynchronize(uint64_t nsCurrent, uint64_t nsDelay)
Wait until the real time is in sync with the specified simulation time.
bool GetCondition(void)
Get the value of the underlying condition.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
virtual ~WallClockSynchronizer()
Destructor.
Base class used for synchronizing the simulation events to some real time "wall clock.".
Definition: synchronizer.h:51
bool TimedWait(uint64_t ns)
Wait a maximum of ns nanoseconds for the condition to be true.
virtual void DoSetOrigin(uint64_t ns)
Establish a correspondence between a simulation time and a wall-clock (real) time.
static const uint64_t US_PER_SEC
Conversion constant between μs and seconds.
uint64_t m_realtimeOriginNano
The real time, in ns, when SetOrigin was called.
Definition: synchronizer.h:314
virtual void DoEventStart(void)
Record the normalized real time at which the current event is starting execution. ...
virtual void DoSetCondition(bool cond)
Set the condition variable to tell a possible simulator thread waiting in the Synchronize method that...
void NsToTimeval(int64_t ns, struct timeval *tv)
Convert an absolute time in ns to a timeval.
static TypeId GetTypeId(void)
Get the registered TypeId for this class.
void TimevalAdd(struct timeval *tv1, struct timeval *tv2, struct timeval *result)
Add two timeval.
SystemCondition m_condition
Thread synchronizer.
Debug message logging.
a unique identifier for an interface.
Definition: type-id.h:51
uint64_t GetNormalizedRealtime(void)
Get the current normalized real time, in ns.
TypeId SetParent(TypeId tid)
Definition: type-id.cc:631
bool SpinWait(uint64_t ns)
Do a busy-wait until the normalized realtime equals the argument or the condition variable becomes tr...
virtual void DoSignal(void)
Tell a possible simulator thread waiting in the DoSynchronize method that an event has happened which...
virtual uint64_t DoEventEnd(void)
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...