From e605065a43a7ab5d7ca94d4dfa41d100023dcd2b Mon Sep 17 00:00:00 2001 From: F5 Date: Sat, 11 Nov 2023 21:17:27 +0800 Subject: [PATCH] Apply clang-format to modified code for ease of merging --- src/core/model/atomic-counter.h | 59 +- src/core/model/hash.h | 285 +- src/core/model/object.cc | 492 +-- src/core/model/simple-ref-count.h | 150 +- src/flow-monitor/model/flow-monitor.cc | 673 ++-- src/flow-monitor/model/flow-monitor.h | 473 +-- .../model/ipv4-flow-classifier.cc | 285 +- src/flow-monitor/model/ipv4-flow-classifier.h | 132 +- src/flow-monitor/model/ipv4-flow-probe.cc | 601 ++-- .../model/ipv6-flow-classifier.cc | 286 +- src/flow-monitor/model/ipv6-flow-classifier.h | 132 +- src/flow-monitor/model/ipv6-flow-probe.cc | 494 +-- .../model/global-route-manager-impl.cc | 2929 ++++++++--------- src/internet/model/ipv4-end-point-demux.cc | 475 +-- src/internet/model/ipv4-global-routing.cc | 766 +++-- src/internet/model/ipv4-global-routing.h | 397 +-- src/internet/model/ipv4-packet-info-tag.cc | 136 +- src/internet/model/ipv6-end-point-demux.cc | 413 +-- src/internet/model/ipv6-packet-info-tag.cc | 128 +- src/internet/model/tcp-option.cc | 165 +- src/mpi/examples/simple-hybrid.cc | 334 +- .../granted-time-window-mpi-interface.cc | 409 +-- .../model/granted-time-window-mpi-interface.h | 186 +- src/mpi/model/hybrid-simulator-impl.cc | 482 +-- src/mpi/model/hybrid-simulator-impl.h | 85 +- src/mpi/model/mpi-interface.cc | 126 +- src/mtp/examples/simple-mtp.cc | 264 +- src/mtp/model/logical-process.cc | 342 +- src/mtp/model/logical-process.h | 161 +- src/mtp/model/mtp-interface.cc | 358 +- src/mtp/model/mtp-interface.h | 232 +- src/mtp/model/multithreaded-simulator-impl.cc | 435 +-- src/mtp/model/multithreaded-simulator-impl.h | 73 +- src/network/model/buffer.cc | 1621 ++++----- src/network/model/buffer.h | 1627 ++++----- src/network/model/byte-tag-list.cc | 676 ++-- src/network/model/node.cc | 472 +-- src/network/model/node.h | 472 +-- src/network/model/packet-metadata.cc | 2154 ++++++------ src/network/model/packet-metadata.h | 1223 +++---- src/network/model/packet-tag-list.h | 435 +-- src/network/model/socket.cc | 932 +++--- src/network/utils/simple-net-device.cc | 724 ++-- .../model/nix-vector-routing.cc | 1783 +++++----- .../model/nix-vector-routing.h | 780 ++--- 45 files changed, 13100 insertions(+), 12757 deletions(-) diff --git a/src/core/model/atomic-counter.h b/src/core/model/atomic-counter.h index 2dd8051dd..81f7f87ac 100644 --- a/src/core/model/atomic-counter.h +++ b/src/core/model/atomic-counter.h @@ -4,44 +4,45 @@ #include -namespace ns3 { +namespace ns3 +{ class AtomicCounter { -public: - inline AtomicCounter () - { - m_count.store (0, std::memory_order_release); - } + public: + inline AtomicCounter() + { + m_count.store(0, std::memory_order_release); + } - inline AtomicCounter (uint32_t count) - { - m_count.store (count, std::memory_order_release); - } + inline AtomicCounter(uint32_t count) + { + m_count.store(count, std::memory_order_release); + } - inline operator uint32_t () const - { - return m_count.load (std::memory_order_acquire); - } + inline operator uint32_t() const + { + return m_count.load(std::memory_order_acquire); + } - inline uint32_t operator = (const uint32_t count) - { - m_count.store (count, std::memory_order_release); - return count; - } + inline uint32_t operator=(const uint32_t count) + { + m_count.store(count, std::memory_order_release); + return count; + } - inline uint32_t operator++ (int) - { - return m_count.fetch_add (1, std::memory_order_relaxed); - } + inline uint32_t operator++(int) + { + return m_count.fetch_add(1, std::memory_order_relaxed); + } - inline uint32_t operator-- (int) - { - return m_count.fetch_sub (1, std::memory_order_release); - } + inline uint32_t operator--(int) + { + return m_count.fetch_sub(1, std::memory_order_release); + } -private: - std::atomic m_count; + private: + std::atomic m_count; }; } // namespace ns3 diff --git a/src/core/model/hash.h b/src/core/model/hash.h index 3c051289f..714bdc221 100644 --- a/src/core/model/hash.h +++ b/src/core/model/hash.h @@ -21,14 +21,13 @@ #ifndef HASH_H #define HASH_H -#include - #include "assert.h" -#include "ptr.h" - +#include "hash-fnv.h" #include "hash-function.h" #include "hash-murmur3.h" -#include "hash-fnv.h" +#include "ptr.h" + +#include /** * \file @@ -36,7 +35,8 @@ * \brief ns3::Hasher, ns3::Hash32() and ns3::Hash64() function declarations. */ -namespace ns3 { +namespace ns3 +{ /** * \ingroup core @@ -86,96 +86,95 @@ namespace ns3 { */ class Hasher { -public: - /** - * Constructor using the default implementation. - */ - Hasher (); - /** - * Constructor using the supplied implementation. - * - * \param [in] hp Ptr to the desired implementation. - */ - Hasher (Ptr hp); - /** - * Compute 32-bit hash of a byte buffer. - * - * Call clear () between calls to GetHash32() to reset the - * internal state and hash each buffer separately. - * - * If you don't call clear() between calls to GetHash32, - * you can hash successive buffers. The final return value - * will be the cumulative hash across all calls. - * - * \param [in] buffer Pointer to the beginning of the buffer. - * \param [in] size Length of the buffer, in bytes. - * \return 32-bit hash of the buffer.. - */ - uint32_t GetHash32 (const char * buffer, const std::size_t size); - /** - * Compute 64-bit hash of a byte buffer. - * - * Call clear () between calls to GetHash64() to reset the - * internal state and hash each buffer separately. - * - * If you don't call clear() between calls to GetHash64, - * you can hash successive buffers. The final return value - * will be the cumulative hash across all calls. - * - * \param [in] buffer Pointer to the beginning of the buffer. - * \param [in] size Length of the buffer, in bytes. - * \return 64-bit hash of the buffer. - */ - uint64_t GetHash64 (const char * buffer, const std::size_t size); + public: + /** + * Constructor using the default implementation. + */ + Hasher(); + /** + * Constructor using the supplied implementation. + * + * \param [in] hp Ptr to the desired implementation. + */ + Hasher(Ptr hp); + /** + * Compute 32-bit hash of a byte buffer. + * + * Call clear () between calls to GetHash32() to reset the + * internal state and hash each buffer separately. + * + * If you don't call clear() between calls to GetHash32, + * you can hash successive buffers. The final return value + * will be the cumulative hash across all calls. + * + * \param [in] buffer Pointer to the beginning of the buffer. + * \param [in] size Length of the buffer, in bytes. + * \return 32-bit hash of the buffer.. + */ + uint32_t GetHash32(const char* buffer, const std::size_t size); + /** + * Compute 64-bit hash of a byte buffer. + * + * Call clear () between calls to GetHash64() to reset the + * internal state and hash each buffer separately. + * + * If you don't call clear() between calls to GetHash64, + * you can hash successive buffers. The final return value + * will be the cumulative hash across all calls. + * + * \param [in] buffer Pointer to the beginning of the buffer. + * \param [in] size Length of the buffer, in bytes. + * \return 64-bit hash of the buffer. + */ + uint64_t GetHash64(const char* buffer, const std::size_t size); - /** - * Compute 32-bit hash of a string. - * - * Call clear () between calls to GetHash32() to reset the - * internal state and hash each string separately. - * - * If you don't call clear() between calls to GetHash32, - * you can hash successive strings. The final return value - * will be the cumulative hash across all calls. - * - * \param [in] s String to hash. - * \return 32-bit hash of the string. - */ - uint32_t GetHash32 (const std::string s); - /** - * Compute 64-bit hash of a string. - * - * Call clear () between calls to GetHash64() to reset the - * internal state and hash each string separately. - * - * If you don't call clear() between calls to GetHash64, - * you can hash successive strings. The final return value - * will be the cumulative hash across all calls. - * - * \param [in] s String to hash. - * \return 64-bit hash of the string. - */ - uint64_t GetHash64 (const std::string s); - /** - * Restore initial state. - * - * Returning this Hasher allows code like this: - * - * \code - * Hasher h; - * h.GetHash32 (...); - * ... - * h.clear ().GetHash64 (...); - * \endcode - * - * \return This hasher. - */ - Hasher & clear (); - -private: - Ptr m_impl; /**< Hash implementation. */ -}; // Hasher + /** + * Compute 32-bit hash of a string. + * + * Call clear () between calls to GetHash32() to reset the + * internal state and hash each string separately. + * + * If you don't call clear() between calls to GetHash32, + * you can hash successive strings. The final return value + * will be the cumulative hash across all calls. + * + * \param [in] s String to hash. + * \return 32-bit hash of the string. + */ + uint32_t GetHash32(const std::string s); + /** + * Compute 64-bit hash of a string. + * + * Call clear () between calls to GetHash64() to reset the + * internal state and hash each string separately. + * + * If you don't call clear() between calls to GetHash64, + * you can hash successive strings. The final return value + * will be the cumulative hash across all calls. + * + * \param [in] s String to hash. + * \return 64-bit hash of the string. + */ + uint64_t GetHash64(const std::string s); + /** + * Restore initial state. + * + * Returning this Hasher allows code like this: + * + * \code + * Hasher h; + * h.GetHash32 (...); + * ... + * h.clear ().GetHash64 (...); + * \endcode + * + * \return This hasher. + */ + Hasher& clear(); + private: + Ptr m_impl; /**< Hash implementation. */ +}; // Hasher /************************************************* ** Global functions declarations @@ -190,7 +189,7 @@ private: * \param [in] size Length of the buffer, in bytes. * \return 32-bit hash of the buffer. */ -uint32_t Hash32 (const char * buffer, const std::size_t size); +uint32_t Hash32(const char* buffer, const std::size_t size); /** * \ingroup hash * @@ -200,7 +199,7 @@ uint32_t Hash32 (const char * buffer, const std::size_t size); * \param [in] size Length of the buffer, in bytes. * \return 64-bit hash of the buffer. */ -uint64_t Hash64 (const char * buffer, const std::size_t size); +uint64_t Hash64(const char* buffer, const std::size_t size); /** * \ingroup hash @@ -210,7 +209,7 @@ uint64_t Hash64 (const char * buffer, const std::size_t size); * \param [in] s String to hash. * \return 32-bit hash of the string. */ -uint32_t Hash32 (const std::string s); +uint32_t Hash32(const std::string s); /** * \ingroup hash * @@ -219,109 +218,99 @@ uint32_t Hash32 (const std::string s); * \param [in] s String to hash. * \return 64-bit hash of the string. */ -uint64_t Hash64 (const std::string s); - -} // namespace ns3 +uint64_t Hash64(const std::string s); +} // namespace ns3 /************************************************* ** Inline implementations for rvo ************************************************/ -namespace ns3 { +namespace ns3 +{ /************************************************* class Hasher implementation, inlined for rvo */ -inline -uint32_t -Hasher::GetHash32 (const char * buffer, const std::size_t size) +inline uint32_t +Hasher::GetHash32(const char* buffer, const std::size_t size) { - NS_ASSERT (m_impl); - return m_impl->GetHash32 (buffer, size); + NS_ASSERT(m_impl); + return m_impl->GetHash32(buffer, size); } -inline -uint64_t -Hasher::GetHash64 (const char * buffer, const std::size_t size) +inline uint64_t +Hasher::GetHash64(const char* buffer, const std::size_t size) { - NS_ASSERT (m_impl); - return m_impl->GetHash64 (buffer, size); + NS_ASSERT(m_impl); + return m_impl->GetHash64(buffer, size); } -inline -uint32_t -Hasher::GetHash32 (const std::string s) +inline uint32_t +Hasher::GetHash32(const std::string s) { - NS_ASSERT (m_impl); - return m_impl->GetHash32 (s.c_str (), s.size ()); + NS_ASSERT(m_impl); + return m_impl->GetHash32(s.c_str(), s.size()); } -inline -uint64_t -Hasher::GetHash64 (const std::string s) +inline uint64_t +Hasher::GetHash64(const std::string s) { - NS_ASSERT (m_impl); - return m_impl->GetHash64 (s.c_str (), s.size ()); + NS_ASSERT(m_impl); + return m_impl->GetHash64(s.c_str(), s.size()); } - /************************************************* Global hash functions, inlined for rvo */ /** - * \brief Get a reference to the static global hasher at g_hasher - * \return Reference to the static Hasher instance. - */ -Hasher& GetStaticHash (); + * \brief Get a reference to the static global hasher at g_hasher + * \return Reference to the static Hasher instance. + */ +Hasher& GetStaticHash(); -inline -uint32_t -Hash32 (const char * buffer, const std::size_t size) +inline uint32_t +Hash32(const char* buffer, const std::size_t size) { #ifdef NS3_MTP - return Hasher ().GetHash32 (buffer, size); + return Hasher().GetHash32(buffer, size); #else - return GetStaticHash ().GetHash32 (buffer, size); + return GetStaticHash().GetHash32(buffer, size); #endif } -inline -uint64_t -Hash64 (const char * buffer, const std::size_t size) +inline uint64_t +Hash64(const char* buffer, const std::size_t size) { #ifdef NS3_MTP - return Hasher ().GetHash64 (buffer, size); + return Hasher().GetHash64(buffer, size); #else - return GetStaticHash ().GetHash64 (buffer, size); + return GetStaticHash().GetHash64(buffer, size); #endif } -inline -uint32_t -Hash32 (const std::string s) +inline uint32_t +Hash32(const std::string s) { #ifdef NS3_MTP - return Hasher ().GetHash32 (s); + return Hasher().GetHash32(s); #else - return GetStaticHash ().GetHash32 (s); + return GetStaticHash().GetHash32(s); #endif } -inline -uint64_t -Hash64 (const std::string s) +inline uint64_t +Hash64(const std::string s) { #ifdef NS3_MTP - return Hasher ().GetHash64 (s); + return Hasher().GetHash64(s); #else - return GetStaticHash ().GetHash64 (s); + return GetStaticHash().GetHash64(s); #endif } - -} // namespace ns3 +} // namespace ns3 #endif /* HASH_H */ diff --git a/src/core/model/object.cc b/src/core/model/object.cc index 1d83e9430..8bfaf051c 100644 --- a/src/core/model/object.cc +++ b/src/core/model/object.cc @@ -20,15 +20,17 @@ */ #include "object.h" -#include "object-factory.h" + #include "assert.h" #include "attribute.h" #include "log.h" +#include "object-factory.h" #include "string.h" -#include -#include + #include #include +#include +#include /** * \file @@ -36,333 +38,339 @@ * ns3::Object class implementation. */ -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Object"); +NS_LOG_COMPONENT_DEFINE("Object"); /********************************************************************* * The Object implementation *********************************************************************/ -NS_OBJECT_ENSURE_REGISTERED (Object); +NS_OBJECT_ENSURE_REGISTERED(Object); -Object::AggregateIterator::AggregateIterator () - : m_object (nullptr), - m_current (0) +Object::AggregateIterator::AggregateIterator() + : m_object(nullptr), + m_current(0) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } bool -Object::AggregateIterator::HasNext () const +Object::AggregateIterator::HasNext() const { - NS_LOG_FUNCTION (this); - return m_current < m_object->m_aggregates->n; + NS_LOG_FUNCTION(this); + return m_current < m_object->m_aggregates->n; } + Ptr -Object::AggregateIterator::Next () +Object::AggregateIterator::Next() { - NS_LOG_FUNCTION (this); - Object *object = m_object->m_aggregates->buffer[m_current]; - m_current++; - return object; -} -Object::AggregateIterator::AggregateIterator (Ptr object) - : m_object (object), - m_current (0) -{ - NS_LOG_FUNCTION (this << object); + NS_LOG_FUNCTION(this); + Object* object = m_object->m_aggregates->buffer[m_current]; + m_current++; + return object; } - -TypeId -Object::GetInstanceTypeId () const +Object::AggregateIterator::AggregateIterator(Ptr object) + : m_object(object), + m_current(0) { - NS_LOG_FUNCTION (this); - return m_tid; + NS_LOG_FUNCTION(this << object); } TypeId -Object::GetTypeId () +Object::GetInstanceTypeId() const { - static TypeId tid = TypeId ("ns3::Object") - .SetParent () - .SetGroupName ("Core") - ; - return tid; + NS_LOG_FUNCTION(this); + return m_tid; } - -Object::Object () - : m_tid (Object::GetTypeId ()), - m_disposed (false), - m_initialized (false), - m_aggregates ((struct Aggregates *) std::malloc (sizeof (struct Aggregates))), - m_getObjectCount (0) +TypeId +Object::GetTypeId() { - NS_LOG_FUNCTION (this); - m_aggregates->n = 1; - m_aggregates->buffer[0] = this; + static TypeId tid = TypeId("ns3::Object").SetParent().SetGroupName("Core"); + return tid; } -Object::~Object () + +Object::Object() + : m_tid(Object::GetTypeId()), + m_disposed(false), + m_initialized(false), + m_aggregates((struct Aggregates*)std::malloc(sizeof(struct Aggregates))), + m_getObjectCount(0) { - // remove this object from the aggregate list - NS_LOG_FUNCTION (this); - uint32_t n = m_aggregates->n; - for (uint32_t i = 0; i < n; i++) + NS_LOG_FUNCTION(this); + m_aggregates->n = 1; + m_aggregates->buffer[0] = this; +} + +Object::~Object() +{ + // remove this object from the aggregate list + NS_LOG_FUNCTION(this); + uint32_t n = m_aggregates->n; + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - if (current == this) + Object* current = m_aggregates->buffer[i]; + if (current == this) { - std::memmove (&m_aggregates->buffer[i], - &m_aggregates->buffer[i + 1], - sizeof (Object *) * (m_aggregates->n - (i + 1))); - m_aggregates->n--; + std::memmove(&m_aggregates->buffer[i], + &m_aggregates->buffer[i + 1], + sizeof(Object*) * (m_aggregates->n - (i + 1))); + m_aggregates->n--; } } - // finally, if all objects have been removed from the list, - // delete the aggregate list - if (m_aggregates->n == 0) + // finally, if all objects have been removed from the list, + // delete the aggregate list + if (m_aggregates->n == 0) { - std::free (m_aggregates); + std::free(m_aggregates); } - m_aggregates = nullptr; + m_aggregates = nullptr; } -Object::Object (const Object &o) - : m_tid (o.m_tid), - m_disposed (false), - m_initialized (false), - m_aggregates ((struct Aggregates *) std::malloc (sizeof (struct Aggregates))), - m_getObjectCount (0) + +Object::Object(const Object& o) + : m_tid(o.m_tid), + m_disposed(false), + m_initialized(false), + m_aggregates((struct Aggregates*)std::malloc(sizeof(struct Aggregates))), + m_getObjectCount(0) { - m_aggregates->n = 1; - m_aggregates->buffer[0] = this; + m_aggregates->n = 1; + m_aggregates->buffer[0] = this; } + void -Object::Construct (const AttributeConstructionList &attributes) +Object::Construct(const AttributeConstructionList& attributes) { - NS_LOG_FUNCTION (this << &attributes); - ConstructSelf (attributes); + NS_LOG_FUNCTION(this << &attributes); + ConstructSelf(attributes); } Ptr -Object::DoGetObject (TypeId tid) const +Object::DoGetObject(TypeId tid) const { - NS_LOG_FUNCTION (this << tid); - NS_ASSERT (CheckLoose ()); + NS_LOG_FUNCTION(this << tid); + NS_ASSERT(CheckLoose()); - uint32_t n = m_aggregates->n; - TypeId objectTid = Object::GetTypeId (); - for (uint32_t i = 0; i < n; i++) + uint32_t n = m_aggregates->n; + TypeId objectTid = Object::GetTypeId(); + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - TypeId cur = current->GetInstanceTypeId (); - while (cur != tid && cur != objectTid) + Object* current = m_aggregates->buffer[i]; + TypeId cur = current->GetInstanceTypeId(); + while (cur != tid && cur != objectTid) { - cur = cur.GetParent (); + cur = cur.GetParent(); } - if (cur == tid) + if (cur == tid) { #ifndef NS3_MTP - // This is an attempt to 'cache' the result of this lookup. - // the idea is that if we perform a lookup for a TypeId on this object, - // we are likely to perform the same lookup later so, we make sure - // that the aggregate array is sorted by the number of accesses - // to each object. + // This is an attempt to 'cache' the result of this lookup. + // the idea is that if we perform a lookup for a TypeId on this object, + // we are likely to perform the same lookup later so, we make sure + // that the aggregate array is sorted by the number of accesses + // to each object. - // first, increment the access count - current->m_getObjectCount++; - // then, update the sort - UpdateSortedArray (m_aggregates, i); + // first, increment the access count + current->m_getObjectCount++; + // then, update the sort + UpdateSortedArray(m_aggregates, i); #endif - // finally, return the match - return const_cast (current); + // finally, return the match + return const_cast(current); } } - return nullptr; + return nullptr; } + void -Object::Initialize () +Object::Initialize() { - /** - * Note: the code here is a bit tricky because we need to protect ourselves from - * modifications in the aggregate array while DoInitialize is called. The user's - * implementation of the DoInitialize method could call GetObject (which could - * reorder the array) and it could call AggregateObject which would add an - * object at the end of the array. To be safe, we restart iteration over the - * array whenever we call some user code, just in case. - */ - NS_LOG_FUNCTION (this); + /** + * Note: the code here is a bit tricky because we need to protect ourselves from + * modifications in the aggregate array while DoInitialize is called. The user's + * implementation of the DoInitialize method could call GetObject (which could + * reorder the array) and it could call AggregateObject which would add an + * object at the end of the array. To be safe, we restart iteration over the + * array whenever we call some user code, just in case. + */ + NS_LOG_FUNCTION(this); restart: - uint32_t n = m_aggregates->n; - for (uint32_t i = 0; i < n; i++) + uint32_t n = m_aggregates->n; + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - if (!current->m_initialized) + Object* current = m_aggregates->buffer[i]; + if (!current->m_initialized) { - current->DoInitialize (); - current->m_initialized = true; - goto restart; + current->DoInitialize(); + current->m_initialized = true; + goto restart; } } } + bool -Object::IsInitialized () const +Object::IsInitialized() const { - NS_LOG_FUNCTION (this); - return m_initialized; + NS_LOG_FUNCTION(this); + return m_initialized; } + void -Object::Dispose () +Object::Dispose() { - /** - * Note: the code here is a bit tricky because we need to protect ourselves from - * modifications in the aggregate array while DoDispose is called. The user's - * DoDispose implementation could call GetObject (which could reorder the array) - * and it could call AggregateObject which would add an object at the end of the array. - * So, to be safe, we restart the iteration over the array whenever we call some - * user code. - */ - NS_LOG_FUNCTION (this); + /** + * Note: the code here is a bit tricky because we need to protect ourselves from + * modifications in the aggregate array while DoDispose is called. The user's + * DoDispose implementation could call GetObject (which could reorder the array) + * and it could call AggregateObject which would add an object at the end of the array. + * So, to be safe, we restart the iteration over the array whenever we call some + * user code. + */ + NS_LOG_FUNCTION(this); restart: - uint32_t n = m_aggregates->n; - for (uint32_t i = 0; i < n; i++) + uint32_t n = m_aggregates->n; + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - if (!current->m_disposed) + Object* current = m_aggregates->buffer[i]; + if (!current->m_disposed) { - current->DoDispose (); - current->m_disposed = true; - goto restart; + current->DoDispose(); + current->m_disposed = true; + goto restart; } } } + void -Object::UpdateSortedArray (struct Aggregates *aggregates, uint32_t j) const +Object::UpdateSortedArray(struct Aggregates* aggregates, uint32_t j) const { - NS_LOG_FUNCTION (this << aggregates << j); - while (j > 0 - && aggregates->buffer[j]->m_getObjectCount > aggregates->buffer[j - 1]->m_getObjectCount) + NS_LOG_FUNCTION(this << aggregates << j); + while (j > 0 && + aggregates->buffer[j]->m_getObjectCount > aggregates->buffer[j - 1]->m_getObjectCount) { - Object *tmp = aggregates->buffer[j - 1]; - aggregates->buffer[j - 1] = aggregates->buffer[j]; - aggregates->buffer[j] = tmp; - j--; + Object* tmp = aggregates->buffer[j - 1]; + aggregates->buffer[j - 1] = aggregates->buffer[j]; + aggregates->buffer[j] = tmp; + j--; } } + void -Object::AggregateObject (Ptr o) +Object::AggregateObject(Ptr o) { - NS_LOG_FUNCTION (this << o); - NS_ASSERT (!m_disposed); - NS_ASSERT (!o->m_disposed); - NS_ASSERT (CheckLoose ()); - NS_ASSERT (o->CheckLoose ()); + NS_LOG_FUNCTION(this << o); + NS_ASSERT(!m_disposed); + NS_ASSERT(!o->m_disposed); + NS_ASSERT(CheckLoose()); + NS_ASSERT(o->CheckLoose()); - Object *other = PeekPointer (o); - // first create the new aggregate buffer. - uint32_t total = m_aggregates->n + other->m_aggregates->n; - struct Aggregates *aggregates = - (struct Aggregates *)std::malloc (sizeof(struct Aggregates) + (total - 1) * sizeof(Object*)); - aggregates->n = total; + Object* other = PeekPointer(o); + // first create the new aggregate buffer. + uint32_t total = m_aggregates->n + other->m_aggregates->n; + struct Aggregates* aggregates = + (struct Aggregates*)std::malloc(sizeof(struct Aggregates) + (total - 1) * sizeof(Object*)); + aggregates->n = total; - // copy our buffer to the new buffer - std::memcpy (&aggregates->buffer[0], - &m_aggregates->buffer[0], - m_aggregates->n * sizeof(Object*)); + // copy our buffer to the new buffer + std::memcpy(&aggregates->buffer[0], + &m_aggregates->buffer[0], + m_aggregates->n * sizeof(Object*)); - // append the other buffer into the new buffer too - for (uint32_t i = 0; i < other->m_aggregates->n; i++) + // append the other buffer into the new buffer too + for (uint32_t i = 0; i < other->m_aggregates->n; i++) { - aggregates->buffer[m_aggregates->n + i] = other->m_aggregates->buffer[i]; - const TypeId typeId = other->m_aggregates->buffer[i]->GetInstanceTypeId (); - if (DoGetObject (typeId)) + aggregates->buffer[m_aggregates->n + i] = other->m_aggregates->buffer[i]; + const TypeId typeId = other->m_aggregates->buffer[i]->GetInstanceTypeId(); + if (DoGetObject(typeId)) { - NS_FATAL_ERROR ("Object::AggregateObject(): " - "Multiple aggregation of objects of type " << - other->GetInstanceTypeId () << - " on objects of type " << typeId); + NS_FATAL_ERROR("Object::AggregateObject(): " + "Multiple aggregation of objects of type " + << other->GetInstanceTypeId() << " on objects of type " << typeId); } - UpdateSortedArray (aggregates, m_aggregates->n + i); + UpdateSortedArray(aggregates, m_aggregates->n + i); } - // keep track of the old aggregate buffers for the iteration - // of NotifyNewAggregates - struct Aggregates *a = m_aggregates; - struct Aggregates *b = other->m_aggregates; + // keep track of the old aggregate buffers for the iteration + // of NotifyNewAggregates + struct Aggregates* a = m_aggregates; + struct Aggregates* b = other->m_aggregates; - // Then, assign the new aggregation buffer to every object - uint32_t n = aggregates->n; - for (uint32_t i = 0; i < n; i++) + // Then, assign the new aggregation buffer to every object + uint32_t n = aggregates->n; + for (uint32_t i = 0; i < n; i++) { - Object *current = aggregates->buffer[i]; - current->m_aggregates = aggregates; + Object* current = aggregates->buffer[i]; + current->m_aggregates = aggregates; } - // Finally, call NotifyNewAggregate on all the objects aggregates together. - // We purposely use the old aggregate buffers to iterate over the objects - // because this allows us to assume that they will not change from under - // our feet, even if our users call AggregateObject from within their - // NotifyNewAggregate method. - for (uint32_t i = 0; i < a->n; i++) + // Finally, call NotifyNewAggregate on all the objects aggregates together. + // We purposely use the old aggregate buffers to iterate over the objects + // because this allows us to assume that they will not change from under + // our feet, even if our users call AggregateObject from within their + // NotifyNewAggregate method. + for (uint32_t i = 0; i < a->n; i++) { - Object *current = a->buffer[i]; - current->NotifyNewAggregate (); + Object* current = a->buffer[i]; + current->NotifyNewAggregate(); } - for (uint32_t i = 0; i < b->n; i++) + for (uint32_t i = 0; i < b->n; i++) { - Object *current = b->buffer[i]; - current->NotifyNewAggregate (); + Object* current = b->buffer[i]; + current->NotifyNewAggregate(); } - // Now that we are done with them, we can free our old aggregate buffers - std::free (a); - std::free (b); + // Now that we are done with them, we can free our old aggregate buffers + std::free(a); + std::free(b); } + /** * This function must be implemented in the stack that needs to notify * other stacks connected to the node of their presence in the node. */ void -Object::NotifyNewAggregate () +Object::NotifyNewAggregate() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } Object::AggregateIterator -Object::GetAggregateIterator () const +Object::GetAggregateIterator() const { - NS_LOG_FUNCTION (this); - return AggregateIterator (this); + NS_LOG_FUNCTION(this); + return AggregateIterator(this); } void -Object::SetTypeId (TypeId tid) +Object::SetTypeId(TypeId tid) { - NS_LOG_FUNCTION (this << tid); - NS_ASSERT (Check ()); - m_tid = tid; + NS_LOG_FUNCTION(this << tid); + NS_ASSERT(Check()); + m_tid = tid; } void -Object::DoDispose () +Object::DoDispose() { - NS_LOG_FUNCTION (this); - NS_ASSERT (!m_disposed); + NS_LOG_FUNCTION(this); + NS_ASSERT(!m_disposed); } void -Object::DoInitialize () +Object::DoInitialize() { - NS_LOG_FUNCTION (this); - NS_ASSERT (!m_initialized); + NS_LOG_FUNCTION(this); + NS_ASSERT(!m_initialized); } bool -Object::Check () const +Object::Check() const { - NS_LOG_FUNCTION (this); - return (GetReferenceCount () > 0); + NS_LOG_FUNCTION(this); + return (GetReferenceCount() > 0); } /* In some cases, when an event is scheduled against a subclass of @@ -373,61 +381,61 @@ Object::Check () const * check the aggregate reference count. */ bool -Object::CheckLoose () const +Object::CheckLoose() const { - NS_LOG_FUNCTION (this); - bool nonZeroRefCount = false; - uint32_t n = m_aggregates->n; - for (uint32_t i = 0; i < n; i++) + NS_LOG_FUNCTION(this); + bool nonZeroRefCount = false; + uint32_t n = m_aggregates->n; + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - if (current->GetReferenceCount ()) + Object* current = m_aggregates->buffer[i]; + if (current->GetReferenceCount()) { - nonZeroRefCount = true; - break; + nonZeroRefCount = true; + break; } } - return nonZeroRefCount; + return nonZeroRefCount; } + void -Object::DoDelete () +Object::DoDelete() { - // check if we really need to die - NS_LOG_FUNCTION (this); - for (uint32_t i = 0; i < m_aggregates->n; i++) + // check if we really need to die + NS_LOG_FUNCTION(this); + for (uint32_t i = 0; i < m_aggregates->n; i++) { - Object *current = m_aggregates->buffer[i]; - if (current->GetReferenceCount () > 0) + Object* current = m_aggregates->buffer[i]; + if (current->GetReferenceCount() > 0) { - return; + return; } } - // Now, we know that we are alone to use this aggregate so, - // we can dispose and delete everything safely. + // Now, we know that we are alone to use this aggregate so, + // we can dispose and delete everything safely. - uint32_t n = m_aggregates->n; - // Ensure we are disposed. - for (uint32_t i = 0; i < n; i++) + uint32_t n = m_aggregates->n; + // Ensure we are disposed. + for (uint32_t i = 0; i < n; i++) { - Object *current = m_aggregates->buffer[i]; - if (!current->m_disposed) + Object* current = m_aggregates->buffer[i]; + if (!current->m_disposed) { - current->DoDispose (); + current->DoDispose(); } } - // Now, actually delete all objects - struct Aggregates *aggregates = m_aggregates; - for (uint32_t i = 0; i < n; i++) + // Now, actually delete all objects + struct Aggregates* aggregates = m_aggregates; + for (uint32_t i = 0; i < n; i++) { - // There is a trick here: each time we call delete below, - // the deleted object is removed from the aggregate buffer - // in the destructor so, the index of the next element to - // lookup is always zero - Object *current = aggregates->buffer[0]; - delete current; + // There is a trick here: each time we call delete below, + // the deleted object is removed from the aggregate buffer + // in the destructor so, the index of the next element to + // lookup is always zero + Object* current = aggregates->buffer[0]; + delete current; } } } // namespace ns3 - diff --git a/src/core/model/simple-ref-count.h b/src/core/model/simple-ref-count.h index 7e50886c5..b82eb5dfb 100644 --- a/src/core/model/simple-ref-count.h +++ b/src/core/model/simple-ref-count.h @@ -22,11 +22,12 @@ #ifndef SIMPLE_REF_COUNT_H #define SIMPLE_REF_COUNT_H +#include "assert.h" #include "atomic-counter.h" #include "default-deleter.h" -#include "assert.h" -#include + #include +#include /** * \file @@ -34,7 +35,8 @@ * ns3::SimpleRefCount declaration and template implementation. */ -namespace ns3 { +namespace ns3 +{ /** * \ingroup ptr @@ -44,7 +46,6 @@ class empty { }; - /** * \ingroup ptr * \brief A template-based reference counting class @@ -77,82 +78,87 @@ class empty * * Interesting users of this class include ns3::Object as well as ns3::Packet. */ -template > +template > class SimpleRefCount : public PARENT { -public: - /** Default constructor. */ - SimpleRefCount () - : m_count (1) - {} - /** - * Copy constructor - * \param [in] o The object to copy into this one. - */ - SimpleRefCount (const SimpleRefCount & o [[maybe_unused]]) - : m_count (1) - { - } - /** - * Assignment operator - * \param [in] o The object to copy - * \returns The copy of \pname{o} - */ - SimpleRefCount &operator = ([[maybe_unused]] const SimpleRefCount &o) - { - return *this; - } - /** - * Increment the reference count. This method should not be called - * by user code. SimpleRefCount instances are expected to be used in - * conjunction with the Ptr template which would make calling Ref - * unnecessary and dangerous. - */ - inline void Ref () const - { - NS_ASSERT (m_count < std::numeric_limits::max ()); - m_count++; - } - /** - * Decrement the reference count. This method should not be called - * by user code. SimpleRefCount instances are expected to be used in - * conjunction with the Ptr template which would make calling Ref - * unnecessary and dangerous. - */ - inline void Unref () const - { - if (m_count-- == 1) - { + public: + /** Default constructor. */ + SimpleRefCount() + : m_count(1) + { + } + + /** + * Copy constructor + * \param [in] o The object to copy into this one. + */ + SimpleRefCount(const SimpleRefCount& o [[maybe_unused]]) + : m_count(1) + { + } + + /** + * Assignment operator + * \param [in] o The object to copy + * \returns The copy of \pname{o} + */ + SimpleRefCount& operator=([[maybe_unused]] const SimpleRefCount& o) + { + return *this; + } + + /** + * Increment the reference count. This method should not be called + * by user code. SimpleRefCount instances are expected to be used in + * conjunction with the Ptr template which would make calling Ref + * unnecessary and dangerous. + */ + inline void Ref() const + { + NS_ASSERT(m_count < std::numeric_limits::max()); + m_count++; + } + + /** + * Decrement the reference count. This method should not be called + * by user code. SimpleRefCount instances are expected to be used in + * conjunction with the Ptr template which would make calling Ref + * unnecessary and dangerous. + */ + inline void Unref() const + { + if (m_count-- == 1) + { #ifdef NS3_MTP - std::atomic_thread_fence (std::memory_order_acquire); + std::atomic_thread_fence(std::memory_order_acquire); #endif - DELETER::Delete (static_cast (const_cast (this))); - } - } + DELETER::Delete(static_cast(const_cast(this))); + } + } - /** - * Get the reference count of the object. - * Normally not needed; for language bindings. - * - * \return The reference count. - */ - inline uint32_t GetReferenceCount () const - { - return m_count; - } + /** + * Get the reference count of the object. + * Normally not needed; for language bindings. + * + * \return The reference count. + */ + inline uint32_t GetReferenceCount() const + { + return m_count; + } -private: - /** - * The reference count. - * - * \internal - * Note we make this mutable so that the const methods can still - * change it. - */ + private: + /** + * The reference count. + * + * \internal + * Note we make this mutable so that the const methods can still + * change it. + */ #ifdef NS3_MTP - mutable AtomicCounter m_count; + mutable AtomicCounter m_count; #else - mutable uint32_t m_count; + mutable uint32_t m_count; #endif }; diff --git a/src/flow-monitor/model/flow-monitor.cc b/src/flow-monitor/model/flow-monitor.cc index 6a69b71ac..da5f2cf17 100644 --- a/src/flow-monitor/model/flow-monitor.cc +++ b/src/flow-monitor/model/flow-monitor.cc @@ -19,557 +19,568 @@ // #include "flow-monitor.h" -#include "ns3/simulator.h" -#include "ns3/log.h" + #include "ns3/double.h" +#include "ns3/log.h" +#include "ns3/simulator.h" + #include #include -#define PERIODIC_CHECK_INTERVAL (Seconds (1)) +#define PERIODIC_CHECK_INTERVAL (Seconds(1)) -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("FlowMonitor"); +NS_LOG_COMPONENT_DEFINE("FlowMonitor"); -NS_OBJECT_ENSURE_REGISTERED (FlowMonitor); +NS_OBJECT_ENSURE_REGISTERED(FlowMonitor); TypeId -FlowMonitor::GetTypeId () +FlowMonitor::GetTypeId() { - static TypeId tid = TypeId ("ns3::FlowMonitor") - .SetParent () - .SetGroupName ("FlowMonitor") - .AddConstructor () - .AddAttribute ("MaxPerHopDelay", ("The maximum per-hop delay that should be considered. " - "Packets still not received after this delay are to be considered lost."), - TimeValue (Seconds (10.0)), - MakeTimeAccessor (&FlowMonitor::m_maxPerHopDelay), - MakeTimeChecker ()) - .AddAttribute ("StartTime", ("The time when the monitoring starts."), - TimeValue (Seconds (0.0)), - MakeTimeAccessor (&FlowMonitor::Start), - MakeTimeChecker ()) - .AddAttribute ("DelayBinWidth", ("The width used in the delay histogram."), - DoubleValue (0.001), - MakeDoubleAccessor (&FlowMonitor::m_delayBinWidth), - MakeDoubleChecker ()) - .AddAttribute ("JitterBinWidth", ("The width used in the jitter histogram."), - DoubleValue (0.001), - MakeDoubleAccessor (&FlowMonitor::m_jitterBinWidth), - MakeDoubleChecker ()) - .AddAttribute ("PacketSizeBinWidth", ("The width used in the packetSize histogram."), - DoubleValue (20), - MakeDoubleAccessor (&FlowMonitor::m_packetSizeBinWidth), - MakeDoubleChecker ()) - .AddAttribute ("FlowInterruptionsBinWidth", ("The width used in the flowInterruptions histogram."), - DoubleValue (0.250), - MakeDoubleAccessor (&FlowMonitor::m_flowInterruptionsBinWidth), - MakeDoubleChecker ()) - .AddAttribute ("FlowInterruptionsMinTime", ("The minimum inter-arrival time that is considered a flow interruption."), - TimeValue (Seconds (0.5)), - MakeTimeAccessor (&FlowMonitor::m_flowInterruptionsMinTime), - MakeTimeChecker ()) - ; - return tid; + static TypeId tid = + TypeId("ns3::FlowMonitor") + .SetParent() + .SetGroupName("FlowMonitor") + .AddConstructor() + .AddAttribute( + "MaxPerHopDelay", + ("The maximum per-hop delay that should be considered. " + "Packets still not received after this delay are to be considered lost."), + TimeValue(Seconds(10.0)), + MakeTimeAccessor(&FlowMonitor::m_maxPerHopDelay), + MakeTimeChecker()) + .AddAttribute("StartTime", + ("The time when the monitoring starts."), + TimeValue(Seconds(0.0)), + MakeTimeAccessor(&FlowMonitor::Start), + MakeTimeChecker()) + .AddAttribute("DelayBinWidth", + ("The width used in the delay histogram."), + DoubleValue(0.001), + MakeDoubleAccessor(&FlowMonitor::m_delayBinWidth), + MakeDoubleChecker()) + .AddAttribute("JitterBinWidth", + ("The width used in the jitter histogram."), + DoubleValue(0.001), + MakeDoubleAccessor(&FlowMonitor::m_jitterBinWidth), + MakeDoubleChecker()) + .AddAttribute("PacketSizeBinWidth", + ("The width used in the packetSize histogram."), + DoubleValue(20), + MakeDoubleAccessor(&FlowMonitor::m_packetSizeBinWidth), + MakeDoubleChecker()) + .AddAttribute("FlowInterruptionsBinWidth", + ("The width used in the flowInterruptions histogram."), + DoubleValue(0.250), + MakeDoubleAccessor(&FlowMonitor::m_flowInterruptionsBinWidth), + MakeDoubleChecker()) + .AddAttribute( + "FlowInterruptionsMinTime", + ("The minimum inter-arrival time that is considered a flow interruption."), + TimeValue(Seconds(0.5)), + MakeTimeAccessor(&FlowMonitor::m_flowInterruptionsMinTime), + MakeTimeChecker()); + return tid; } TypeId -FlowMonitor::GetInstanceTypeId () const +FlowMonitor::GetInstanceTypeId() const { - return GetTypeId (); + return GetTypeId(); } -FlowMonitor::FlowMonitor () - : m_enabled (false) +FlowMonitor::FlowMonitor() + : m_enabled(false) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); #ifdef NS3_MTP - m_lock.store (false, std::memory_order_relaxed); + m_lock.store(false, std::memory_order_relaxed); #endif } void -FlowMonitor::DoDispose () +FlowMonitor::DoDispose() { - NS_LOG_FUNCTION (this); - Simulator::Cancel (m_startEvent); - Simulator::Cancel (m_stopEvent); - for (std::list >::iterator iter = m_classifiers.begin (); - iter != m_classifiers.end (); - iter ++) + NS_LOG_FUNCTION(this); + Simulator::Cancel(m_startEvent); + Simulator::Cancel(m_stopEvent); + for (std::list>::iterator iter = m_classifiers.begin(); + iter != m_classifiers.end(); + iter++) { - *iter = nullptr; + *iter = nullptr; } - for (uint32_t i = 0; i < m_flowProbes.size (); i++) + for (uint32_t i = 0; i < m_flowProbes.size(); i++) { - m_flowProbes[i]->Dispose (); - m_flowProbes[i] = nullptr; + m_flowProbes[i]->Dispose(); + m_flowProbes[i] = nullptr; } - Object::DoDispose (); + Object::DoDispose(); } inline FlowMonitor::FlowStats& -FlowMonitor::GetStatsForFlow (FlowId flowId) +FlowMonitor::GetStatsForFlow(FlowId flowId) { - NS_LOG_FUNCTION (this); - FlowStatsContainerI iter; - iter = m_flowStats.find (flowId); - if (iter == m_flowStats.end ()) + NS_LOG_FUNCTION(this); + FlowStatsContainerI iter; + iter = m_flowStats.find(flowId); + if (iter == m_flowStats.end()) { - FlowMonitor::FlowStats &ref = m_flowStats[flowId]; - ref.delaySum = Seconds (0); - ref.jitterSum = Seconds (0); - ref.lastDelay = Seconds (0); - ref.txBytes = 0; - ref.rxBytes = 0; - ref.txPackets = 0; - ref.rxPackets = 0; - ref.lostPackets = 0; - ref.timesForwarded = 0; - ref.delayHistogram.SetDefaultBinWidth (m_delayBinWidth); - ref.jitterHistogram.SetDefaultBinWidth (m_jitterBinWidth); - ref.packetSizeHistogram.SetDefaultBinWidth (m_packetSizeBinWidth); - ref.flowInterruptionsHistogram.SetDefaultBinWidth (m_flowInterruptionsBinWidth); - return ref; + FlowMonitor::FlowStats& ref = m_flowStats[flowId]; + ref.delaySum = Seconds(0); + ref.jitterSum = Seconds(0); + ref.lastDelay = Seconds(0); + ref.txBytes = 0; + ref.rxBytes = 0; + ref.txPackets = 0; + ref.rxPackets = 0; + ref.lostPackets = 0; + ref.timesForwarded = 0; + ref.delayHistogram.SetDefaultBinWidth(m_delayBinWidth); + ref.jitterHistogram.SetDefaultBinWidth(m_jitterBinWidth); + ref.packetSizeHistogram.SetDefaultBinWidth(m_packetSizeBinWidth); + ref.flowInterruptionsHistogram.SetDefaultBinWidth(m_flowInterruptionsBinWidth); + return ref; } - else + else { - return iter->second; + return iter->second; } } - void -FlowMonitor::ReportFirstTx (Ptr probe, uint32_t flowId, uint32_t packetId, uint32_t packetSize) +FlowMonitor::ReportFirstTx(Ptr probe, + uint32_t flowId, + uint32_t packetId, + uint32_t packetSize) { - NS_LOG_FUNCTION (this << probe << flowId << packetId << packetSize); - if (!m_enabled) + NS_LOG_FUNCTION(this << probe << flowId << packetId << packetSize); + if (!m_enabled) { - NS_LOG_DEBUG ("FlowMonitor not enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor not enabled; returning"); + return; } - Time now = Simulator::Now (); + Time now = Simulator::Now(); #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - TrackedPacket &tracked = m_trackedPackets[std::make_pair (flowId, packetId)]; - tracked.firstSeenTime = now; - tracked.lastSeenTime = tracked.firstSeenTime; - tracked.timesForwarded = 0; - NS_LOG_DEBUG ("ReportFirstTx: adding tracked packet (flowId=" << flowId << ", packetId=" << packetId - << ")."); + TrackedPacket& tracked = m_trackedPackets[std::make_pair(flowId, packetId)]; + tracked.firstSeenTime = now; + tracked.lastSeenTime = tracked.firstSeenTime; + tracked.timesForwarded = 0; + NS_LOG_DEBUG("ReportFirstTx: adding tracked packet (flowId=" << flowId << ", packetId=" + << packetId << ")."); - probe->AddPacketStats (flowId, packetSize, Seconds (0)); + probe->AddPacketStats(flowId, packetSize, Seconds(0)); - FlowStats &stats = GetStatsForFlow (flowId); - stats.txBytes += packetSize; - stats.txPackets++; - if (stats.txPackets == 1) + FlowStats& stats = GetStatsForFlow(flowId); + stats.txBytes += packetSize; + stats.txPackets++; + if (stats.txPackets == 1) { - stats.timeFirstTxPacket = now; + stats.timeFirstTxPacket = now; } - stats.timeLastTxPacket = now; + stats.timeLastTxPacket = now; #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif } - void -FlowMonitor::ReportForwarding (Ptr probe, uint32_t flowId, uint32_t packetId, uint32_t packetSize) +FlowMonitor::ReportForwarding(Ptr probe, + uint32_t flowId, + uint32_t packetId, + uint32_t packetSize) { - NS_LOG_FUNCTION (this << probe << flowId << packetId << packetSize); - if (!m_enabled) + NS_LOG_FUNCTION(this << probe << flowId << packetId << packetSize); + if (!m_enabled) { - NS_LOG_DEBUG ("FlowMonitor not enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor not enabled; returning"); + return; } #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - std::pair key (flowId, packetId); - TrackedPacketMap::iterator tracked = m_trackedPackets.find (key); - if (tracked == m_trackedPackets.end ()) + std::pair key(flowId, packetId); + TrackedPacketMap::iterator tracked = m_trackedPackets.find(key); + if (tracked == m_trackedPackets.end()) { - NS_LOG_WARN ("Received packet forward report (flowId=" << flowId << ", packetId=" << packetId - << ") but not known to be transmitted."); + NS_LOG_WARN("Received packet forward report (flowId=" + << flowId << ", packetId=" << packetId << ") but not known to be transmitted."); #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif - return; + return; } - tracked->second.timesForwarded++; - tracked->second.lastSeenTime = Simulator::Now (); + tracked->second.timesForwarded++; + tracked->second.lastSeenTime = Simulator::Now(); - Time delay = (Simulator::Now () - tracked->second.firstSeenTime); - probe->AddPacketStats (flowId, packetSize, delay); + Time delay = (Simulator::Now() - tracked->second.firstSeenTime); + probe->AddPacketStats(flowId, packetSize, delay); #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif } - void -FlowMonitor::ReportLastRx (Ptr probe, uint32_t flowId, uint32_t packetId, uint32_t packetSize) +FlowMonitor::ReportLastRx(Ptr probe, + uint32_t flowId, + uint32_t packetId, + uint32_t packetSize) { - NS_LOG_FUNCTION (this << probe << flowId << packetId << packetSize); - if (!m_enabled) + NS_LOG_FUNCTION(this << probe << flowId << packetId << packetSize); + if (!m_enabled) { - NS_LOG_DEBUG ("FlowMonitor not enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor not enabled; returning"); + return; } #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - TrackedPacketMap::iterator tracked = m_trackedPackets.find (std::make_pair (flowId, packetId)); - if (tracked == m_trackedPackets.end ()) + TrackedPacketMap::iterator tracked = m_trackedPackets.find(std::make_pair(flowId, packetId)); + if (tracked == m_trackedPackets.end()) { - NS_LOG_WARN ("Received packet last-tx report (flowId=" << flowId << ", packetId=" << packetId - << ") but not known to be transmitted."); + NS_LOG_WARN("Received packet last-tx report (flowId=" + << flowId << ", packetId=" << packetId << ") but not known to be transmitted."); #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif - return; + return; } - Time now = Simulator::Now (); - Time delay = (now - tracked->second.firstSeenTime); - probe->AddPacketStats (flowId, packetSize, delay); + Time now = Simulator::Now(); + Time delay = (now - tracked->second.firstSeenTime); + probe->AddPacketStats(flowId, packetSize, delay); - FlowStats &stats = GetStatsForFlow (flowId); - stats.delaySum += delay; - stats.delayHistogram.AddValue (delay.GetSeconds ()); - if (stats.rxPackets > 0 ) + FlowStats& stats = GetStatsForFlow(flowId); + stats.delaySum += delay; + stats.delayHistogram.AddValue(delay.GetSeconds()); + if (stats.rxPackets > 0) { - Time jitter = stats.lastDelay - delay; - if (jitter > Seconds (0)) + Time jitter = stats.lastDelay - delay; + if (jitter > Seconds(0)) { - stats.jitterSum += jitter; - stats.jitterHistogram.AddValue (jitter.GetSeconds ()); + stats.jitterSum += jitter; + stats.jitterHistogram.AddValue(jitter.GetSeconds()); } - else + else { - stats.jitterSum -= jitter; - stats.jitterHistogram.AddValue (-jitter.GetSeconds ()); + stats.jitterSum -= jitter; + stats.jitterHistogram.AddValue(-jitter.GetSeconds()); } } - stats.lastDelay = delay; + stats.lastDelay = delay; - stats.rxBytes += packetSize; - stats.packetSizeHistogram.AddValue ((double) packetSize); - stats.rxPackets++; - if (stats.rxPackets == 1) + stats.rxBytes += packetSize; + stats.packetSizeHistogram.AddValue((double)packetSize); + stats.rxPackets++; + if (stats.rxPackets == 1) { - stats.timeFirstRxPacket = now; + stats.timeFirstRxPacket = now; } - else + else { - // measure possible flow interruptions - Time interArrivalTime = now - stats.timeLastRxPacket; - if (interArrivalTime > m_flowInterruptionsMinTime) + // measure possible flow interruptions + Time interArrivalTime = now - stats.timeLastRxPacket; + if (interArrivalTime > m_flowInterruptionsMinTime) { - stats.flowInterruptionsHistogram.AddValue (interArrivalTime.GetSeconds ()); + stats.flowInterruptionsHistogram.AddValue(interArrivalTime.GetSeconds()); } } - stats.timeLastRxPacket = now; - stats.timesForwarded += tracked->second.timesForwarded; + stats.timeLastRxPacket = now; + stats.timesForwarded += tracked->second.timesForwarded; - NS_LOG_DEBUG ("ReportLastTx: removing tracked packet (flowId=" - << flowId << ", packetId=" << packetId << ")."); + NS_LOG_DEBUG("ReportLastTx: removing tracked packet (flowId=" << flowId << ", packetId=" + << packetId << ")."); - m_trackedPackets.erase (tracked); // we don't need to track this packet anymore + m_trackedPackets.erase(tracked); // we don't need to track this packet anymore #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif } void -FlowMonitor::ReportDrop (Ptr probe, uint32_t flowId, uint32_t packetId, uint32_t packetSize, - uint32_t reasonCode) +FlowMonitor::ReportDrop(Ptr probe, + uint32_t flowId, + uint32_t packetId, + uint32_t packetSize, + uint32_t reasonCode) { - NS_LOG_FUNCTION (this << probe << flowId << packetId << packetSize << reasonCode); - if (!m_enabled) + NS_LOG_FUNCTION(this << probe << flowId << packetId << packetSize << reasonCode); + if (!m_enabled) { - NS_LOG_DEBUG ("FlowMonitor not enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor not enabled; returning"); + return; } #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - probe->AddPacketDropStats (flowId, packetSize, reasonCode); + probe->AddPacketDropStats(flowId, packetSize, reasonCode); - FlowStats &stats = GetStatsForFlow (flowId); - stats.lostPackets++; - if (stats.packetsDropped.size () < reasonCode + 1) + FlowStats& stats = GetStatsForFlow(flowId); + stats.lostPackets++; + if (stats.packetsDropped.size() < reasonCode + 1) { - stats.packetsDropped.resize (reasonCode + 1, 0); - stats.bytesDropped.resize (reasonCode + 1, 0); + stats.packetsDropped.resize(reasonCode + 1, 0); + stats.bytesDropped.resize(reasonCode + 1, 0); } - ++stats.packetsDropped[reasonCode]; - stats.bytesDropped[reasonCode] += packetSize; - NS_LOG_DEBUG ("++stats.packetsDropped[" << reasonCode<< "]; // becomes: " << stats.packetsDropped[reasonCode]); + ++stats.packetsDropped[reasonCode]; + stats.bytesDropped[reasonCode] += packetSize; + NS_LOG_DEBUG("++stats.packetsDropped[" + << reasonCode << "]; // becomes: " << stats.packetsDropped[reasonCode]); - TrackedPacketMap::iterator tracked = m_trackedPackets.find (std::make_pair (flowId, packetId)); - if (tracked != m_trackedPackets.end ()) + TrackedPacketMap::iterator tracked = m_trackedPackets.find(std::make_pair(flowId, packetId)); + if (tracked != m_trackedPackets.end()) { - // we don't need to track this packet anymore - // FIXME: this will not necessarily be true with broadcast/multicast - NS_LOG_DEBUG ("ReportDrop: removing tracked packet (flowId=" - << flowId << ", packetId=" << packetId << ")."); - m_trackedPackets.erase (tracked); + // we don't need to track this packet anymore + // FIXME: this will not necessarily be true with broadcast/multicast + NS_LOG_DEBUG("ReportDrop: removing tracked packet (flowId=" << flowId << ", packetId=" + << packetId << ")."); + m_trackedPackets.erase(tracked); } #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif } const FlowMonitor::FlowStatsContainer& -FlowMonitor::GetFlowStats () const +FlowMonitor::GetFlowStats() const { - return m_flowStats; + return m_flowStats; } - void -FlowMonitor::CheckForLostPackets (Time maxDelay) +FlowMonitor::CheckForLostPackets(Time maxDelay) { - NS_LOG_FUNCTION (this << maxDelay.As (Time::S)); - Time now = Simulator::Now (); + NS_LOG_FUNCTION(this << maxDelay.As(Time::S)); + Time now = Simulator::Now(); - for (TrackedPacketMap::iterator iter = m_trackedPackets.begin (); - iter != m_trackedPackets.end (); ) + for (TrackedPacketMap::iterator iter = m_trackedPackets.begin(); + iter != m_trackedPackets.end();) { - if (now - iter->second.lastSeenTime >= maxDelay) + if (now - iter->second.lastSeenTime >= maxDelay) { - // packet is considered lost, add it to the loss statistics - FlowStatsContainerI flow = m_flowStats.find (iter->first.first); - NS_ASSERT (flow != m_flowStats.end ()); - flow->second.lostPackets++; + // packet is considered lost, add it to the loss statistics + FlowStatsContainerI flow = m_flowStats.find(iter->first.first); + NS_ASSERT(flow != m_flowStats.end()); + flow->second.lostPackets++; - // we won't track it anymore - m_trackedPackets.erase (iter++); + // we won't track it anymore + m_trackedPackets.erase(iter++); } - else + else { - iter++; + iter++; } } } void -FlowMonitor::CheckForLostPackets () +FlowMonitor::CheckForLostPackets() { - CheckForLostPackets (m_maxPerHopDelay); + CheckForLostPackets(m_maxPerHopDelay); } void -FlowMonitor::PeriodicCheckForLostPackets () +FlowMonitor::PeriodicCheckForLostPackets() { - CheckForLostPackets (); - Simulator::Schedule (PERIODIC_CHECK_INTERVAL, &FlowMonitor::PeriodicCheckForLostPackets, this); + CheckForLostPackets(); + Simulator::Schedule(PERIODIC_CHECK_INTERVAL, &FlowMonitor::PeriodicCheckForLostPackets, this); } void -FlowMonitor::NotifyConstructionCompleted () +FlowMonitor::NotifyConstructionCompleted() { - Object::NotifyConstructionCompleted (); - Simulator::Schedule (PERIODIC_CHECK_INTERVAL, &FlowMonitor::PeriodicCheckForLostPackets, this); + Object::NotifyConstructionCompleted(); + Simulator::Schedule(PERIODIC_CHECK_INTERVAL, &FlowMonitor::PeriodicCheckForLostPackets, this); } void -FlowMonitor::AddProbe (Ptr probe) +FlowMonitor::AddProbe(Ptr probe) { - m_flowProbes.push_back (probe); + m_flowProbes.push_back(probe); } - const FlowMonitor::FlowProbeContainer& -FlowMonitor::GetAllProbes () const +FlowMonitor::GetAllProbes() const { - return m_flowProbes; + return m_flowProbes; } - void -FlowMonitor::Start (const Time &time) +FlowMonitor::Start(const Time& time) { - NS_LOG_FUNCTION (this << time.As (Time::S)); - if (m_enabled) + NS_LOG_FUNCTION(this << time.As(Time::S)); + if (m_enabled) { - NS_LOG_DEBUG ("FlowMonitor already enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor already enabled; returning"); + return; } - Simulator::Cancel (m_startEvent); - NS_LOG_DEBUG ("Scheduling start at " << time.As (Time::S)); - m_startEvent = Simulator::Schedule (time, &FlowMonitor::StartRightNow, this); + Simulator::Cancel(m_startEvent); + NS_LOG_DEBUG("Scheduling start at " << time.As(Time::S)); + m_startEvent = Simulator::Schedule(time, &FlowMonitor::StartRightNow, this); } void -FlowMonitor::Stop (const Time &time) +FlowMonitor::Stop(const Time& time) { - NS_LOG_FUNCTION (this << time.As (Time::S)); - Simulator::Cancel (m_stopEvent); - NS_LOG_DEBUG ("Scheduling stop at " << time.As (Time::S)); - m_stopEvent = Simulator::Schedule (time, &FlowMonitor::StopRightNow, this); + NS_LOG_FUNCTION(this << time.As(Time::S)); + Simulator::Cancel(m_stopEvent); + NS_LOG_DEBUG("Scheduling stop at " << time.As(Time::S)); + m_stopEvent = Simulator::Schedule(time, &FlowMonitor::StopRightNow, this); } - void -FlowMonitor::StartRightNow () +FlowMonitor::StartRightNow() { - NS_LOG_FUNCTION (this); - if (m_enabled) + NS_LOG_FUNCTION(this); + if (m_enabled) { - NS_LOG_DEBUG ("FlowMonitor already enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor already enabled; returning"); + return; } - m_enabled = true; + m_enabled = true; } - void -FlowMonitor::StopRightNow () +FlowMonitor::StopRightNow() { - NS_LOG_FUNCTION (this); - if (!m_enabled) + NS_LOG_FUNCTION(this); + if (!m_enabled) { - NS_LOG_DEBUG ("FlowMonitor not enabled; returning"); - return; + NS_LOG_DEBUG("FlowMonitor not enabled; returning"); + return; } - m_enabled = false; - CheckForLostPackets (); + m_enabled = false; + CheckForLostPackets(); } void -FlowMonitor::AddFlowClassifier (Ptr classifier) +FlowMonitor::AddFlowClassifier(Ptr classifier) { - m_classifiers.push_back (classifier); + m_classifiers.push_back(classifier); } void -FlowMonitor::SerializeToXmlStream (std::ostream &os, uint16_t indent, bool enableHistograms, bool enableProbes) +FlowMonitor::SerializeToXmlStream(std::ostream& os, + uint16_t indent, + bool enableHistograms, + bool enableProbes) { - NS_LOG_FUNCTION (this << indent << enableHistograms << enableProbes); - CheckForLostPackets (); + NS_LOG_FUNCTION(this << indent << enableHistograms << enableProbes); + CheckForLostPackets(); - os << std::string ( indent, ' ' ) << "\n"; - indent += 2; - os << std::string ( indent, ' ' ) << "\n"; - indent += 2; - for (FlowStatsContainerCI flowI = m_flowStats.begin (); - flowI != m_flowStats.end (); flowI++) + os << std::string(indent, ' ') << "\n"; + indent += 2; + os << std::string(indent, ' ') << "\n"; + indent += 2; + for (FlowStatsContainerCI flowI = m_flowStats.begin(); flowI != m_flowStats.end(); flowI++) { - os << std::string ( indent, ' ' ); -#define ATTRIB(name) << " " # name "=\"" << flowI->second.name << "\"" -#define ATTRIB_TIME(name) << " " #name "=\"" << flowI->second.name.As (Time::NS) << "\"" - os << "first << "\"" - ATTRIB_TIME (timeFirstTxPacket) - ATTRIB_TIME (timeFirstRxPacket) - ATTRIB_TIME (timeLastTxPacket) - ATTRIB_TIME (timeLastRxPacket) - ATTRIB_TIME (delaySum) - ATTRIB_TIME (jitterSum) - ATTRIB_TIME (lastDelay) - ATTRIB (txBytes) - ATTRIB (rxBytes) - ATTRIB (txPackets) - ATTRIB (rxPackets) - ATTRIB (lostPackets) - ATTRIB (timesForwarded) - << ">\n"; + os << std::string(indent, ' '); +#define ATTRIB(name) << " " #name "=\"" << flowI->second.name << "\"" +#define ATTRIB_TIME(name) << " " #name "=\"" << flowI->second.name.As(Time::NS) << "\"" + os << "first + << "\"" ATTRIB_TIME(timeFirstTxPacket) ATTRIB_TIME(timeFirstRxPacket) + ATTRIB_TIME(timeLastTxPacket) ATTRIB_TIME(timeLastRxPacket) ATTRIB_TIME(delaySum) + ATTRIB_TIME(jitterSum) ATTRIB_TIME(lastDelay) ATTRIB(txBytes) ATTRIB(rxBytes) + ATTRIB(txPackets) ATTRIB(rxPackets) ATTRIB(lostPackets) + ATTRIB(timesForwarded) + << ">\n"; #undef ATTRIB_TIME #undef ATTRIB - indent += 2; - for (uint32_t reasonCode = 0; reasonCode < flowI->second.packetsDropped.size (); reasonCode++) + indent += 2; + for (uint32_t reasonCode = 0; reasonCode < flowI->second.packetsDropped.size(); + reasonCode++) { - os << std::string ( indent, ' ' ); - os << "second.packetsDropped[reasonCode] - << "\" />\n"; + os << std::string(indent, ' '); + os << "second.packetsDropped[reasonCode] << "\" />\n"; } - for (uint32_t reasonCode = 0; reasonCode < flowI->second.bytesDropped.size (); reasonCode++) + for (uint32_t reasonCode = 0; reasonCode < flowI->second.bytesDropped.size(); reasonCode++) { - os << std::string ( indent, ' ' ); - os << "second.bytesDropped[reasonCode] - << "\" />\n"; + os << std::string(indent, ' '); + os << "second.bytesDropped[reasonCode] << "\" />\n"; } - if (enableHistograms) + if (enableHistograms) { - flowI->second.delayHistogram.SerializeToXmlStream (os, indent, "delayHistogram"); - flowI->second.jitterHistogram.SerializeToXmlStream (os, indent, "jitterHistogram"); - flowI->second.packetSizeHistogram.SerializeToXmlStream (os, indent, "packetSizeHistogram"); - flowI->second.flowInterruptionsHistogram.SerializeToXmlStream (os, indent, "flowInterruptionsHistogram"); + flowI->second.delayHistogram.SerializeToXmlStream(os, indent, "delayHistogram"); + flowI->second.jitterHistogram.SerializeToXmlStream(os, indent, "jitterHistogram"); + flowI->second.packetSizeHistogram.SerializeToXmlStream(os, + indent, + "packetSizeHistogram"); + flowI->second.flowInterruptionsHistogram.SerializeToXmlStream( + os, + indent, + "flowInterruptionsHistogram"); } - indent -= 2; + indent -= 2; - os << std::string ( indent, ' ' ) << "\n"; + os << std::string(indent, ' ') << "\n"; } - indent -= 2; - os << std::string ( indent, ' ' ) << "\n"; + indent -= 2; + os << std::string(indent, ' ') << "\n"; - for (std::list >::iterator iter = m_classifiers.begin (); - iter != m_classifiers.end (); - iter ++) + for (std::list>::iterator iter = m_classifiers.begin(); + iter != m_classifiers.end(); + iter++) { - (*iter)->SerializeToXmlStream (os, indent); + (*iter)->SerializeToXmlStream(os, indent); } - if (enableProbes) + if (enableProbes) { - os << std::string ( indent, ' ' ) << "\n"; - indent += 2; - for (uint32_t i = 0; i < m_flowProbes.size (); i++) + os << std::string(indent, ' ') << "\n"; + indent += 2; + for (uint32_t i = 0; i < m_flowProbes.size(); i++) { - m_flowProbes[i]->SerializeToXmlStream (os, indent, i); + m_flowProbes[i]->SerializeToXmlStream(os, indent, i); } - indent -= 2; - os << std::string ( indent, ' ' ) << "\n"; + indent -= 2; + os << std::string(indent, ' ') << "\n"; } - indent -= 2; - os << std::string ( indent, ' ' ) << "\n"; + indent -= 2; + os << std::string(indent, ' ') << "\n"; } - std::string -FlowMonitor::SerializeToXmlString (uint16_t indent, bool enableHistograms, bool enableProbes) +FlowMonitor::SerializeToXmlString(uint16_t indent, bool enableHistograms, bool enableProbes) { - NS_LOG_FUNCTION (this << indent << enableHistograms << enableProbes); - std::ostringstream os; - SerializeToXmlStream (os, indent, enableHistograms, enableProbes); - return os.str (); + NS_LOG_FUNCTION(this << indent << enableHistograms << enableProbes); + std::ostringstream os; + SerializeToXmlStream(os, indent, enableHistograms, enableProbes); + return os.str(); } - void -FlowMonitor::SerializeToXmlFile (std::string fileName, bool enableHistograms, bool enableProbes) +FlowMonitor::SerializeToXmlFile(std::string fileName, bool enableHistograms, bool enableProbes) { - NS_LOG_FUNCTION (this << fileName << enableHistograms << enableProbes); - std::ofstream os (fileName.c_str (), std::ios::out|std::ios::binary); - os << "\n"; - SerializeToXmlStream (os, 0, enableHistograms, enableProbes); - os.close (); + NS_LOG_FUNCTION(this << fileName << enableHistograms << enableProbes); + std::ofstream os(fileName.c_str(), std::ios::out | std::ios::binary); + os << "\n"; + SerializeToXmlStream(os, 0, enableHistograms, enableProbes); + os.close(); } - } // namespace ns3 - diff --git a/src/flow-monitor/model/flow-monitor.h b/src/flow-monitor/model/flow-monitor.h index 369209b20..8222f173c 100644 --- a/src/flow-monitor/model/flow-monitor.h +++ b/src/flow-monitor/model/flow-monitor.h @@ -21,19 +21,20 @@ #ifndef FLOW_MONITOR_H #define FLOW_MONITOR_H -#include -#include -#include - -#include "ns3/ptr.h" -#include "ns3/object.h" -#include "ns3/flow-probe.h" +#include "ns3/event-id.h" #include "ns3/flow-classifier.h" +#include "ns3/flow-probe.h" #include "ns3/histogram.h" #include "ns3/nstime.h" -#include "ns3/event-id.h" +#include "ns3/object.h" +#include "ns3/ptr.h" -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ /** * \defgroup flow-monitor Flow Monitor @@ -50,266 +51,276 @@ namespace ns3 { */ class FlowMonitor : public Object { -public: + public: + /// \brief Structure that represents the measured metrics of an individual packet flow + struct FlowStats + { + /// Contains the absolute time when the first packet in the flow + /// was transmitted, i.e. the time when the flow transmission + /// starts + Time timeFirstTxPacket; - /// \brief Structure that represents the measured metrics of an individual packet flow - struct FlowStats - { - /// Contains the absolute time when the first packet in the flow - /// was transmitted, i.e. the time when the flow transmission - /// starts - Time timeFirstTxPacket; + /// Contains the absolute time when the first packet in the flow + /// was received by an end node, i.e. the time when the flow + /// reception starts + Time timeFirstRxPacket; - /// Contains the absolute time when the first packet in the flow - /// was received by an end node, i.e. the time when the flow - /// reception starts - Time timeFirstRxPacket; + /// Contains the absolute time when the last packet in the flow + /// was transmitted, i.e. the time when the flow transmission + /// ends + Time timeLastTxPacket; - /// Contains the absolute time when the last packet in the flow - /// was transmitted, i.e. the time when the flow transmission - /// ends - Time timeLastTxPacket; + /// Contains the absolute time when the last packet in the flow + /// was received, i.e. the time when the flow reception ends + Time timeLastRxPacket; - /// Contains the absolute time when the last packet in the flow - /// was received, i.e. the time when the flow reception ends - Time timeLastRxPacket; + /// Contains the sum of all end-to-end delays for all received + /// packets of the flow. + Time delaySum; // delayCount == rxPackets - /// Contains the sum of all end-to-end delays for all received - /// packets of the flow. - Time delaySum; // delayCount == rxPackets + /// Contains the sum of all end-to-end delay jitter (delay + /// variation) values for all received packets of the flow. Here + /// we define _jitter_ of a packet as the delay variation + /// relatively to the last packet of the stream, + /// i.e. \f$Jitter\left\{P_N\right\} = \left|Delay\left\{P_N\right\} - + /// Delay\left\{P_{N-1}\right\}\right|\f$. This definition is in accordance with the + /// Type-P-One-way-ipdv as defined in IETF \RFC{3393}. + Time jitterSum; // jitterCount == rxPackets - 1 - /// Contains the sum of all end-to-end delay jitter (delay - /// variation) values for all received packets of the flow. Here - /// we define _jitter_ of a packet as the delay variation - /// relatively to the last packet of the stream, - /// i.e. \f$Jitter\left\{P_N\right\} = \left|Delay\left\{P_N\right\} - Delay\left\{P_{N-1}\right\}\right|\f$. - /// This definition is in accordance with the Type-P-One-way-ipdv - /// as defined in IETF \RFC{3393}. - Time jitterSum; // jitterCount == rxPackets - 1 + /// Contains the last measured delay of a packet + /// It is stored to measure the packet's Jitter + Time lastDelay; - /// Contains the last measured delay of a packet - /// It is stored to measure the packet's Jitter - Time lastDelay; + /// Total number of transmitted bytes for the flow + uint64_t txBytes; + /// Total number of received bytes for the flow + uint64_t rxBytes; + /// Total number of transmitted packets for the flow + uint32_t txPackets; + /// Total number of received packets for the flow + uint32_t rxPackets; - /// Total number of transmitted bytes for the flow - uint64_t txBytes; - /// Total number of received bytes for the flow - uint64_t rxBytes; - /// Total number of transmitted packets for the flow - uint32_t txPackets; - /// Total number of received packets for the flow - uint32_t rxPackets; + /// Total number of packets that are assumed to be lost, + /// i.e. those that were transmitted but have not been reportedly + /// received or forwarded for a long time. By default, packets + /// missing for a period of over 10 seconds are assumed to be + /// lost, although this value can be easily configured in runtime + uint32_t lostPackets; - /// Total number of packets that are assumed to be lost, - /// i.e. those that were transmitted but have not been reportedly - /// received or forwarded for a long time. By default, packets - /// missing for a period of over 10 seconds are assumed to be - /// lost, although this value can be easily configured in runtime - uint32_t lostPackets; + /// Contains the number of times a packet has been reportedly + /// forwarded, summed for all received packets in the flow + uint32_t timesForwarded; - /// Contains the number of times a packet has been reportedly - /// forwarded, summed for all received packets in the flow - uint32_t timesForwarded; + /// Histogram of the packet delays + Histogram delayHistogram; + /// Histogram of the packet jitters + Histogram jitterHistogram; + /// Histogram of the packet sizes + Histogram packetSizeHistogram; - /// Histogram of the packet delays - Histogram delayHistogram; - /// Histogram of the packet jitters - Histogram jitterHistogram; - /// Histogram of the packet sizes - Histogram packetSizeHistogram; + /// This attribute also tracks the number of lost packets and + /// bytes, but discriminates the losses by a _reason code_. This + /// reason code is usually an enumeration defined by the concrete + /// FlowProbe class, and for each reason code there may be a + /// vector entry indexed by that code and whose value is the + /// number of packets or bytes lost due to this reason. For + /// instance, in the Ipv4FlowProbe case the following reasons are + /// currently defined: DROP_NO_ROUTE (no IPv4 route found for a + /// packet), DROP_TTL_EXPIRE (a packet was dropped due to an IPv4 + /// TTL field decremented and reaching zero), and + /// DROP_BAD_CHECKSUM (a packet had bad IPv4 header checksum and + /// had to be dropped). + std::vector + packetsDropped; // packetsDropped[reasonCode] => number of dropped packets - /// This attribute also tracks the number of lost packets and - /// bytes, but discriminates the losses by a _reason code_. This - /// reason code is usually an enumeration defined by the concrete - /// FlowProbe class, and for each reason code there may be a - /// vector entry indexed by that code and whose value is the - /// number of packets or bytes lost due to this reason. For - /// instance, in the Ipv4FlowProbe case the following reasons are - /// currently defined: DROP_NO_ROUTE (no IPv4 route found for a - /// packet), DROP_TTL_EXPIRE (a packet was dropped due to an IPv4 - /// TTL field decremented and reaching zero), and - /// DROP_BAD_CHECKSUM (a packet had bad IPv4 header checksum and - /// had to be dropped). - std::vector packetsDropped; // packetsDropped[reasonCode] => number of dropped packets + /// This attribute also tracks the number of lost bytes. See also + /// comment in attribute packetsDropped. + std::vector bytesDropped; // bytesDropped[reasonCode] => number of dropped bytes + Histogram flowInterruptionsHistogram; //!< histogram of durations of flow interruptions + }; - /// This attribute also tracks the number of lost bytes. See also - /// comment in attribute packetsDropped. - std::vector bytesDropped; // bytesDropped[reasonCode] => number of dropped bytes - Histogram flowInterruptionsHistogram; //!< histogram of durations of flow interruptions - }; + // --- basic methods --- + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(); + TypeId GetInstanceTypeId() const override; + FlowMonitor(); - // --- basic methods --- - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (); - TypeId GetInstanceTypeId () const override; - FlowMonitor (); + /// Add a FlowClassifier to be used by the flow monitor. + /// \param classifier the FlowClassifier + void AddFlowClassifier(Ptr classifier); - /// Add a FlowClassifier to be used by the flow monitor. - /// \param classifier the FlowClassifier - void AddFlowClassifier (Ptr classifier); + /// Set the time, counting from the current time, from which to start monitoring flows. + /// This method overwrites any previous calls to Start() + /// \param time delta time to start + void Start(const Time& time); + /// Set the time, counting from the current time, from which to stop monitoring flows. + /// This method overwrites any previous calls to Stop() + /// \param time delta time to stop + void Stop(const Time& time); + /// Begin monitoring flows *right now* + void StartRightNow(); + /// End monitoring flows *right now* + void StopRightNow(); - /// Set the time, counting from the current time, from which to start monitoring flows. - /// This method overwrites any previous calls to Start() - /// \param time delta time to start - void Start (const Time &time); - /// Set the time, counting from the current time, from which to stop monitoring flows. - /// This method overwrites any previous calls to Stop() - /// \param time delta time to stop - void Stop (const Time &time); - /// Begin monitoring flows *right now* - void StartRightNow (); - /// End monitoring flows *right now* - void StopRightNow (); + // --- methods to be used by the FlowMonitorProbe's only --- + /// Register a new FlowProbe that will begin monitoring and report + /// events to this monitor. This method is normally only used by + /// FlowProbe implementations. + /// \param probe the probe to add + void AddProbe(Ptr probe); - // --- methods to be used by the FlowMonitorProbe's only --- - /// Register a new FlowProbe that will begin monitoring and report - /// events to this monitor. This method is normally only used by - /// FlowProbe implementations. - /// \param probe the probe to add - void AddProbe (Ptr probe); + /// FlowProbe implementations are supposed to call this method to + /// report that a new packet was transmitted (but keep in mind the + /// distinction between a new packet entering the system and a + /// packet that is already known and is only being forwarded). + /// \param probe the reporting probe + /// \param flowId flow identification + /// \param packetId Packet ID + /// \param packetSize packet size + void ReportFirstTx(Ptr probe, + FlowId flowId, + FlowPacketId packetId, + uint32_t packetSize); + /// FlowProbe implementations are supposed to call this method to + /// report that a known packet is being forwarded. + /// \param probe the reporting probe + /// \param flowId flow identification + /// \param packetId Packet ID + /// \param packetSize packet size + void ReportForwarding(Ptr probe, + FlowId flowId, + FlowPacketId packetId, + uint32_t packetSize); + /// FlowProbe implementations are supposed to call this method to + /// report that a known packet is being received. + /// \param probe the reporting probe + /// \param flowId flow identification + /// \param packetId Packet ID + /// \param packetSize packet size + void ReportLastRx(Ptr probe, + FlowId flowId, + FlowPacketId packetId, + uint32_t packetSize); + /// FlowProbe implementations are supposed to call this method to + /// report that a known packet is being dropped due to some reason. + /// \param probe the reporting probe + /// \param flowId flow identification + /// \param packetId Packet ID + /// \param packetSize packet size + /// \param reasonCode drop reason code + void ReportDrop(Ptr probe, + FlowId flowId, + FlowPacketId packetId, + uint32_t packetSize, + uint32_t reasonCode); - /// FlowProbe implementations are supposed to call this method to - /// report that a new packet was transmitted (but keep in mind the - /// distinction between a new packet entering the system and a - /// packet that is already known and is only being forwarded). - /// \param probe the reporting probe - /// \param flowId flow identification - /// \param packetId Packet ID - /// \param packetSize packet size - void ReportFirstTx (Ptr probe, FlowId flowId, FlowPacketId packetId, uint32_t packetSize); - /// FlowProbe implementations are supposed to call this method to - /// report that a known packet is being forwarded. - /// \param probe the reporting probe - /// \param flowId flow identification - /// \param packetId Packet ID - /// \param packetSize packet size - void ReportForwarding (Ptr probe, FlowId flowId, FlowPacketId packetId, uint32_t packetSize); - /// FlowProbe implementations are supposed to call this method to - /// report that a known packet is being received. - /// \param probe the reporting probe - /// \param flowId flow identification - /// \param packetId Packet ID - /// \param packetSize packet size - void ReportLastRx (Ptr probe, FlowId flowId, FlowPacketId packetId, uint32_t packetSize); - /// FlowProbe implementations are supposed to call this method to - /// report that a known packet is being dropped due to some reason. - /// \param probe the reporting probe - /// \param flowId flow identification - /// \param packetId Packet ID - /// \param packetSize packet size - /// \param reasonCode drop reason code - void ReportDrop (Ptr probe, FlowId flowId, FlowPacketId packetId, - uint32_t packetSize, uint32_t reasonCode); + /// Check right now for packets that appear to be lost + void CheckForLostPackets(); - /// Check right now for packets that appear to be lost - void CheckForLostPackets (); + /// Check right now for packets that appear to be lost, considering + /// packets as lost if not seen in the network for a time larger + /// than maxDelay + /// \param maxDelay the max delay for a packet + void CheckForLostPackets(Time maxDelay); - /// Check right now for packets that appear to be lost, considering - /// packets as lost if not seen in the network for a time larger - /// than maxDelay - /// \param maxDelay the max delay for a packet - void CheckForLostPackets (Time maxDelay); + // --- methods to get the results --- - // --- methods to get the results --- + /// Container: FlowId, FlowStats + typedef std::map FlowStatsContainer; + /// Container Iterator: FlowId, FlowStats + typedef std::map::iterator FlowStatsContainerI; + /// Container Const Iterator: FlowId, FlowStats + typedef std::map::const_iterator FlowStatsContainerCI; + /// Container: FlowProbe + typedef std::vector> FlowProbeContainer; + /// Container Iterator: FlowProbe + typedef std::vector>::iterator FlowProbeContainerI; + /// Container Const Iterator: FlowProbe + typedef std::vector>::const_iterator FlowProbeContainerCI; - /// Container: FlowId, FlowStats - typedef std::map FlowStatsContainer; - /// Container Iterator: FlowId, FlowStats - typedef std::map::iterator FlowStatsContainerI; - /// Container Const Iterator: FlowId, FlowStats - typedef std::map::const_iterator FlowStatsContainerCI; - /// Container: FlowProbe - typedef std::vector< Ptr > FlowProbeContainer; - /// Container Iterator: FlowProbe - typedef std::vector< Ptr >::iterator FlowProbeContainerI; - /// Container Const Iterator: FlowProbe - typedef std::vector< Ptr >::const_iterator FlowProbeContainerCI; + /// Retrieve all collected the flow statistics. Note, if the + /// FlowMonitor has not stopped monitoring yet, you should call + /// CheckForLostPackets() to make sure all possibly lost packets are + /// accounted for. + /// \returns the flows statistics + const FlowStatsContainer& GetFlowStats() const; - /// Retrieve all collected the flow statistics. Note, if the - /// FlowMonitor has not stopped monitoring yet, you should call - /// CheckForLostPackets() to make sure all possibly lost packets are - /// accounted for. - /// \returns the flows statistics - const FlowStatsContainer& GetFlowStats () const; + /// Get a list of all FlowProbe's associated with this FlowMonitor + /// \returns a list of all the probes + const FlowProbeContainer& GetAllProbes() const; - /// Get a list of all FlowProbe's associated with this FlowMonitor - /// \returns a list of all the probes - const FlowProbeContainer& GetAllProbes () const; + /// Serializes the results to an std::ostream in XML format + /// \param os the output stream + /// \param indent number of spaces to use as base indentation level + /// \param enableHistograms if true, include also the histograms in the output + /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output + void SerializeToXmlStream(std::ostream& os, + uint16_t indent, + bool enableHistograms, + bool enableProbes); - /// Serializes the results to an std::ostream in XML format - /// \param os the output stream - /// \param indent number of spaces to use as base indentation level - /// \param enableHistograms if true, include also the histograms in the output - /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output - void SerializeToXmlStream (std::ostream &os, uint16_t indent, bool enableHistograms, bool enableProbes); + /// Same as SerializeToXmlStream, but returns the output as a std::string + /// \param indent number of spaces to use as base indentation level + /// \param enableHistograms if true, include also the histograms in the output + /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output + /// \return the XML output as string + std::string SerializeToXmlString(uint16_t indent, bool enableHistograms, bool enableProbes); - /// Same as SerializeToXmlStream, but returns the output as a std::string - /// \param indent number of spaces to use as base indentation level - /// \param enableHistograms if true, include also the histograms in the output - /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output - /// \return the XML output as string - std::string SerializeToXmlString (uint16_t indent, bool enableHistograms, bool enableProbes); + /// Same as SerializeToXmlStream, but writes to a file instead + /// \param fileName name or path of the output file that will be created + /// \param enableHistograms if true, include also the histograms in the output + /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output + void SerializeToXmlFile(std::string fileName, bool enableHistograms, bool enableProbes); - /// Same as SerializeToXmlStream, but writes to a file instead - /// \param fileName name or path of the output file that will be created - /// \param enableHistograms if true, include also the histograms in the output - /// \param enableProbes if true, include also the per-probe/flow pair statistics in the output - void SerializeToXmlFile (std::string fileName, bool enableHistograms, bool enableProbes); + protected: + void NotifyConstructionCompleted() override; + void DoDispose() override; + private: + /// Structure to represent a single tracked packet data + struct TrackedPacket + { + Time firstSeenTime; //!< absolute time when the packet was first seen by a probe + Time lastSeenTime; //!< absolute time when the packet was last seen by a probe + uint32_t timesForwarded; //!< number of times the packet was reportedly forwarded + }; -protected: + /// FlowId --> FlowStats + FlowStatsContainer m_flowStats; - void NotifyConstructionCompleted () override; - void DoDispose () override; + /// (FlowId,PacketId) --> TrackedPacket + typedef std::map, TrackedPacket> TrackedPacketMap; + TrackedPacketMap m_trackedPackets; //!< Tracked packets + Time m_maxPerHopDelay; //!< Minimum per-hop delay + FlowProbeContainer m_flowProbes; //!< all the FlowProbes -private: + // note: this is needed only for serialization + std::list> m_classifiers; //!< the FlowClassifiers - /// Structure to represent a single tracked packet data - struct TrackedPacket - { - Time firstSeenTime; //!< absolute time when the packet was first seen by a probe - Time lastSeenTime; //!< absolute time when the packet was last seen by a probe - uint32_t timesForwarded; //!< number of times the packet was reportedly forwarded - }; - - /// FlowId --> FlowStats - FlowStatsContainer m_flowStats; - - /// (FlowId,PacketId) --> TrackedPacket - typedef std::map< std::pair, TrackedPacket> TrackedPacketMap; - TrackedPacketMap m_trackedPackets; //!< Tracked packets - Time m_maxPerHopDelay; //!< Minimum per-hop delay - FlowProbeContainer m_flowProbes; //!< all the FlowProbes - - // note: this is needed only for serialization - std::list > m_classifiers; //!< the FlowClassifiers - - EventId m_startEvent; //!< Start event - EventId m_stopEvent; //!< Stop event - bool m_enabled; //!< FlowMon is enabled - double m_delayBinWidth; //!< Delay bin width (for histograms) - double m_jitterBinWidth; //!< Jitter bin width (for histograms) - double m_packetSizeBinWidth; //!< packet size bin width (for histograms) - double m_flowInterruptionsBinWidth; //!< Flow interruptions bin width (for histograms) - Time m_flowInterruptionsMinTime; //!< Flow interruptions minimum time + EventId m_startEvent; //!< Start event + EventId m_stopEvent; //!< Stop event + bool m_enabled; //!< FlowMon is enabled + double m_delayBinWidth; //!< Delay bin width (for histograms) + double m_jitterBinWidth; //!< Jitter bin width (for histograms) + double m_packetSizeBinWidth; //!< packet size bin width (for histograms) + double m_flowInterruptionsBinWidth; //!< Flow interruptions bin width (for histograms) + Time m_flowInterruptionsMinTime; //!< Flow interruptions minimum time #ifdef NS3_MTP - std::atomic m_lock; + std::atomic m_lock; #endif - /// Get the stats for a given flow - /// \param flowId the Flow identification - /// \returns the stats of the flow - FlowStats& GetStatsForFlow (FlowId flowId); + /// Get the stats for a given flow + /// \param flowId the Flow identification + /// \returns the stats of the flow + FlowStats& GetStatsForFlow(FlowId flowId); - /// Periodic function to check for lost packets and prune statistics - void PeriodicCheckForLostPackets (); + /// Periodic function to check for lost packets and prune statistics + void PeriodicCheckForLostPackets(); }; - } // namespace ns3 #endif /* FLOW_MONITOR_H */ - diff --git a/src/flow-monitor/model/ipv4-flow-classifier.cc b/src/flow-monitor/model/ipv4-flow-classifier.cc index 67b8192d6..6fc6c893b 100644 --- a/src/flow-monitor/model/ipv4-flow-classifier.cc +++ b/src/flow-monitor/model/ipv4-flow-classifier.cc @@ -18,260 +18,263 @@ // Author: Gustavo J. A. M. Carneiro // -#include "ns3/packet.h" - #include "ipv4-flow-classifier.h" -#include "ns3/udp-header.h" + +#include "ns3/packet.h" #include "ns3/tcp-header.h" +#include "ns3/udp-header.h" + #include -namespace ns3 { +namespace ns3 +{ /* see http://www.iana.org/assignments/protocol-numbers */ const uint8_t TCP_PROT_NUMBER = 6; //!< TCP Protocol number const uint8_t UDP_PROT_NUMBER = 17; //!< UDP Protocol number - - -bool operator < (const Ipv4FlowClassifier::FiveTuple &t1, - const Ipv4FlowClassifier::FiveTuple &t2) +bool +operator<(const Ipv4FlowClassifier::FiveTuple& t1, const Ipv4FlowClassifier::FiveTuple& t2) { - if (t1.sourceAddress < t2.sourceAddress) + if (t1.sourceAddress < t2.sourceAddress) { - return true; + return true; } - if (t1.sourceAddress != t2.sourceAddress) + if (t1.sourceAddress != t2.sourceAddress) { - return false; + return false; } - if (t1.destinationAddress < t2.destinationAddress) + if (t1.destinationAddress < t2.destinationAddress) { - return true; + return true; } - if (t1.destinationAddress != t2.destinationAddress) + if (t1.destinationAddress != t2.destinationAddress) { - return false; + return false; } - if (t1.protocol < t2.protocol) + if (t1.protocol < t2.protocol) { - return true; + return true; } - if (t1.protocol != t2.protocol) + if (t1.protocol != t2.protocol) { - return false; + return false; } - if (t1.sourcePort < t2.sourcePort) + if (t1.sourcePort < t2.sourcePort) { - return true; + return true; } - if (t1.sourcePort != t2.sourcePort) + if (t1.sourcePort != t2.sourcePort) { - return false; + return false; } - if (t1.destinationPort < t2.destinationPort) + if (t1.destinationPort < t2.destinationPort) { - return true; + return true; } - if (t1.destinationPort != t2.destinationPort) + if (t1.destinationPort != t2.destinationPort) { - return false; + return false; } - return false; + return false; } -bool operator == (const Ipv4FlowClassifier::FiveTuple &t1, - const Ipv4FlowClassifier::FiveTuple &t2) +bool +operator==(const Ipv4FlowClassifier::FiveTuple& t1, const Ipv4FlowClassifier::FiveTuple& t2) { - return (t1.sourceAddress == t2.sourceAddress && - t1.destinationAddress == t2.destinationAddress && - t1.protocol == t2.protocol && - t1.sourcePort == t2.sourcePort && - t1.destinationPort == t2.destinationPort); + return (t1.sourceAddress == t2.sourceAddress && + t1.destinationAddress == t2.destinationAddress && t1.protocol == t2.protocol && + t1.sourcePort == t2.sourcePort && t1.destinationPort == t2.destinationPort); } - - -Ipv4FlowClassifier::Ipv4FlowClassifier () +Ipv4FlowClassifier::Ipv4FlowClassifier() { #ifdef NS3_MTP - m_lock.store (false, std::memory_order_relaxed); + m_lock.store(false, std::memory_order_relaxed); #endif } bool -Ipv4FlowClassifier::Classify (const Ipv4Header &ipHeader, Ptr ipPayload, - uint32_t *out_flowId, uint32_t *out_packetId) +Ipv4FlowClassifier::Classify(const Ipv4Header& ipHeader, + Ptr ipPayload, + uint32_t* out_flowId, + uint32_t* out_packetId) { - if (ipHeader.GetFragmentOffset () > 0 ) + if (ipHeader.GetFragmentOffset() > 0) { - // Ignore fragments: they don't carry a valid L4 header - return false; + // Ignore fragments: they don't carry a valid L4 header + return false; } - FiveTuple tuple; - tuple.sourceAddress = ipHeader.GetSource (); - tuple.destinationAddress = ipHeader.GetDestination (); - tuple.protocol = ipHeader.GetProtocol (); + FiveTuple tuple; + tuple.sourceAddress = ipHeader.GetSource(); + tuple.destinationAddress = ipHeader.GetDestination(); + tuple.protocol = ipHeader.GetProtocol(); - if ((tuple.protocol != UDP_PROT_NUMBER) && (tuple.protocol != TCP_PROT_NUMBER)) + if ((tuple.protocol != UDP_PROT_NUMBER) && (tuple.protocol != TCP_PROT_NUMBER)) { - return false; + return false; } - if (ipPayload->GetSize () < 4) + if (ipPayload->GetSize() < 4) { - // the packet doesn't carry enough bytes - return false; + // the packet doesn't carry enough bytes + return false; } - // we rely on the fact that for both TCP and UDP the ports are - // carried in the first 4 octects. - // This allows to read the ports even on fragmented packets - // not carrying a full TCP or UDP header. + // we rely on the fact that for both TCP and UDP the ports are + // carried in the first 4 octects. + // This allows to read the ports even on fragmented packets + // not carrying a full TCP or UDP header. - uint8_t data[4]; - ipPayload->CopyData (data, 4); + uint8_t data[4]; + ipPayload->CopyData(data, 4); - uint16_t srcPort = 0; - srcPort |= data[0]; - srcPort <<= 8; - srcPort |= data[1]; + uint16_t srcPort = 0; + srcPort |= data[0]; + srcPort <<= 8; + srcPort |= data[1]; - uint16_t dstPort = 0; - dstPort |= data[2]; - dstPort <<= 8; - dstPort |= data[3]; + uint16_t dstPort = 0; + dstPort |= data[2]; + dstPort <<= 8; + dstPort |= data[3]; - tuple.sourcePort = srcPort; - tuple.destinationPort = dstPort; + tuple.sourcePort = srcPort; + tuple.destinationPort = dstPort; #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - // try to insert the tuple, but check if it already exists - std::pair::iterator, bool> insert - = m_flowMap.insert (std::pair (tuple, 0)); + // try to insert the tuple, but check if it already exists + std::pair::iterator, bool> insert = + m_flowMap.insert(std::pair(tuple, 0)); - // if the insertion succeeded, we need to assign this tuple a new flow identifier - if (insert.second) + // if the insertion succeeded, we need to assign this tuple a new flow identifier + if (insert.second) { - FlowId newFlowId = GetNewFlowId (); - insert.first->second = newFlowId; - m_flowPktIdMap[newFlowId] = 0; - m_flowDscpMap[newFlowId]; + FlowId newFlowId = GetNewFlowId(); + insert.first->second = newFlowId; + m_flowPktIdMap[newFlowId] = 0; + m_flowDscpMap[newFlowId]; } - else + else { - m_flowPktIdMap[insert.first->second] ++; + m_flowPktIdMap[insert.first->second]++; } - // increment the counter of packets with the same DSCP value - Ipv4Header::DscpType dscp = ipHeader.GetDscp (); - std::pair::iterator, bool> dscpInserter - = m_flowDscpMap[insert.first->second].insert (std::pair (dscp, 1)); + // increment the counter of packets with the same DSCP value + Ipv4Header::DscpType dscp = ipHeader.GetDscp(); + std::pair::iterator, bool> dscpInserter = + m_flowDscpMap[insert.first->second].insert( + std::pair(dscp, 1)); - // if the insertion did not succeed, we need to increment the counter - if (!dscpInserter.second) + // if the insertion did not succeed, we need to increment the counter + if (!dscpInserter.second) { - m_flowDscpMap[insert.first->second][dscp] ++; + m_flowDscpMap[insert.first->second][dscp]++; } - *out_flowId = insert.first->second; - *out_packetId = m_flowPktIdMap[*out_flowId]; + *out_flowId = insert.first->second; + *out_packetId = m_flowPktIdMap[*out_flowId]; #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif - return true; + return true; } - Ipv4FlowClassifier::FiveTuple -Ipv4FlowClassifier::FindFlow (FlowId flowId) const +Ipv4FlowClassifier::FindFlow(FlowId flowId) const { - for (std::map::const_iterator - iter = m_flowMap.begin (); iter != m_flowMap.end (); iter++) + for (std::map::const_iterator iter = m_flowMap.begin(); + iter != m_flowMap.end(); + iter++) { - if (iter->second == flowId) + if (iter->second == flowId) { - return iter->first; + return iter->first; } } - NS_FATAL_ERROR ("Could not find the flow with ID " << flowId); - FiveTuple retval = { Ipv4Address::GetZero (), Ipv4Address::GetZero (), 0, 0, 0 }; - return retval; + NS_FATAL_ERROR("Could not find the flow with ID " << flowId); + FiveTuple retval = {Ipv4Address::GetZero(), Ipv4Address::GetZero(), 0, 0, 0}; + return retval; } bool -Ipv4FlowClassifier::SortByCount::operator() (std::pair left, - std::pair right) +Ipv4FlowClassifier::SortByCount::operator()(std::pair left, + std::pair right) { - return left.second > right.second; + return left.second > right.second; } -std::vector > -Ipv4FlowClassifier::GetDscpCounts (FlowId flowId) const +std::vector> +Ipv4FlowClassifier::GetDscpCounts(FlowId flowId) const { - std::map >::const_iterator flow - = m_flowDscpMap.find (flowId); + std::map>::const_iterator flow = + m_flowDscpMap.find(flowId); - if (flow == m_flowDscpMap.end ()) + if (flow == m_flowDscpMap.end()) { - NS_FATAL_ERROR ("Could not find the flow with ID " << flowId); + NS_FATAL_ERROR("Could not find the flow with ID " << flowId); } - std::vector > v (flow->second.begin (), flow->second.end ()); - std::sort (v.begin (), v.end (), SortByCount ()); - return v; + std::vector> v(flow->second.begin(), + flow->second.end()); + std::sort(v.begin(), v.end(), SortByCount()); + return v; } void -Ipv4FlowClassifier::SerializeToXmlStream (std::ostream &os, uint16_t indent) const +Ipv4FlowClassifier::SerializeToXmlStream(std::ostream& os, uint16_t indent) const { - Indent (os, indent); os << "\n"; + Indent(os, indent); + os << "\n"; - indent += 2; - for (std::map::const_iterator - iter = m_flowMap.begin (); iter != m_flowMap.end (); iter++) + indent += 2; + for (std::map::const_iterator iter = m_flowMap.begin(); + iter != m_flowMap.end(); + iter++) { - Indent (os, indent); - os << "second << "\"" - << " sourceAddress=\"" << iter->first.sourceAddress << "\"" - << " destinationAddress=\"" << iter->first.destinationAddress << "\"" - << " protocol=\"" << int(iter->first.protocol) << "\"" - << " sourcePort=\"" << iter->first.sourcePort << "\"" - << " destinationPort=\"" << iter->first.destinationPort << "\">\n"; + Indent(os, indent); + os << "second << "\"" << " sourceAddress=\"" + << iter->first.sourceAddress << "\"" << " destinationAddress=\"" + << iter->first.destinationAddress << "\"" << " protocol=\"" << int(iter->first.protocol) + << "\"" << " sourcePort=\"" << iter->first.sourcePort << "\"" << " destinationPort=\"" + << iter->first.destinationPort << "\">\n"; - indent += 2; - std::map >::const_iterator flow - = m_flowDscpMap.find (iter->second); + indent += 2; + std::map>::const_iterator flow = + m_flowDscpMap.find(iter->second); - if (flow != m_flowDscpMap.end ()) + if (flow != m_flowDscpMap.end()) { - for (std::map::const_iterator i = flow->second.begin (); i != flow->second.end (); i++) + for (std::map::const_iterator i = flow->second.begin(); + i != flow->second.end(); + i++) { - Indent (os, indent); - os << " (i->first) << "\"" - << " packets=\"" << std::dec << i->second << "\" />\n"; + Indent(os, indent); + os << "(i->first) << "\"" + << " packets=\"" << std::dec << i->second << "\" />\n"; } } - indent -= 2; - Indent (os, indent); os << "\n"; + indent -= 2; + Indent(os, indent); + os << "\n"; } - indent -= 2; - Indent (os, indent); os << "\n"; + indent -= 2; + Indent(os, indent); + os << "\n"; } - } // namespace ns3 - diff --git a/src/flow-monitor/model/ipv4-flow-classifier.h b/src/flow-monitor/model/ipv4-flow-classifier.h index f676e85bf..56d797c31 100644 --- a/src/flow-monitor/model/ipv4-flow-classifier.h +++ b/src/flow-monitor/model/ipv4-flow-classifier.h @@ -21,14 +21,15 @@ #ifndef IPV4_FLOW_CLASSIFIER_H #define IPV4_FLOW_CLASSIFIER_H -#include -#include -#include - -#include "ns3/ipv4-header.h" #include "ns3/flow-classifier.h" +#include "ns3/ipv4-header.h" -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ class Packet; @@ -38,70 +39,70 @@ class Packet; /// flow identifier is assigned for each different tuple combination class Ipv4FlowClassifier : public FlowClassifier { -public: - - /// Structure to classify a packet - struct FiveTuple - { - Ipv4Address sourceAddress; //!< Source address - Ipv4Address destinationAddress; //!< Destination address - uint8_t protocol; //!< Protocol - uint16_t sourcePort; //!< Source port - uint16_t destinationPort; //!< Destination port - }; - - Ipv4FlowClassifier (); - - /// \brief try to classify the packet into flow-id and packet-id - /// - /// \warning: it must be called only once per packet, from SendOutgoingLogger. - /// - /// \return true if the packet was classified, false if not (i.e. it - /// does not appear to be part of a flow). - /// \param ipHeader packet's IP header - /// \param ipPayload packet's IP payload - /// \param out_flowId packet's FlowId - /// \param out_packetId packet's identifier - bool Classify (const Ipv4Header &ipHeader, Ptr ipPayload, - uint32_t *out_flowId, uint32_t *out_packetId); - - /// Searches for the FiveTuple corresponding to the given flowId - /// \param flowId the FlowId to search for - /// \returns the FiveTuple corresponding to flowId - FiveTuple FindFlow (FlowId flowId) const; - - /// Comparator used to sort the vector of DSCP values - class SortByCount - { public: - /// Comparator function - /// \param left left operand - /// \param right right operand - /// \return true if left DSCP is greater than right DSCP - bool operator() (std::pair left, - std::pair right); - }; + /// Structure to classify a packet + struct FiveTuple + { + Ipv4Address sourceAddress; //!< Source address + Ipv4Address destinationAddress; //!< Destination address + uint8_t protocol; //!< Protocol + uint16_t sourcePort; //!< Source port + uint16_t destinationPort; //!< Destination port + }; - /// \brief get the DSCP values of the packets belonging to the flow with the - /// given FlowId, sorted in decreasing order of number of packets seen with - /// that DSCP value - /// \param flowId the identifier of the flow of interest - /// \returns the vector of DSCP values - std::vector > GetDscpCounts (FlowId flowId) const; + Ipv4FlowClassifier(); - void SerializeToXmlStream (std::ostream &os, uint16_t indent) const override; + /// \brief try to classify the packet into flow-id and packet-id + /// + /// \warning: it must be called only once per packet, from SendOutgoingLogger. + /// + /// \return true if the packet was classified, false if not (i.e. it + /// does not appear to be part of a flow). + /// \param ipHeader packet's IP header + /// \param ipPayload packet's IP payload + /// \param out_flowId packet's FlowId + /// \param out_packetId packet's identifier + bool Classify(const Ipv4Header& ipHeader, + Ptr ipPayload, + uint32_t* out_flowId, + uint32_t* out_packetId); -private: + /// Searches for the FiveTuple corresponding to the given flowId + /// \param flowId the FlowId to search for + /// \returns the FiveTuple corresponding to flowId + FiveTuple FindFlow(FlowId flowId) const; - /// Map to Flows Identifiers to FlowIds - std::map m_flowMap; - /// Map to FlowIds to FlowPacketId - std::map m_flowPktIdMap; - /// Map FlowIds to (DSCP value, packet count) pairs - std::map > m_flowDscpMap; + /// Comparator used to sort the vector of DSCP values + class SortByCount + { + public: + /// Comparator function + /// \param left left operand + /// \param right right operand + /// \return true if left DSCP is greater than right DSCP + bool operator()(std::pair left, + std::pair right); + }; + + /// \brief get the DSCP values of the packets belonging to the flow with the + /// given FlowId, sorted in decreasing order of number of packets seen with + /// that DSCP value + /// \param flowId the identifier of the flow of interest + /// \returns the vector of DSCP values + std::vector> GetDscpCounts(FlowId flowId) const; + + void SerializeToXmlStream(std::ostream& os, uint16_t indent) const override; + + private: + /// Map to Flows Identifiers to FlowIds + std::map m_flowMap; + /// Map to FlowIds to FlowPacketId + std::map m_flowPktIdMap; + /// Map FlowIds to (DSCP value, packet count) pairs + std::map> m_flowDscpMap; #ifdef NS3_MTP - std::atomic m_lock; + std::atomic m_lock; #endif }; @@ -112,7 +113,7 @@ private: * \param t2 the first operand * \returns true if the operands are equal */ -bool operator < (const Ipv4FlowClassifier::FiveTuple &t1, const Ipv4FlowClassifier::FiveTuple &t2); +bool operator<(const Ipv4FlowClassifier::FiveTuple& t1, const Ipv4FlowClassifier::FiveTuple& t2); /** * \brief Equal to operator. @@ -121,8 +122,7 @@ bool operator < (const Ipv4FlowClassifier::FiveTuple &t1, const Ipv4FlowClassifi * \param t2 the first operand * \returns true if the operands are equal */ -bool operator == (const Ipv4FlowClassifier::FiveTuple &t1, const Ipv4FlowClassifier::FiveTuple &t2); - +bool operator==(const Ipv4FlowClassifier::FiveTuple& t1, const Ipv4FlowClassifier::FiveTuple& t2); } // namespace ns3 diff --git a/src/flow-monitor/model/ipv4-flow-probe.cc b/src/flow-monitor/model/ipv4-flow-probe.cc index d6ba543e1..1b4b15196 100644 --- a/src/flow-monitor/model/ipv4-flow-probe.cc +++ b/src/flow-monitor/model/ipv4-flow-probe.cc @@ -19,18 +19,20 @@ // #include "ns3/ipv4-flow-probe.h" -#include "ns3/ipv4-flow-classifier.h" -#include "ns3/node.h" -#include "ns3/packet.h" -#include "ns3/flow-monitor.h" -#include "ns3/log.h" -#include "ns3/pointer.h" + #include "ns3/config.h" #include "ns3/flow-id-tag.h" +#include "ns3/flow-monitor.h" +#include "ns3/ipv4-flow-classifier.h" +#include "ns3/log.h" +#include "ns3/node.h" +#include "ns3/packet.h" +#include "ns3/pointer.h" -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Ipv4FlowProbe"); +NS_LOG_COMPONENT_DEFINE("Ipv4FlowProbe"); ////////////////////////////////////// // Ipv4FlowProbeTag class implementation // @@ -47,336 +49,382 @@ NS_LOG_COMPONENT_DEFINE ("Ipv4FlowProbe"); */ class Ipv4FlowProbeTag : public Tag { -public: - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (); - TypeId GetInstanceTypeId () const override; - uint32_t GetSerializedSize () const override; - void Serialize (TagBuffer buf) const override; - void Deserialize (TagBuffer buf) override; - void Print (std::ostream &os) const override; - Ipv4FlowProbeTag (); - /** - * \brief Consructor - * \param flowId the flow identifier - * \param packetId the packet identifier - * \param packetSize the packet size - * \param src packet source address - * \param dst packet destination address - */ - Ipv4FlowProbeTag (uint32_t flowId, uint32_t packetId, uint32_t packetSize, Ipv4Address src, Ipv4Address dst); - /** - * \brief Set the flow identifier - * \param flowId the flow identifier - */ - void SetFlowId (uint32_t flowId); - /** - * \brief Set the packet identifier - * \param packetId the packet identifier - */ - void SetPacketId (uint32_t packetId); - /** - * \brief Set the packet size - * \param packetSize the packet size - */ - void SetPacketSize (uint32_t packetSize); - /** - * \brief Set the flow identifier - * \returns the flow identifier - */ - uint32_t GetFlowId () const; - /** - * \brief Set the packet identifier - * \returns the packet identifier - */ - uint32_t GetPacketId () const; - /** - * \brief Get the packet size - * \returns the packet size - */ - uint32_t GetPacketSize () const; - /** - * \brief Checks if the addresses stored in tag are matching - * the arguments. - * - * This check is important for IP over IP encapsulation. - * - * \param src Source address. - * \param dst Destination address. - * \returns True if the addresses are matching. - */ - bool IsSrcDstValid (Ipv4Address src, Ipv4Address dst) const; -private: - uint32_t m_flowId; //!< flow identifier - uint32_t m_packetId; //!< packet identifier - uint32_t m_packetSize; //!< packet size - Ipv4Address m_src; //!< IP source - Ipv4Address m_dst; //!< IP destination + public: + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(); + TypeId GetInstanceTypeId() const override; + uint32_t GetSerializedSize() const override; + void Serialize(TagBuffer buf) const override; + void Deserialize(TagBuffer buf) override; + void Print(std::ostream& os) const override; + Ipv4FlowProbeTag(); + /** + * \brief Consructor + * \param flowId the flow identifier + * \param packetId the packet identifier + * \param packetSize the packet size + * \param src packet source address + * \param dst packet destination address + */ + Ipv4FlowProbeTag(uint32_t flowId, + uint32_t packetId, + uint32_t packetSize, + Ipv4Address src, + Ipv4Address dst); + /** + * \brief Set the flow identifier + * \param flowId the flow identifier + */ + void SetFlowId(uint32_t flowId); + /** + * \brief Set the packet identifier + * \param packetId the packet identifier + */ + void SetPacketId(uint32_t packetId); + /** + * \brief Set the packet size + * \param packetSize the packet size + */ + void SetPacketSize(uint32_t packetSize); + /** + * \brief Set the flow identifier + * \returns the flow identifier + */ + uint32_t GetFlowId() const; + /** + * \brief Set the packet identifier + * \returns the packet identifier + */ + uint32_t GetPacketId() const; + /** + * \brief Get the packet size + * \returns the packet size + */ + uint32_t GetPacketSize() const; + /** + * \brief Checks if the addresses stored in tag are matching + * the arguments. + * + * This check is important for IP over IP encapsulation. + * + * \param src Source address. + * \param dst Destination address. + * \returns True if the addresses are matching. + */ + bool IsSrcDstValid(Ipv4Address src, Ipv4Address dst) const; + + private: + uint32_t m_flowId; //!< flow identifier + uint32_t m_packetId; //!< packet identifier + uint32_t m_packetSize; //!< packet size + Ipv4Address m_src; //!< IP source + Ipv4Address m_dst; //!< IP destination }; -NS_OBJECT_ENSURE_REGISTERED (Ipv4FlowProbeTag); +NS_OBJECT_ENSURE_REGISTERED(Ipv4FlowProbeTag); -TypeId -Ipv4FlowProbeTag::GetTypeId (void) -{ - static TypeId tid = TypeId ("ns3::Ipv4FlowProbeTag") - .SetParent () - .SetGroupName ("FlowMonitor") - .AddConstructor () - ; - return tid; -} TypeId -Ipv4FlowProbeTag::GetInstanceTypeId () const +Ipv4FlowProbeTag::GetTypeId(void) { - return GetTypeId (); + static TypeId tid = TypeId("ns3::Ipv4FlowProbeTag") + .SetParent() + .SetGroupName("FlowMonitor") + .AddConstructor(); + return tid; } + +TypeId +Ipv4FlowProbeTag::GetInstanceTypeId() const +{ + return GetTypeId(); +} + uint32_t -Ipv4FlowProbeTag::GetSerializedSize () const +Ipv4FlowProbeTag::GetSerializedSize() const { - return 4 + 4 + 4 + 8; + return 4 + 4 + 4 + 8; } -void -Ipv4FlowProbeTag::Serialize (TagBuffer buf) const -{ - buf.WriteU32 (m_flowId); - buf.WriteU32 (m_packetId); - buf.WriteU32 (m_packetSize); - uint8_t tBuf[4]; - m_src.Serialize (tBuf); - buf.Write (tBuf, 4); - m_dst.Serialize (tBuf); - buf.Write (tBuf, 4); -} void -Ipv4FlowProbeTag::Deserialize (TagBuffer buf) +Ipv4FlowProbeTag::Serialize(TagBuffer buf) const { - m_flowId = buf.ReadU32 (); - m_packetId = buf.ReadU32 (); - m_packetSize = buf.ReadU32 (); + buf.WriteU32(m_flowId); + buf.WriteU32(m_packetId); + buf.WriteU32(m_packetSize); - uint8_t tBuf[4]; - buf.Read (tBuf, 4); - m_src = Ipv4Address::Deserialize (tBuf); - buf.Read (tBuf, 4); - m_dst = Ipv4Address::Deserialize (tBuf); + uint8_t tBuf[4]; + m_src.Serialize(tBuf); + buf.Write(tBuf, 4); + m_dst.Serialize(tBuf); + buf.Write(tBuf, 4); } + void -Ipv4FlowProbeTag::Print (std::ostream &os) const +Ipv4FlowProbeTag::Deserialize(TagBuffer buf) { - os << "FlowId=" << m_flowId; - os << " PacketId=" << m_packetId; - os << " PacketSize=" << m_packetSize; + m_flowId = buf.ReadU32(); + m_packetId = buf.ReadU32(); + m_packetSize = buf.ReadU32(); + + uint8_t tBuf[4]; + buf.Read(tBuf, 4); + m_src = Ipv4Address::Deserialize(tBuf); + buf.Read(tBuf, 4); + m_dst = Ipv4Address::Deserialize(tBuf); } -Ipv4FlowProbeTag::Ipv4FlowProbeTag () - : Tag () + +void +Ipv4FlowProbeTag::Print(std::ostream& os) const +{ + os << "FlowId=" << m_flowId; + os << " PacketId=" << m_packetId; + os << " PacketSize=" << m_packetSize; +} + +Ipv4FlowProbeTag::Ipv4FlowProbeTag() + : Tag() { } -Ipv4FlowProbeTag::Ipv4FlowProbeTag (uint32_t flowId, uint32_t packetId, uint32_t packetSize, Ipv4Address src, Ipv4Address dst) - : Tag (), m_flowId (flowId), m_packetId (packetId), m_packetSize (packetSize), m_src (src), m_dst (dst) +Ipv4FlowProbeTag::Ipv4FlowProbeTag(uint32_t flowId, + uint32_t packetId, + uint32_t packetSize, + Ipv4Address src, + Ipv4Address dst) + : Tag(), + m_flowId(flowId), + m_packetId(packetId), + m_packetSize(packetSize), + m_src(src), + m_dst(dst) { } void -Ipv4FlowProbeTag::SetFlowId (uint32_t id) +Ipv4FlowProbeTag::SetFlowId(uint32_t id) { - m_flowId = id; + m_flowId = id; } + void -Ipv4FlowProbeTag::SetPacketId (uint32_t id) +Ipv4FlowProbeTag::SetPacketId(uint32_t id) { - m_packetId = id; + m_packetId = id; } + void -Ipv4FlowProbeTag::SetPacketSize (uint32_t size) +Ipv4FlowProbeTag::SetPacketSize(uint32_t size) { - m_packetSize = size; + m_packetSize = size; } + uint32_t -Ipv4FlowProbeTag::GetFlowId () const +Ipv4FlowProbeTag::GetFlowId() const { - return m_flowId; + return m_flowId; } + uint32_t -Ipv4FlowProbeTag::GetPacketId () const +Ipv4FlowProbeTag::GetPacketId() const { - return m_packetId; + return m_packetId; } + uint32_t -Ipv4FlowProbeTag::GetPacketSize () const +Ipv4FlowProbeTag::GetPacketSize() const { - return m_packetSize; + return m_packetSize; } + bool -Ipv4FlowProbeTag::IsSrcDstValid (Ipv4Address src, Ipv4Address dst) const +Ipv4FlowProbeTag::IsSrcDstValid(Ipv4Address src, Ipv4Address dst) const { - return ((m_src == src) && (m_dst == dst)); + return ((m_src == src) && (m_dst == dst)); } //////////////////////////////////////// // Ipv4FlowProbe class implementation // //////////////////////////////////////// -Ipv4FlowProbe::Ipv4FlowProbe (Ptr monitor, - Ptr classifier, - Ptr node) - : FlowProbe (monitor), - m_classifier (classifier) +Ipv4FlowProbe::Ipv4FlowProbe(Ptr monitor, + Ptr classifier, + Ptr node) + : FlowProbe(monitor), + m_classifier(classifier) { - NS_LOG_FUNCTION (this << node->GetId ()); + NS_LOG_FUNCTION(this << node->GetId()); - m_ipv4 = node->GetObject (); + m_ipv4 = node->GetObject(); - if (!m_ipv4->TraceConnectWithoutContext ("SendOutgoing", - MakeCallback (&Ipv4FlowProbe::SendOutgoingLogger, Ptr (this)))) + if (!m_ipv4->TraceConnectWithoutContext( + "SendOutgoing", + MakeCallback(&Ipv4FlowProbe::SendOutgoingLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!m_ipv4->TraceConnectWithoutContext ("UnicastForward", - MakeCallback (&Ipv4FlowProbe::ForwardLogger, Ptr (this)))) + if (!m_ipv4->TraceConnectWithoutContext( + "UnicastForward", + MakeCallback(&Ipv4FlowProbe::ForwardLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!m_ipv4->TraceConnectWithoutContext ("LocalDeliver", - MakeCallback (&Ipv4FlowProbe::ForwardUpLogger, Ptr (this)))) + if (!m_ipv4->TraceConnectWithoutContext( + "LocalDeliver", + MakeCallback(&Ipv4FlowProbe::ForwardUpLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!m_ipv4->TraceConnectWithoutContext ("Drop", - MakeCallback (&Ipv4FlowProbe::DropLogger, Ptr (this)))) + if (!m_ipv4->TraceConnectWithoutContext( + "Drop", + MakeCallback(&Ipv4FlowProbe::DropLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - std::ostringstream qd; - qd << "/NodeList/" << node->GetId () << "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Drop"; - Config::ConnectWithoutContextFailSafe (qd.str (), MakeCallback (&Ipv4FlowProbe::QueueDiscDropLogger, Ptr (this))); + std::ostringstream qd; + qd << "/NodeList/" << node->GetId() << "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Drop"; + Config::ConnectWithoutContextFailSafe( + qd.str(), + MakeCallback(&Ipv4FlowProbe::QueueDiscDropLogger, Ptr(this))); - // code copied from point-to-point-helper.cc - std::ostringstream oss; - oss << "/NodeList/" << node->GetId () << "/DeviceList/*/TxQueue/Drop"; - Config::ConnectWithoutContextFailSafe (oss.str (), MakeCallback (&Ipv4FlowProbe::QueueDropLogger, Ptr (this))); + // code copied from point-to-point-helper.cc + std::ostringstream oss; + oss << "/NodeList/" << node->GetId() << "/DeviceList/*/TxQueue/Drop"; + Config::ConnectWithoutContextFailSafe( + oss.str(), + MakeCallback(&Ipv4FlowProbe::QueueDropLogger, Ptr(this))); } -Ipv4FlowProbe::~Ipv4FlowProbe () +Ipv4FlowProbe::~Ipv4FlowProbe() { } /* static */ TypeId -Ipv4FlowProbe::GetTypeId () +Ipv4FlowProbe::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv4FlowProbe") - .SetParent () - .SetGroupName ("FlowMonitor") - // No AddConstructor because this class has no default constructor. - ; + static TypeId tid = + TypeId("ns3::Ipv4FlowProbe").SetParent().SetGroupName("FlowMonitor") + // No AddConstructor because this class has no default constructor. + ; - return tid; + return tid; } void -Ipv4FlowProbe::DoDispose () +Ipv4FlowProbe::DoDispose() { - m_ipv4 = nullptr; - m_classifier = nullptr; - FlowProbe::DoDispose (); + m_ipv4 = nullptr; + m_classifier = nullptr; + FlowProbe::DoDispose(); } void -Ipv4FlowProbe::SendOutgoingLogger (const Ipv4Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv4FlowProbe::SendOutgoingLogger(const Ipv4Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - FlowId flowId; - FlowPacketId packetId; + FlowId flowId; + FlowPacketId packetId; - if (!m_ipv4->IsUnicast(ipHeader.GetDestination ())) + if (!m_ipv4->IsUnicast(ipHeader.GetDestination())) { - // we are not prepared to handle broadcast yet - return; + // we are not prepared to handle broadcast yet + return; } - Ipv4FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); - if (found) + Ipv4FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); + if (found) { - return; + return; } - if (m_classifier->Classify (ipHeader, ipPayload, &flowId, &packetId)) + if (m_classifier->Classify(ipHeader, ipPayload, &flowId, &packetId)) { - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportFirstTx ("<ReportFirstTx (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportFirstTx (" << this << ", " << flowId << ", " << packetId << ", " << size + << "); " << ipHeader << *ipPayload); + m_flowMonitor->ReportFirstTx(this, flowId, packetId, size); - // tag the packet with the flow id and packet id, so that the packet can be identified even - // when Ipv4Header is not accessible at some non-IPv4 protocol layer - Ipv4FlowProbeTag fTag (flowId, packetId, size, ipHeader.GetSource (), ipHeader.GetDestination ()); - ipPayload->AddByteTag (fTag); + // tag the packet with the flow id and packet id, so that the packet can be identified even + // when Ipv4Header is not accessible at some non-IPv4 protocol layer + Ipv4FlowProbeTag fTag(flowId, + packetId, + size, + ipHeader.GetSource(), + ipHeader.GetDestination()); + ipPayload->AddByteTag(fTag); } } void -Ipv4FlowProbe::ForwardLogger (const Ipv4Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv4FlowProbe::ForwardLogger(const Ipv4Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - Ipv4FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv4FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - if (!ipHeader.IsLastFragment () || ipHeader.GetFragmentOffset () != 0) + if (!ipHeader.IsLastFragment() || ipHeader.GetFragmentOffset() != 0) { - NS_LOG_WARN ("Not counting fragmented packets"); - return; + NS_LOG_WARN("Not counting fragmented packets"); + return; } - if (!fTag.IsSrcDstValid (ipHeader.GetSource (), ipHeader.GetDestination ())) + if (!fTag.IsSrcDstValid(ipHeader.GetSource(), ipHeader.GetDestination())) { - NS_LOG_LOGIC ("Not reporting encapsulated packet"); - return; + NS_LOG_LOGIC("Not reporting encapsulated packet"); + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportForwarding ("<ReportForwarding (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportForwarding (" << this << ", " << flowId << ", " << packetId << ", " + << size << ");"); + m_flowMonitor->ReportForwarding(this, flowId, packetId, size); } } void -Ipv4FlowProbe::ForwardUpLogger (const Ipv4Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv4FlowProbe::ForwardUpLogger(const Ipv4Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - Ipv4FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv4FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - if (!fTag.IsSrcDstValid (ipHeader.GetSource (), ipHeader.GetDestination ())) + if (!fTag.IsSrcDstValid(ipHeader.GetSource(), ipHeader.GetDestination())) { - NS_LOG_LOGIC ("Not reporting encapsulated packet"); - return; + NS_LOG_LOGIC("Not reporting encapsulated packet"); + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportLastRx ("<ReportLastRx (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportLastRx (" << this << ", " << flowId << ", " << packetId << ", " << size + << "); " << ipHeader << *ipPayload); + m_flowMonitor->ReportLastRx(this, flowId, packetId, size); } } void -Ipv4FlowProbe::DropLogger (const Ipv4Header &ipHeader, Ptr ipPayload, - Ipv4L3Protocol::DropReason reason, Ptr ipv4, uint32_t ifIndex) +Ipv4FlowProbe::DropLogger(const Ipv4Header& ipHeader, + Ptr ipPayload, + Ipv4L3Protocol::DropReason reason, + Ptr ipv4, + uint32_t ifIndex) { #if 0 switch (reason) @@ -396,100 +444,97 @@ Ipv4FlowProbe::DropLogger (const Ipv4Header &ipHeader, Ptr ipPaylo } #endif - Ipv4FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv4FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("Drop ("<GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("Drop (" << this << ", " << flowId << ", " << packetId << ", " << size << ", " + << reason << ", destIp=" << ipHeader.GetDestination() << "); " + << "HDR: " << ipHeader << " PKT: " << *ipPayload); - DropReason myReason; + DropReason myReason; - - switch (reason) + switch (reason) { case Ipv4L3Protocol::DROP_TTL_EXPIRED: - myReason = DROP_TTL_EXPIRE; - NS_LOG_DEBUG ("DROP_TTL_EXPIRE"); - break; + myReason = DROP_TTL_EXPIRE; + NS_LOG_DEBUG("DROP_TTL_EXPIRE"); + break; case Ipv4L3Protocol::DROP_NO_ROUTE: - myReason = DROP_NO_ROUTE; - NS_LOG_DEBUG ("DROP_NO_ROUTE"); - break; + myReason = DROP_NO_ROUTE; + NS_LOG_DEBUG("DROP_NO_ROUTE"); + break; case Ipv4L3Protocol::DROP_BAD_CHECKSUM: - myReason = DROP_BAD_CHECKSUM; - NS_LOG_DEBUG ("DROP_BAD_CHECKSUM"); - break; + myReason = DROP_BAD_CHECKSUM; + NS_LOG_DEBUG("DROP_BAD_CHECKSUM"); + break; case Ipv4L3Protocol::DROP_INTERFACE_DOWN: - myReason = DROP_INTERFACE_DOWN; - NS_LOG_DEBUG ("DROP_INTERFACE_DOWN"); - break; + myReason = DROP_INTERFACE_DOWN; + NS_LOG_DEBUG("DROP_INTERFACE_DOWN"); + break; case Ipv4L3Protocol::DROP_ROUTE_ERROR: - myReason = DROP_ROUTE_ERROR; - NS_LOG_DEBUG ("DROP_ROUTE_ERROR"); - break; + myReason = DROP_ROUTE_ERROR; + NS_LOG_DEBUG("DROP_ROUTE_ERROR"); + break; case Ipv4L3Protocol::DROP_FRAGMENT_TIMEOUT: - myReason = DROP_FRAGMENT_TIMEOUT; - NS_LOG_DEBUG ("DROP_FRAGMENT_TIMEOUT"); - break; + myReason = DROP_FRAGMENT_TIMEOUT; + NS_LOG_DEBUG("DROP_FRAGMENT_TIMEOUT"); + break; default: - myReason = DROP_INVALID_REASON; - NS_FATAL_ERROR ("Unexpected drop reason code " << reason); + myReason = DROP_INVALID_REASON; + NS_FATAL_ERROR("Unexpected drop reason code " << reason); } - m_flowMonitor->ReportDrop (this, flowId, packetId, size, myReason); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, myReason); } } void -Ipv4FlowProbe::QueueDropLogger (Ptr ipPayload) +Ipv4FlowProbe::QueueDropLogger(Ptr ipPayload) { - Ipv4FlowProbeTag fTag; - bool tagFound = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv4FlowProbeTag fTag; + bool tagFound = ipPayload->FindFirstMatchingByteTag(fTag); - if (!tagFound) + if (!tagFound) { - return; + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); - uint32_t size = fTag.GetPacketSize (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); + uint32_t size = fTag.GetPacketSize(); - NS_LOG_DEBUG ("Drop ("<ReportDrop (this, flowId, packetId, size, DROP_QUEUE); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, DROP_QUEUE); } void -Ipv4FlowProbe::QueueDiscDropLogger (Ptr item) +Ipv4FlowProbe::QueueDiscDropLogger(Ptr item) { - Ipv4FlowProbeTag fTag; - bool tagFound = item->GetPacket ()->FindFirstMatchingByteTag (fTag); + Ipv4FlowProbeTag fTag; + bool tagFound = item->GetPacket()->FindFirstMatchingByteTag(fTag); - if (!tagFound) + if (!tagFound) { - return; + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); - uint32_t size = fTag.GetPacketSize (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); + uint32_t size = fTag.GetPacketSize(); - NS_LOG_DEBUG ("Drop ("<ReportDrop (this, flowId, packetId, size, DROP_QUEUE_DISC); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, DROP_QUEUE_DISC); } } // namespace ns3 - - diff --git a/src/flow-monitor/model/ipv6-flow-classifier.cc b/src/flow-monitor/model/ipv6-flow-classifier.cc index 5db15a4dd..737791f7e 100644 --- a/src/flow-monitor/model/ipv6-flow-classifier.cc +++ b/src/flow-monitor/model/ipv6-flow-classifier.cc @@ -19,261 +19,263 @@ // Modifications: Tommaso Pecorella // -#include "ns3/packet.h" - #include "ipv6-flow-classifier.h" -#include "ns3/udp-header.h" + +#include "ns3/packet.h" #include "ns3/tcp-header.h" +#include "ns3/udp-header.h" + #include -namespace ns3 { +namespace ns3 +{ /* see http://www.iana.org/assignments/protocol-numbers */ const uint8_t TCP_PROT_NUMBER = 6; //!< TCP Protocol number const uint8_t UDP_PROT_NUMBER = 17; //!< UDP Protocol number - - -bool operator < (const Ipv6FlowClassifier::FiveTuple &t1, - const Ipv6FlowClassifier::FiveTuple &t2) +bool +operator<(const Ipv6FlowClassifier::FiveTuple& t1, const Ipv6FlowClassifier::FiveTuple& t2) { - if (t1.sourceAddress < t2.sourceAddress) + if (t1.sourceAddress < t2.sourceAddress) { - return true; + return true; } - if (t1.sourceAddress != t2.sourceAddress) + if (t1.sourceAddress != t2.sourceAddress) { - return false; + return false; } - if (t1.destinationAddress < t2.destinationAddress) + if (t1.destinationAddress < t2.destinationAddress) { - return true; + return true; } - if (t1.destinationAddress != t2.destinationAddress) + if (t1.destinationAddress != t2.destinationAddress) { - return false; + return false; } - if (t1.protocol < t2.protocol) + if (t1.protocol < t2.protocol) { - return true; + return true; } - if (t1.protocol != t2.protocol) + if (t1.protocol != t2.protocol) { - return false; + return false; } - if (t1.sourcePort < t2.sourcePort) + if (t1.sourcePort < t2.sourcePort) { - return true; + return true; } - if (t1.sourcePort != t2.sourcePort) + if (t1.sourcePort != t2.sourcePort) { - return false; + return false; } - if (t1.destinationPort < t2.destinationPort) + if (t1.destinationPort < t2.destinationPort) { - return true; + return true; } - if (t1.destinationPort != t2.destinationPort) + if (t1.destinationPort != t2.destinationPort) { - return false; + return false; } - return false; + return false; } -bool operator == (const Ipv6FlowClassifier::FiveTuple &t1, - const Ipv6FlowClassifier::FiveTuple &t2) +bool +operator==(const Ipv6FlowClassifier::FiveTuple& t1, const Ipv6FlowClassifier::FiveTuple& t2) { - return (t1.sourceAddress == t2.sourceAddress && - t1.destinationAddress == t2.destinationAddress && - t1.protocol == t2.protocol && - t1.sourcePort == t2.sourcePort && - t1.destinationPort == t2.destinationPort); + return (t1.sourceAddress == t2.sourceAddress && + t1.destinationAddress == t2.destinationAddress && t1.protocol == t2.protocol && + t1.sourcePort == t2.sourcePort && t1.destinationPort == t2.destinationPort); } - - -Ipv6FlowClassifier::Ipv6FlowClassifier () +Ipv6FlowClassifier::Ipv6FlowClassifier() { #ifdef NS3_MTP - m_lock.store (false, std::memory_order_relaxed); + m_lock.store(false, std::memory_order_relaxed); #endif } bool -Ipv6FlowClassifier::Classify (const Ipv6Header &ipHeader, Ptr ipPayload, - uint32_t *out_flowId, uint32_t *out_packetId) +Ipv6FlowClassifier::Classify(const Ipv6Header& ipHeader, + Ptr ipPayload, + uint32_t* out_flowId, + uint32_t* out_packetId) { - if (ipHeader.GetDestination ().IsMulticast ()) + if (ipHeader.GetDestination().IsMulticast()) { - // we are not prepared to handle multicast yet - return false; + // we are not prepared to handle multicast yet + return false; } - FiveTuple tuple; - tuple.sourceAddress = ipHeader.GetSource (); - tuple.destinationAddress = ipHeader.GetDestination (); - tuple.protocol = ipHeader.GetNextHeader (); + FiveTuple tuple; + tuple.sourceAddress = ipHeader.GetSource(); + tuple.destinationAddress = ipHeader.GetDestination(); + tuple.protocol = ipHeader.GetNextHeader(); - if ((tuple.protocol != UDP_PROT_NUMBER) && (tuple.protocol != TCP_PROT_NUMBER)) + if ((tuple.protocol != UDP_PROT_NUMBER) && (tuple.protocol != TCP_PROT_NUMBER)) { - return false; + return false; } - if (ipPayload->GetSize () < 4) + if (ipPayload->GetSize() < 4) { - // the packet doesn't carry enough bytes - return false; + // the packet doesn't carry enough bytes + return false; } - // we rely on the fact that for both TCP and UDP the ports are - // carried in the first 4 octects. - // This allows to read the ports even on fragmented packets - // not carrying a full TCP or UDP header. + // we rely on the fact that for both TCP and UDP the ports are + // carried in the first 4 octects. + // This allows to read the ports even on fragmented packets + // not carrying a full TCP or UDP header. - uint8_t data[4]; - ipPayload->CopyData (data, 4); + uint8_t data[4]; + ipPayload->CopyData(data, 4); - uint16_t srcPort = 0; - srcPort |= data[0]; - srcPort <<= 8; - srcPort |= data[1]; + uint16_t srcPort = 0; + srcPort |= data[0]; + srcPort <<= 8; + srcPort |= data[1]; - uint16_t dstPort = 0; - dstPort |= data[2]; - dstPort <<= 8; - dstPort |= data[3]; + uint16_t dstPort = 0; + dstPort |= data[2]; + dstPort <<= 8; + dstPort |= data[3]; - tuple.sourcePort = srcPort; - tuple.destinationPort = dstPort; + tuple.sourcePort = srcPort; + tuple.destinationPort = dstPort; #ifdef NS3_MTP - while (m_lock.exchange (true, std::memory_order_acquire)) - ; + while (m_lock.exchange(true, std::memory_order_acquire)) + ; #endif - // try to insert the tuple, but check if it already exists - std::pair::iterator, bool> insert - = m_flowMap.insert (std::pair (tuple, 0)); + // try to insert the tuple, but check if it already exists + std::pair::iterator, bool> insert = + m_flowMap.insert(std::pair(tuple, 0)); - // if the insertion succeeded, we need to assign this tuple a new flow identifier - if (insert.second) + // if the insertion succeeded, we need to assign this tuple a new flow identifier + if (insert.second) { - FlowId newFlowId = GetNewFlowId (); - insert.first->second = newFlowId; - m_flowPktIdMap[newFlowId] = 0; - m_flowDscpMap[newFlowId]; + FlowId newFlowId = GetNewFlowId(); + insert.first->second = newFlowId; + m_flowPktIdMap[newFlowId] = 0; + m_flowDscpMap[newFlowId]; } - else + else { - m_flowPktIdMap[insert.first->second] ++; + m_flowPktIdMap[insert.first->second]++; } - // increment the counter of packets with the same DSCP value - Ipv6Header::DscpType dscp = ipHeader.GetDscp (); - std::pair::iterator, bool> dscpInserter - = m_flowDscpMap[insert.first->second].insert (std::pair (dscp, 1)); + // increment the counter of packets with the same DSCP value + Ipv6Header::DscpType dscp = ipHeader.GetDscp(); + std::pair::iterator, bool> dscpInserter = + m_flowDscpMap[insert.first->second].insert( + std::pair(dscp, 1)); - // if the insertion did not succeed, we need to increment the counter - if (!dscpInserter.second) + // if the insertion did not succeed, we need to increment the counter + if (!dscpInserter.second) { - m_flowDscpMap[insert.first->second][dscp] ++; + m_flowDscpMap[insert.first->second][dscp]++; } - *out_flowId = insert.first->second; - *out_packetId = m_flowPktIdMap[*out_flowId]; + *out_flowId = insert.first->second; + *out_packetId = m_flowPktIdMap[*out_flowId]; #ifdef NS3_MTP - m_lock.store (false, std::memory_order_release); + m_lock.store(false, std::memory_order_release); #endif - return true; + return true; } - Ipv6FlowClassifier::FiveTuple -Ipv6FlowClassifier::FindFlow (FlowId flowId) const +Ipv6FlowClassifier::FindFlow(FlowId flowId) const { - for (std::map::const_iterator - iter = m_flowMap.begin (); iter != m_flowMap.end (); iter++) + for (std::map::const_iterator iter = m_flowMap.begin(); + iter != m_flowMap.end(); + iter++) { - if (iter->second == flowId) + if (iter->second == flowId) { - return iter->first; + return iter->first; } } - NS_FATAL_ERROR ("Could not find the flow with ID " << flowId); - FiveTuple retval = { Ipv6Address::GetZero (), Ipv6Address::GetZero (), 0, 0, 0 }; - return retval; + NS_FATAL_ERROR("Could not find the flow with ID " << flowId); + FiveTuple retval = {Ipv6Address::GetZero(), Ipv6Address::GetZero(), 0, 0, 0}; + return retval; } bool -Ipv6FlowClassifier::SortByCount::operator() (std::pair left, - std::pair right) +Ipv6FlowClassifier::SortByCount::operator()(std::pair left, + std::pair right) { - return left.second > right.second; + return left.second > right.second; } -std::vector > -Ipv6FlowClassifier::GetDscpCounts (FlowId flowId) const +std::vector> +Ipv6FlowClassifier::GetDscpCounts(FlowId flowId) const { - std::map >::const_iterator flow - = m_flowDscpMap.find (flowId); + std::map>::const_iterator flow = + m_flowDscpMap.find(flowId); - if (flow == m_flowDscpMap.end ()) + if (flow == m_flowDscpMap.end()) { - NS_FATAL_ERROR ("Could not find the flow with ID " << flowId); + NS_FATAL_ERROR("Could not find the flow with ID " << flowId); } - std::vector > v (flow->second.begin (), flow->second.end ()); - std::sort (v.begin (), v.end (), SortByCount ()); - return v; + std::vector> v(flow->second.begin(), + flow->second.end()); + std::sort(v.begin(), v.end(), SortByCount()); + return v; } void -Ipv6FlowClassifier::SerializeToXmlStream (std::ostream &os, uint16_t indent) const +Ipv6FlowClassifier::SerializeToXmlStream(std::ostream& os, uint16_t indent) const { - Indent (os, indent); os << "\n"; + Indent(os, indent); + os << "\n"; - indent += 2; - for (std::map::const_iterator - iter = m_flowMap.begin (); iter != m_flowMap.end (); iter++) + indent += 2; + for (std::map::const_iterator iter = m_flowMap.begin(); + iter != m_flowMap.end(); + iter++) { - Indent (os, indent); - os << "second << "\"" - << " sourceAddress=\"" << iter->first.sourceAddress << "\"" - << " destinationAddress=\"" << iter->first.destinationAddress << "\"" - << " protocol=\"" << int(iter->first.protocol) << "\"" - << " sourcePort=\"" << iter->first.sourcePort << "\"" - << " destinationPort=\"" << iter->first.destinationPort << "\">\n"; + Indent(os, indent); + os << "second << "\"" << " sourceAddress=\"" + << iter->first.sourceAddress << "\"" << " destinationAddress=\"" + << iter->first.destinationAddress << "\"" << " protocol=\"" << int(iter->first.protocol) + << "\"" << " sourcePort=\"" << iter->first.sourcePort << "\"" << " destinationPort=\"" + << iter->first.destinationPort << "\">\n"; - indent += 2; - std::map >::const_iterator flow - = m_flowDscpMap.find (iter->second); + indent += 2; + std::map>::const_iterator flow = + m_flowDscpMap.find(iter->second); - if (flow != m_flowDscpMap.end ()) + if (flow != m_flowDscpMap.end()) { - for (std::map::const_iterator i = flow->second.begin (); i != flow->second.end (); i++) + for (std::map::const_iterator i = flow->second.begin(); + i != flow->second.end(); + i++) { - Indent (os, indent); - os << " (i->first) << "\"" - << " packets=\"" << std::dec << i->second << "\" />\n"; + Indent(os, indent); + os << "(i->first) << "\"" + << " packets=\"" << std::dec << i->second << "\" />\n"; } } - indent -= 2; - Indent (os, indent); os << "\n"; + indent -= 2; + Indent(os, indent); + os << "\n"; } - indent -= 2; - Indent (os, indent); os << "\n"; - + indent -= 2; + Indent(os, indent); + os << "\n"; } - } // namespace ns3 - diff --git a/src/flow-monitor/model/ipv6-flow-classifier.h b/src/flow-monitor/model/ipv6-flow-classifier.h index 0ba6d9346..c870009e9 100644 --- a/src/flow-monitor/model/ipv6-flow-classifier.h +++ b/src/flow-monitor/model/ipv6-flow-classifier.h @@ -22,14 +22,15 @@ #ifndef IPV6_FLOW_CLASSIFIER_H #define IPV6_FLOW_CLASSIFIER_H -#include -#include -#include - -#include "ns3/ipv6-header.h" #include "ns3/flow-classifier.h" +#include "ns3/ipv6-header.h" -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ class Packet; @@ -39,70 +40,70 @@ class Packet; /// flow identifier is assigned for each different tuple combination class Ipv6FlowClassifier : public FlowClassifier { -public: - - /// Structure to classify a packet - struct FiveTuple - { - Ipv6Address sourceAddress; //!< Source address - Ipv6Address destinationAddress; //!< Destination address - uint8_t protocol; //!< Protocol - uint16_t sourcePort; //!< Source port - uint16_t destinationPort; //!< Destination port - }; - - Ipv6FlowClassifier (); - - /// \brief try to classify the packet into flow-id and packet-id - /// - /// \warning: it must be called only once per packet, from SendOutgoingLogger. - /// - /// \return true if the packet was classified, false if not (i.e. it - /// does not appear to be part of a flow). - /// \param ipHeader packet's IP header - /// \param ipPayload packet's IP payload - /// \param out_flowId packet's FlowId - /// \param out_packetId packet's identifier - bool Classify (const Ipv6Header &ipHeader, Ptr ipPayload, - uint32_t *out_flowId, uint32_t *out_packetId); - - /// Searches for the FiveTuple corresponding to the given flowId - /// \param flowId the FlowId to search for - /// \returns the FiveTuple corresponding to flowId - FiveTuple FindFlow (FlowId flowId) const; - - /// Comparator used to sort the vector of DSCP values - class SortByCount - { public: - /// Comparator function - /// \param left left operand - /// \param right right operand - /// \return true if left DSCP is greater than right DSCP - bool operator() (std::pair left, - std::pair right); - }; + /// Structure to classify a packet + struct FiveTuple + { + Ipv6Address sourceAddress; //!< Source address + Ipv6Address destinationAddress; //!< Destination address + uint8_t protocol; //!< Protocol + uint16_t sourcePort; //!< Source port + uint16_t destinationPort; //!< Destination port + }; - /// \brief get the DSCP values of the packets belonging to the flow with the - /// given FlowId, sorted in decreasing order of number of packets seen with - /// that DSCP value - /// \param flowId the identifier of the flow of interest - /// \returns the vector of DSCP values - std::vector > GetDscpCounts (FlowId flowId) const; + Ipv6FlowClassifier(); - void SerializeToXmlStream (std::ostream &os, uint16_t indent) const override; + /// \brief try to classify the packet into flow-id and packet-id + /// + /// \warning: it must be called only once per packet, from SendOutgoingLogger. + /// + /// \return true if the packet was classified, false if not (i.e. it + /// does not appear to be part of a flow). + /// \param ipHeader packet's IP header + /// \param ipPayload packet's IP payload + /// \param out_flowId packet's FlowId + /// \param out_packetId packet's identifier + bool Classify(const Ipv6Header& ipHeader, + Ptr ipPayload, + uint32_t* out_flowId, + uint32_t* out_packetId); -private: + /// Searches for the FiveTuple corresponding to the given flowId + /// \param flowId the FlowId to search for + /// \returns the FiveTuple corresponding to flowId + FiveTuple FindFlow(FlowId flowId) const; - /// Map to Flows Identifiers to FlowIds - std::map m_flowMap; - /// Map to FlowIds to FlowPacketId - std::map m_flowPktIdMap; - /// Map FlowIds to (DSCP value, packet count) pairs - std::map > m_flowDscpMap; + /// Comparator used to sort the vector of DSCP values + class SortByCount + { + public: + /// Comparator function + /// \param left left operand + /// \param right right operand + /// \return true if left DSCP is greater than right DSCP + bool operator()(std::pair left, + std::pair right); + }; + + /// \brief get the DSCP values of the packets belonging to the flow with the + /// given FlowId, sorted in decreasing order of number of packets seen with + /// that DSCP value + /// \param flowId the identifier of the flow of interest + /// \returns the vector of DSCP values + std::vector> GetDscpCounts(FlowId flowId) const; + + void SerializeToXmlStream(std::ostream& os, uint16_t indent) const override; + + private: + /// Map to Flows Identifiers to FlowIds + std::map m_flowMap; + /// Map to FlowIds to FlowPacketId + std::map m_flowPktIdMap; + /// Map FlowIds to (DSCP value, packet count) pairs + std::map> m_flowDscpMap; #ifdef NS3_MTP - std::atomic m_lock; + std::atomic m_lock; #endif }; @@ -113,7 +114,7 @@ private: * \param t2 the first operand * \returns true if the operands are equal */ -bool operator < (const Ipv6FlowClassifier::FiveTuple &t1, const Ipv6FlowClassifier::FiveTuple &t2); +bool operator<(const Ipv6FlowClassifier::FiveTuple& t1, const Ipv6FlowClassifier::FiveTuple& t2); /** * \brief Equal to operator. @@ -122,8 +123,7 @@ bool operator < (const Ipv6FlowClassifier::FiveTuple &t1, const Ipv6FlowClassifi * \param t2 the first operand * \returns true if the operands are equal */ -bool operator == (const Ipv6FlowClassifier::FiveTuple &t1, const Ipv6FlowClassifier::FiveTuple &t2); - +bool operator==(const Ipv6FlowClassifier::FiveTuple& t1, const Ipv6FlowClassifier::FiveTuple& t2); } // namespace ns3 diff --git a/src/flow-monitor/model/ipv6-flow-probe.cc b/src/flow-monitor/model/ipv6-flow-probe.cc index d5a293369..c506b53e3 100644 --- a/src/flow-monitor/model/ipv6-flow-probe.cc +++ b/src/flow-monitor/model/ipv6-flow-probe.cc @@ -20,18 +20,20 @@ // #include "ns3/ipv6-flow-probe.h" -#include "ns3/ipv6-flow-classifier.h" -#include "ns3/node.h" -#include "ns3/packet.h" -#include "ns3/flow-monitor.h" -#include "ns3/log.h" -#include "ns3/pointer.h" + #include "ns3/config.h" #include "ns3/flow-id-tag.h" +#include "ns3/flow-monitor.h" +#include "ns3/ipv6-flow-classifier.h" +#include "ns3/log.h" +#include "ns3/node.h" +#include "ns3/packet.h" +#include "ns3/pointer.h" -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("Ipv6FlowProbe"); +NS_LOG_COMPONENT_DEFINE("Ipv6FlowProbe"); ////////////////////////////////////// // Ipv6FlowProbeTag class implementation // @@ -48,272 +50,303 @@ NS_LOG_COMPONENT_DEFINE ("Ipv6FlowProbe"); */ class Ipv6FlowProbeTag : public Tag { -public: - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (); - TypeId GetInstanceTypeId () const override; - uint32_t GetSerializedSize () const override; - void Serialize (TagBuffer buf) const override; - void Deserialize (TagBuffer buf) override; - void Print (std::ostream &os) const override; - Ipv6FlowProbeTag (); - /** - * \brief Consructor - * \param flowId the flow identifier - * \param packetId the packet identifier - * \param packetSize the packet size - */ - Ipv6FlowProbeTag (uint32_t flowId, uint32_t packetId, uint32_t packetSize); - /** - * \brief Set the flow identifier - * \param flowId the flow identifier - */ - void SetFlowId (uint32_t flowId); - /** - * \brief Set the packet identifier - * \param packetId the packet identifier - */ - void SetPacketId (uint32_t packetId); - /** - * \brief Set the packet size - * \param packetSize the packet size - */ - void SetPacketSize (uint32_t packetSize); - /** - * \brief Set the flow identifier - * \returns the flow identifier - */ - uint32_t GetFlowId () const; - /** - * \brief Set the packet identifier - * \returns the packet identifier - */ - uint32_t GetPacketId () const; - /** - * \brief Get the packet size - * \returns the packet size - */ - uint32_t GetPacketSize () const; -private: - uint32_t m_flowId; //!< flow identifier - uint32_t m_packetId; //!< packet identifier - uint32_t m_packetSize; //!< packet size + public: + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(); + TypeId GetInstanceTypeId() const override; + uint32_t GetSerializedSize() const override; + void Serialize(TagBuffer buf) const override; + void Deserialize(TagBuffer buf) override; + void Print(std::ostream& os) const override; + Ipv6FlowProbeTag(); + /** + * \brief Consructor + * \param flowId the flow identifier + * \param packetId the packet identifier + * \param packetSize the packet size + */ + Ipv6FlowProbeTag(uint32_t flowId, uint32_t packetId, uint32_t packetSize); + /** + * \brief Set the flow identifier + * \param flowId the flow identifier + */ + void SetFlowId(uint32_t flowId); + /** + * \brief Set the packet identifier + * \param packetId the packet identifier + */ + void SetPacketId(uint32_t packetId); + /** + * \brief Set the packet size + * \param packetSize the packet size + */ + void SetPacketSize(uint32_t packetSize); + /** + * \brief Set the flow identifier + * \returns the flow identifier + */ + uint32_t GetFlowId() const; + /** + * \brief Set the packet identifier + * \returns the packet identifier + */ + uint32_t GetPacketId() const; + /** + * \brief Get the packet size + * \returns the packet size + */ + uint32_t GetPacketSize() const; + private: + uint32_t m_flowId; //!< flow identifier + uint32_t m_packetId; //!< packet identifier + uint32_t m_packetSize; //!< packet size }; TypeId -Ipv6FlowProbeTag::GetTypeId () +Ipv6FlowProbeTag::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv6FlowProbeTag") - .SetParent () - .SetGroupName ("FlowMonitor") - .AddConstructor () - ; - return tid; + static TypeId tid = TypeId("ns3::Ipv6FlowProbeTag") + .SetParent() + .SetGroupName("FlowMonitor") + .AddConstructor(); + return tid; } + TypeId -Ipv6FlowProbeTag::GetInstanceTypeId () const +Ipv6FlowProbeTag::GetInstanceTypeId() const { - return GetTypeId (); + return GetTypeId(); } + uint32_t -Ipv6FlowProbeTag::GetSerializedSize () const +Ipv6FlowProbeTag::GetSerializedSize() const { - return 4 + 4 + 4; + return 4 + 4 + 4; } + void -Ipv6FlowProbeTag::Serialize (TagBuffer buf) const +Ipv6FlowProbeTag::Serialize(TagBuffer buf) const { - buf.WriteU32 (m_flowId); - buf.WriteU32 (m_packetId); - buf.WriteU32 (m_packetSize); + buf.WriteU32(m_flowId); + buf.WriteU32(m_packetId); + buf.WriteU32(m_packetSize); } + void -Ipv6FlowProbeTag::Deserialize (TagBuffer buf) +Ipv6FlowProbeTag::Deserialize(TagBuffer buf) { - m_flowId = buf.ReadU32 (); - m_packetId = buf.ReadU32 (); - m_packetSize = buf.ReadU32 (); + m_flowId = buf.ReadU32(); + m_packetId = buf.ReadU32(); + m_packetSize = buf.ReadU32(); } + void -Ipv6FlowProbeTag::Print (std::ostream &os) const +Ipv6FlowProbeTag::Print(std::ostream& os) const { - os << "FlowId=" << m_flowId; - os << "PacketId=" << m_packetId; - os << "PacketSize=" << m_packetSize; + os << "FlowId=" << m_flowId; + os << "PacketId=" << m_packetId; + os << "PacketSize=" << m_packetSize; } -Ipv6FlowProbeTag::Ipv6FlowProbeTag () - : Tag () + +Ipv6FlowProbeTag::Ipv6FlowProbeTag() + : Tag() { } -Ipv6FlowProbeTag::Ipv6FlowProbeTag (uint32_t flowId, uint32_t packetId, uint32_t packetSize) - : Tag (), m_flowId (flowId), m_packetId (packetId), m_packetSize (packetSize) +Ipv6FlowProbeTag::Ipv6FlowProbeTag(uint32_t flowId, uint32_t packetId, uint32_t packetSize) + : Tag(), + m_flowId(flowId), + m_packetId(packetId), + m_packetSize(packetSize) { } void -Ipv6FlowProbeTag::SetFlowId (uint32_t id) +Ipv6FlowProbeTag::SetFlowId(uint32_t id) { - m_flowId = id; + m_flowId = id; } + void -Ipv6FlowProbeTag::SetPacketId (uint32_t id) +Ipv6FlowProbeTag::SetPacketId(uint32_t id) { - m_packetId = id; + m_packetId = id; } + void -Ipv6FlowProbeTag::SetPacketSize (uint32_t size) +Ipv6FlowProbeTag::SetPacketSize(uint32_t size) { - m_packetSize = size; + m_packetSize = size; } + uint32_t -Ipv6FlowProbeTag::GetFlowId () const +Ipv6FlowProbeTag::GetFlowId() const { - return m_flowId; + return m_flowId; } + uint32_t -Ipv6FlowProbeTag::GetPacketId () const +Ipv6FlowProbeTag::GetPacketId() const { - return m_packetId; + return m_packetId; } + uint32_t -Ipv6FlowProbeTag::GetPacketSize () const +Ipv6FlowProbeTag::GetPacketSize() const { - return m_packetSize; + return m_packetSize; } //////////////////////////////////////// // Ipv6FlowProbe class implementation // //////////////////////////////////////// -Ipv6FlowProbe::Ipv6FlowProbe (Ptr monitor, - Ptr classifier, - Ptr node) - : FlowProbe (monitor), - m_classifier (classifier) +Ipv6FlowProbe::Ipv6FlowProbe(Ptr monitor, + Ptr classifier, + Ptr node) + : FlowProbe(monitor), + m_classifier(classifier) { - NS_LOG_FUNCTION (this << node->GetId ()); + NS_LOG_FUNCTION(this << node->GetId()); - Ptr ipv6 = node->GetObject (); + Ptr ipv6 = node->GetObject(); - if (!ipv6->TraceConnectWithoutContext ("SendOutgoing", - MakeCallback (&Ipv6FlowProbe::SendOutgoingLogger, Ptr (this)))) + if (!ipv6->TraceConnectWithoutContext( + "SendOutgoing", + MakeCallback(&Ipv6FlowProbe::SendOutgoingLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!ipv6->TraceConnectWithoutContext ("UnicastForward", - MakeCallback (&Ipv6FlowProbe::ForwardLogger, Ptr (this)))) + if (!ipv6->TraceConnectWithoutContext( + "UnicastForward", + MakeCallback(&Ipv6FlowProbe::ForwardLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!ipv6->TraceConnectWithoutContext ("LocalDeliver", - MakeCallback (&Ipv6FlowProbe::ForwardUpLogger, Ptr (this)))) + if (!ipv6->TraceConnectWithoutContext( + "LocalDeliver", + MakeCallback(&Ipv6FlowProbe::ForwardUpLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - if (!ipv6->TraceConnectWithoutContext ("Drop", - MakeCallback (&Ipv6FlowProbe::DropLogger, Ptr (this)))) + if (!ipv6->TraceConnectWithoutContext( + "Drop", + MakeCallback(&Ipv6FlowProbe::DropLogger, Ptr(this)))) { - NS_FATAL_ERROR ("trace fail"); + NS_FATAL_ERROR("trace fail"); } - std::ostringstream qd; - qd << "/NodeList/" << node->GetId () << "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Drop"; - Config::ConnectWithoutContextFailSafe (qd.str (), MakeCallback (&Ipv6FlowProbe::QueueDiscDropLogger, Ptr (this))); + std::ostringstream qd; + qd << "/NodeList/" << node->GetId() << "/$ns3::TrafficControlLayer/RootQueueDiscList/*/Drop"; + Config::ConnectWithoutContextFailSafe( + qd.str(), + MakeCallback(&Ipv6FlowProbe::QueueDiscDropLogger, Ptr(this))); - // code copied from point-to-point-helper.cc - std::ostringstream oss; - oss << "/NodeList/" << node->GetId () << "/DeviceList/*/TxQueue/Drop"; - Config::ConnectWithoutContextFailSafe (oss.str (), MakeCallback (&Ipv6FlowProbe::QueueDropLogger, Ptr (this))); + // code copied from point-to-point-helper.cc + std::ostringstream oss; + oss << "/NodeList/" << node->GetId() << "/DeviceList/*/TxQueue/Drop"; + Config::ConnectWithoutContextFailSafe( + oss.str(), + MakeCallback(&Ipv6FlowProbe::QueueDropLogger, Ptr(this))); } -NS_OBJECT_ENSURE_REGISTERED (Ipv6FlowProbeTag); +NS_OBJECT_ENSURE_REGISTERED(Ipv6FlowProbeTag); /* static */ TypeId -Ipv6FlowProbe::GetTypeId () +Ipv6FlowProbe::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv6FlowProbe") - .SetParent () - .SetGroupName ("FlowMonitor") - // No AddConstructor because this class has no default constructor. - ; + static TypeId tid = + TypeId("ns3::Ipv6FlowProbe").SetParent().SetGroupName("FlowMonitor") + // No AddConstructor because this class has no default constructor. + ; - return tid; + return tid; } -Ipv6FlowProbe::~Ipv6FlowProbe () +Ipv6FlowProbe::~Ipv6FlowProbe() { } void -Ipv6FlowProbe::DoDispose () +Ipv6FlowProbe::DoDispose() { - FlowProbe::DoDispose (); + FlowProbe::DoDispose(); } void -Ipv6FlowProbe::SendOutgoingLogger (const Ipv6Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv6FlowProbe::SendOutgoingLogger(const Ipv6Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - FlowId flowId; - FlowPacketId packetId; + FlowId flowId; + FlowPacketId packetId; - if (m_classifier->Classify (ipHeader, ipPayload, &flowId, &packetId)) + if (m_classifier->Classify(ipHeader, ipPayload, &flowId, &packetId)) { - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportFirstTx ("<ReportFirstTx (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportFirstTx (" << this << ", " << flowId << ", " << packetId << ", " << size + << "); " << ipHeader << *ipPayload); + m_flowMonitor->ReportFirstTx(this, flowId, packetId, size); - // tag the packet with the flow id and packet id, so that the packet can be identified even - // when Ipv6Header is not accessible at some non-IPv6 protocol layer - Ipv6FlowProbeTag fTag (flowId, packetId, size); - ipPayload->AddByteTag (fTag); + // tag the packet with the flow id and packet id, so that the packet can be identified even + // when Ipv6Header is not accessible at some non-IPv6 protocol layer + Ipv6FlowProbeTag fTag(flowId, packetId, size); + ipPayload->AddByteTag(fTag); } } void -Ipv6FlowProbe::ForwardLogger (const Ipv6Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv6FlowProbe::ForwardLogger(const Ipv6Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - Ipv6FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv6FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportForwarding ("<ReportForwarding (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportForwarding (" << this << ", " << flowId << ", " << packetId << ", " + << size << ");"); + m_flowMonitor->ReportForwarding(this, flowId, packetId, size); } } void -Ipv6FlowProbe::ForwardUpLogger (const Ipv6Header &ipHeader, Ptr ipPayload, uint32_t interface) +Ipv6FlowProbe::ForwardUpLogger(const Ipv6Header& ipHeader, + Ptr ipPayload, + uint32_t interface) { - Ipv6FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv6FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("ReportLastRx ("<ReportLastRx (this, flowId, packetId, size); + uint32_t size = (ipPayload->GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("ReportLastRx (" << this << ", " << flowId << ", " << packetId << ", " << size + << ");"); + m_flowMonitor->ReportLastRx(this, flowId, packetId, size); } } void -Ipv6FlowProbe::DropLogger (const Ipv6Header &ipHeader, Ptr ipPayload, - Ipv6L3Protocol::DropReason reason, Ptr ipv6, uint32_t ifIndex) +Ipv6FlowProbe::DropLogger(const Ipv6Header& ipHeader, + Ptr ipPayload, + Ipv6L3Protocol::DropReason reason, + Ptr ipv6, + uint32_t ifIndex) { #if 0 switch (reason) @@ -333,107 +366,104 @@ Ipv6FlowProbe::DropLogger (const Ipv6Header &ipHeader, Ptr ipPaylo } #endif - Ipv6FlowProbeTag fTag; - bool found = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv6FlowProbeTag fTag; + bool found = ipPayload->FindFirstMatchingByteTag(fTag); - if (found) + if (found) { - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); - uint32_t size = (ipPayload->GetSize () + ipHeader.GetSerializedSize ()); - NS_LOG_DEBUG ("Drop ("<GetSize() + ipHeader.GetSerializedSize()); + NS_LOG_DEBUG("Drop (" << this << ", " << flowId << ", " << packetId << ", " << size << ", " + << reason << ", destIp=" << ipHeader.GetDestination() << "); " + << "HDR: " << ipHeader << " PKT: " << *ipPayload); - DropReason myReason; + DropReason myReason; - - switch (reason) + switch (reason) { case Ipv6L3Protocol::DROP_TTL_EXPIRED: - myReason = DROP_TTL_EXPIRE; - NS_LOG_DEBUG ("DROP_TTL_EXPIRE"); - break; + myReason = DROP_TTL_EXPIRE; + NS_LOG_DEBUG("DROP_TTL_EXPIRE"); + break; case Ipv6L3Protocol::DROP_NO_ROUTE: - myReason = DROP_NO_ROUTE; - NS_LOG_DEBUG ("DROP_NO_ROUTE"); - break; + myReason = DROP_NO_ROUTE; + NS_LOG_DEBUG("DROP_NO_ROUTE"); + break; case Ipv6L3Protocol::DROP_INTERFACE_DOWN: - myReason = DROP_INTERFACE_DOWN; - NS_LOG_DEBUG ("DROP_INTERFACE_DOWN"); - break; + myReason = DROP_INTERFACE_DOWN; + NS_LOG_DEBUG("DROP_INTERFACE_DOWN"); + break; case Ipv6L3Protocol::DROP_ROUTE_ERROR: - myReason = DROP_ROUTE_ERROR; - NS_LOG_DEBUG ("DROP_ROUTE_ERROR"); - break; + myReason = DROP_ROUTE_ERROR; + NS_LOG_DEBUG("DROP_ROUTE_ERROR"); + break; case Ipv6L3Protocol::DROP_UNKNOWN_PROTOCOL: - myReason = DROP_UNKNOWN_PROTOCOL; - NS_LOG_DEBUG ("DROP_UNKNOWN_PROTOCOL"); - break; + myReason = DROP_UNKNOWN_PROTOCOL; + NS_LOG_DEBUG("DROP_UNKNOWN_PROTOCOL"); + break; case Ipv6L3Protocol::DROP_UNKNOWN_OPTION: - myReason = DROP_UNKNOWN_OPTION; - NS_LOG_DEBUG ("DROP_UNKNOWN_OPTION"); - break; + myReason = DROP_UNKNOWN_OPTION; + NS_LOG_DEBUG("DROP_UNKNOWN_OPTION"); + break; case Ipv6L3Protocol::DROP_MALFORMED_HEADER: - myReason = DROP_MALFORMED_HEADER; - NS_LOG_DEBUG ("DROP_MALFORMED_HEADER"); - break; + myReason = DROP_MALFORMED_HEADER; + NS_LOG_DEBUG("DROP_MALFORMED_HEADER"); + break; case Ipv6L3Protocol::DROP_FRAGMENT_TIMEOUT: - myReason = DROP_FRAGMENT_TIMEOUT; - NS_LOG_DEBUG ("DROP_FRAGMENT_TIMEOUT"); - break; + myReason = DROP_FRAGMENT_TIMEOUT; + NS_LOG_DEBUG("DROP_FRAGMENT_TIMEOUT"); + break; default: - myReason = DROP_INVALID_REASON; - NS_FATAL_ERROR ("Unexpected drop reason code " << reason); + myReason = DROP_INVALID_REASON; + NS_FATAL_ERROR("Unexpected drop reason code " << reason); } - m_flowMonitor->ReportDrop (this, flowId, packetId, size, myReason); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, myReason); } } void -Ipv6FlowProbe::QueueDropLogger (Ptr ipPayload) +Ipv6FlowProbe::QueueDropLogger(Ptr ipPayload) { - Ipv6FlowProbeTag fTag; - bool tagFound = ipPayload->FindFirstMatchingByteTag (fTag); + Ipv6FlowProbeTag fTag; + bool tagFound = ipPayload->FindFirstMatchingByteTag(fTag); - if (!tagFound) + if (!tagFound) { - return; + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); - uint32_t size = fTag.GetPacketSize (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); + uint32_t size = fTag.GetPacketSize(); - NS_LOG_DEBUG ("Drop ("<ReportDrop (this, flowId, packetId, size, DROP_QUEUE); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, DROP_QUEUE); } void -Ipv6FlowProbe::QueueDiscDropLogger (Ptr item) +Ipv6FlowProbe::QueueDiscDropLogger(Ptr item) { - Ipv6FlowProbeTag fTag; - bool tagFound = item->GetPacket ()->FindFirstMatchingByteTag (fTag); + Ipv6FlowProbeTag fTag; + bool tagFound = item->GetPacket()->FindFirstMatchingByteTag(fTag); - if (!tagFound) + if (!tagFound) { - return; + return; } - FlowId flowId = fTag.GetFlowId (); - FlowPacketId packetId = fTag.GetPacketId (); - uint32_t size = fTag.GetPacketSize (); + FlowId flowId = fTag.GetFlowId(); + FlowPacketId packetId = fTag.GetPacketId(); + uint32_t size = fTag.GetPacketSize(); - NS_LOG_DEBUG ("Drop ("<ReportDrop (this, flowId, packetId, size, DROP_QUEUE_DISC); + m_flowMonitor->ReportDrop(this, flowId, packetId, size, DROP_QUEUE_DISC); } } // namespace ns3 - - diff --git a/src/internet/model/global-route-manager-impl.cc b/src/internet/model/global-route-manager-impl.cc index edf43821f..c749f2625 100644 --- a/src/internet/model/global-route-manager-impl.cc +++ b/src/internet/model/global-route-manager-impl.cc @@ -22,26 +22,30 @@ * of the quagga 0.99.7/src/ospfd/ospf_spf.c code which was ported here */ -#include -#include -#include -#include -#include -#include "ns3/assert.h" -#include "ns3/fatal-error.h" -#include "ns3/log.h" -#include "ns3/node-list.h" -#include "ns3/ipv4.h" -#include "ns3/ipv4-routing-protocol.h" -#include "ns3/ipv4-list-routing.h" -#include "global-router-interface.h" #include "global-route-manager-impl.h" + #include "candidate-queue.h" +#include "global-router-interface.h" #include "ipv4-global-routing.h" -namespace ns3 { +#include "ns3/assert.h" +#include "ns3/fatal-error.h" +#include "ns3/ipv4-list-routing.h" +#include "ns3/ipv4-routing-protocol.h" +#include "ns3/ipv4.h" +#include "ns3/log.h" +#include "ns3/node-list.h" -NS_LOG_COMPONENT_DEFINE ("GlobalRouteManagerImpl"); +#include +#include +#include +#include +#include + +namespace ns3 +{ + +NS_LOG_COMPONENT_DEFINE("GlobalRouteManagerImpl"); /** * \brief Stream insertion operator. @@ -51,31 +55,31 @@ NS_LOG_COMPONENT_DEFINE ("GlobalRouteManagerImpl"); * \returns the reference to the output stream */ std::ostream& -operator<< (std::ostream& os, const SPFVertex::NodeExit_t& exit) +operator<<(std::ostream& os, const SPFVertex::NodeExit_t& exit) { - os << "(" << exit.first << " ," << exit.second << ")"; - return os; + os << "(" << exit.first << " ," << exit.second << ")"; + return os; } std::ostream& -operator<< (std::ostream& os, const SPFVertex::ListOfSPFVertex_t& vs) +operator<<(std::ostream& os, const SPFVertex::ListOfSPFVertex_t& vs) { - typedef SPFVertex::ListOfSPFVertex_t::const_iterator CIter_t; - os << "{"; - for (CIter_t iter = vs.begin (); iter != vs.end ();) + typedef SPFVertex::ListOfSPFVertex_t::const_iterator CIter_t; + os << "{"; + for (CIter_t iter = vs.begin(); iter != vs.end();) { - os << (*iter)->m_vertexId; - if (++iter != vs.end ()) + os << (*iter)->m_vertexId; + if (++iter != vs.end()) { - os << ", "; + os << ", "; } - else + else { - break; + break; } } - os << "}"; - return os; + os << "}"; + return os; } // --------------------------------------------------------------------------- @@ -84,336 +88,338 @@ operator<< (std::ostream& os, const SPFVertex::ListOfSPFVertex_t& vs) // // --------------------------------------------------------------------------- -SPFVertex::SPFVertex () : - m_vertexType (VertexUnknown), - m_vertexId ("255.255.255.255"), - m_lsa (nullptr), - m_distanceFromRoot (SPF_INFINITY), - m_rootOif (SPF_INFINITY), - m_nextHop ("0.0.0.0"), - m_parents (), - m_children (), - m_vertexProcessed (false) +SPFVertex::SPFVertex() + : m_vertexType(VertexUnknown), + m_vertexId("255.255.255.255"), + m_lsa(nullptr), + m_distanceFromRoot(SPF_INFINITY), + m_rootOif(SPF_INFINITY), + m_nextHop("0.0.0.0"), + m_parents(), + m_children(), + m_vertexProcessed(false) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -SPFVertex::SPFVertex (GlobalRoutingLSA* lsa) : - m_vertexId (lsa->GetLinkStateId ()), - m_lsa (lsa), - m_distanceFromRoot (SPF_INFINITY), - m_rootOif (SPF_INFINITY), - m_nextHop ("0.0.0.0"), - m_parents (), - m_children (), - m_vertexProcessed (false) +SPFVertex::SPFVertex(GlobalRoutingLSA* lsa) + : m_vertexId(lsa->GetLinkStateId()), + m_lsa(lsa), + m_distanceFromRoot(SPF_INFINITY), + m_rootOif(SPF_INFINITY), + m_nextHop("0.0.0.0"), + m_parents(), + m_children(), + m_vertexProcessed(false) { - NS_LOG_FUNCTION (this << lsa); + NS_LOG_FUNCTION(this << lsa); - if (lsa->GetLSType () == GlobalRoutingLSA::RouterLSA) + if (lsa->GetLSType() == GlobalRoutingLSA::RouterLSA) { - NS_LOG_LOGIC ("Setting m_vertexType to VertexRouter"); - m_vertexType = SPFVertex::VertexRouter; + NS_LOG_LOGIC("Setting m_vertexType to VertexRouter"); + m_vertexType = SPFVertex::VertexRouter; } - else if (lsa->GetLSType () == GlobalRoutingLSA::NetworkLSA) + else if (lsa->GetLSType() == GlobalRoutingLSA::NetworkLSA) { - NS_LOG_LOGIC ("Setting m_vertexType to VertexNetwork"); - m_vertexType = SPFVertex::VertexNetwork; + NS_LOG_LOGIC("Setting m_vertexType to VertexNetwork"); + m_vertexType = SPFVertex::VertexNetwork; } } -SPFVertex::~SPFVertex () +SPFVertex::~SPFVertex() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - NS_LOG_LOGIC ("Children vertices - " << m_children); - NS_LOG_LOGIC ("Parent verteices - " << m_parents); + NS_LOG_LOGIC("Children vertices - " << m_children); + NS_LOG_LOGIC("Parent verteices - " << m_parents); - // find this node from all its parents and remove the entry of this node - // from all its parents - for (ListOfSPFVertex_t::iterator piter = m_parents.begin (); - piter != m_parents.end (); - piter++) + // find this node from all its parents and remove the entry of this node + // from all its parents + for (ListOfSPFVertex_t::iterator piter = m_parents.begin(); piter != m_parents.end(); piter++) { - // remove the current vertex from its parent's children list. Check - // if the size of the list is reduced, or the child<->parent relation - // is not bidirectional - uint32_t orgCount = (*piter)->m_children.size (); - (*piter)->m_children.remove (this); - uint32_t newCount = (*piter)->m_children.size (); - if (orgCount > newCount) + // remove the current vertex from its parent's children list. Check + // if the size of the list is reduced, or the child<->parent relation + // is not bidirectional + uint32_t orgCount = (*piter)->m_children.size(); + (*piter)->m_children.remove(this); + uint32_t newCount = (*piter)->m_children.size(); + if (orgCount > newCount) { - NS_ASSERT_MSG (orgCount > newCount, "Unable to find the current vertex from its parents --- impossible!"); + NS_ASSERT_MSG(orgCount > newCount, + "Unable to find the current vertex from its parents --- impossible!"); } } - // delete children - while (m_children.size () > 0) + // delete children + while (m_children.size() > 0) { - // pop out children one by one. Some children may disappear - // when deleting some other children in the list. As a result, - // it is necessary to use pop to walk through all children, instead - // of using iterator. - // - // Note that m_children.pop_front () is not necessary as this - // p is removed from the children list when p is deleted - SPFVertex* p = m_children.front (); - // 'p' == 0, this child is already deleted by its other parent - if (p == nullptr) + // pop out children one by one. Some children may disappear + // when deleting some other children in the list. As a result, + // it is necessary to use pop to walk through all children, instead + // of using iterator. + // + // Note that m_children.pop_front () is not necessary as this + // p is removed from the children list when p is deleted + SPFVertex* p = m_children.front(); + // 'p' == 0, this child is already deleted by its other parent + if (p == nullptr) { - continue; + continue; } - NS_LOG_LOGIC ("Parent vertex-" << m_vertexId << " deleting its child vertex-" << p->GetVertexId ()); - delete p; - p = nullptr; + NS_LOG_LOGIC("Parent vertex-" << m_vertexId << " deleting its child vertex-" + << p->GetVertexId()); + delete p; + p = nullptr; } - m_children.clear (); - // delete parents - m_parents.clear (); - // delete root exit direction - m_ecmpRootExits.clear (); + m_children.clear(); + // delete parents + m_parents.clear(); + // delete root exit direction + m_ecmpRootExits.clear(); - NS_LOG_LOGIC ("Vertex-" << m_vertexId << " completed deleted"); + NS_LOG_LOGIC("Vertex-" << m_vertexId << " completed deleted"); } void -SPFVertex::SetVertexType (SPFVertex::VertexType type) +SPFVertex::SetVertexType(SPFVertex::VertexType type) { - NS_LOG_FUNCTION (this << type); - m_vertexType = type; + NS_LOG_FUNCTION(this << type); + m_vertexType = type; } SPFVertex::VertexType -SPFVertex::GetVertexType () const +SPFVertex::GetVertexType() const { - NS_LOG_FUNCTION (this); - return m_vertexType; + NS_LOG_FUNCTION(this); + return m_vertexType; } void -SPFVertex::SetVertexId (Ipv4Address id) +SPFVertex::SetVertexId(Ipv4Address id) { - NS_LOG_FUNCTION (this << id); - m_vertexId = id; + NS_LOG_FUNCTION(this << id); + m_vertexId = id; } Ipv4Address -SPFVertex::GetVertexId () const +SPFVertex::GetVertexId() const { - NS_LOG_FUNCTION (this); - return m_vertexId; + NS_LOG_FUNCTION(this); + return m_vertexId; } void -SPFVertex::SetLSA (GlobalRoutingLSA* lsa) +SPFVertex::SetLSA(GlobalRoutingLSA* lsa) { - NS_LOG_FUNCTION (this << lsa); - m_lsa = lsa; + NS_LOG_FUNCTION(this << lsa); + m_lsa = lsa; } GlobalRoutingLSA* -SPFVertex::GetLSA () const +SPFVertex::GetLSA() const { - NS_LOG_FUNCTION (this); - return m_lsa; + NS_LOG_FUNCTION(this); + return m_lsa; } void -SPFVertex::SetDistanceFromRoot (uint32_t distance) +SPFVertex::SetDistanceFromRoot(uint32_t distance) { - NS_LOG_FUNCTION (this << distance); - m_distanceFromRoot = distance; + NS_LOG_FUNCTION(this << distance); + m_distanceFromRoot = distance; } uint32_t -SPFVertex::GetDistanceFromRoot () const +SPFVertex::GetDistanceFromRoot() const { - NS_LOG_FUNCTION (this); - return m_distanceFromRoot; + NS_LOG_FUNCTION(this); + return m_distanceFromRoot; } void -SPFVertex::SetParent (SPFVertex* parent) +SPFVertex::SetParent(SPFVertex* parent) { - NS_LOG_FUNCTION (this << parent); + NS_LOG_FUNCTION(this << parent); - // always maintain only one parent when using setter/getter methods - m_parents.clear (); - m_parents.push_back (parent); + // always maintain only one parent when using setter/getter methods + m_parents.clear(); + m_parents.push_back(parent); } SPFVertex* -SPFVertex::GetParent (uint32_t i) const +SPFVertex::GetParent(uint32_t i) const { - NS_LOG_FUNCTION (this << i); + NS_LOG_FUNCTION(this << i); - // If the index i is out-of-range, return 0 and do nothing - if (m_parents.size () <= i) + // If the index i is out-of-range, return 0 and do nothing + if (m_parents.size() <= i) { - NS_LOG_LOGIC ("Index to SPFVertex's parent is out-of-range."); - return nullptr; + NS_LOG_LOGIC("Index to SPFVertex's parent is out-of-range."); + return nullptr; } - ListOfSPFVertex_t::const_iterator iter = m_parents.begin (); - while (i-- > 0) + ListOfSPFVertex_t::const_iterator iter = m_parents.begin(); + while (i-- > 0) { - iter++; + iter++; } - return *iter; + return *iter; } void -SPFVertex::MergeParent (const SPFVertex* v) +SPFVertex::MergeParent(const SPFVertex* v) { - NS_LOG_FUNCTION (this << v); + NS_LOG_FUNCTION(this << v); - NS_LOG_LOGIC ("Before merge, list of parents = " << m_parents); - // combine the two lists first, and then remove any duplicated after - m_parents.insert (m_parents.end (), - v->m_parents.begin (), v->m_parents.end ()); - // remove duplication - m_parents.sort (); - m_parents.unique (); - NS_LOG_LOGIC ("After merge, list of parents = " << m_parents); + NS_LOG_LOGIC("Before merge, list of parents = " << m_parents); + // combine the two lists first, and then remove any duplicated after + m_parents.insert(m_parents.end(), v->m_parents.begin(), v->m_parents.end()); + // remove duplication + m_parents.sort(); + m_parents.unique(); + NS_LOG_LOGIC("After merge, list of parents = " << m_parents); } void -SPFVertex::SetRootExitDirection (Ipv4Address nextHop, int32_t id) +SPFVertex::SetRootExitDirection(Ipv4Address nextHop, int32_t id) { - NS_LOG_FUNCTION (this << nextHop << id); + NS_LOG_FUNCTION(this << nextHop << id); - // always maintain only one root's exit - m_ecmpRootExits.clear (); - m_ecmpRootExits.emplace_back(nextHop, id); - // update the following in order to be backward compatitable with - // GetNextHop and GetOutgoingInterface methods - m_nextHop = nextHop; - m_rootOif = id; + // always maintain only one root's exit + m_ecmpRootExits.clear(); + m_ecmpRootExits.emplace_back(nextHop, id); + // update the following in order to be backward compatitable with + // GetNextHop and GetOutgoingInterface methods + m_nextHop = nextHop; + m_rootOif = id; } void -SPFVertex::SetRootExitDirection (SPFVertex::NodeExit_t exit) +SPFVertex::SetRootExitDirection(SPFVertex::NodeExit_t exit) { - NS_LOG_FUNCTION (this << exit); - SetRootExitDirection (exit.first, exit.second); + NS_LOG_FUNCTION(this << exit); + SetRootExitDirection(exit.first, exit.second); } SPFVertex::NodeExit_t -SPFVertex::GetRootExitDirection (uint32_t i) const +SPFVertex::GetRootExitDirection(uint32_t i) const { - NS_LOG_FUNCTION (this << i); - typedef ListOfNodeExit_t::const_iterator CIter_t; + NS_LOG_FUNCTION(this << i); + typedef ListOfNodeExit_t::const_iterator CIter_t; - NS_ASSERT_MSG (i < m_ecmpRootExits.size (), "Index out-of-range when accessing SPFVertex::m_ecmpRootExits!"); - CIter_t iter = m_ecmpRootExits.begin (); - while (i-- > 0) { iter++; } + NS_ASSERT_MSG(i < m_ecmpRootExits.size(), + "Index out-of-range when accessing SPFVertex::m_ecmpRootExits!"); + CIter_t iter = m_ecmpRootExits.begin(); + while (i-- > 0) + { + iter++; + } - return *iter; + return *iter; } SPFVertex::NodeExit_t -SPFVertex::GetRootExitDirection () const +SPFVertex::GetRootExitDirection() const { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - NS_ASSERT_MSG (m_ecmpRootExits.size () <= 1, "Assumed there is at most one exit from the root to this vertex"); - return GetRootExitDirection (0); + NS_ASSERT_MSG(m_ecmpRootExits.size() <= 1, + "Assumed there is at most one exit from the root to this vertex"); + return GetRootExitDirection(0); } void -SPFVertex::MergeRootExitDirections (const SPFVertex* vertex) +SPFVertex::MergeRootExitDirections(const SPFVertex* vertex) { - NS_LOG_FUNCTION (this << vertex); + NS_LOG_FUNCTION(this << vertex); - // obtain the external list of exit directions - // - // Append the external list into 'this' and remove duplication afterward - const ListOfNodeExit_t& extList = vertex->m_ecmpRootExits; - m_ecmpRootExits.insert (m_ecmpRootExits.end (), - extList.begin (), extList.end ()); - m_ecmpRootExits.sort (); - m_ecmpRootExits.unique (); + // obtain the external list of exit directions + // + // Append the external list into 'this' and remove duplication afterward + const ListOfNodeExit_t& extList = vertex->m_ecmpRootExits; + m_ecmpRootExits.insert(m_ecmpRootExits.end(), extList.begin(), extList.end()); + m_ecmpRootExits.sort(); + m_ecmpRootExits.unique(); } void -SPFVertex::InheritAllRootExitDirections (const SPFVertex* vertex) +SPFVertex::InheritAllRootExitDirections(const SPFVertex* vertex) { - NS_LOG_FUNCTION (this << vertex); + NS_LOG_FUNCTION(this << vertex); - // discard all exit direction currently associated with this vertex, - // and copy all the exit directions from the given vertex - if (m_ecmpRootExits.size () > 0) + // discard all exit direction currently associated with this vertex, + // and copy all the exit directions from the given vertex + if (m_ecmpRootExits.size() > 0) { - NS_LOG_WARN ("x root exit directions in this vertex are going to be discarded"); + NS_LOG_WARN("x root exit directions in this vertex are going to be discarded"); } - m_ecmpRootExits.clear (); - m_ecmpRootExits.insert (m_ecmpRootExits.end (), - vertex->m_ecmpRootExits.begin (), vertex->m_ecmpRootExits.end ()); + m_ecmpRootExits.clear(); + m_ecmpRootExits.insert(m_ecmpRootExits.end(), + vertex->m_ecmpRootExits.begin(), + vertex->m_ecmpRootExits.end()); } uint32_t -SPFVertex::GetNRootExitDirections () const +SPFVertex::GetNRootExitDirections() const { - NS_LOG_FUNCTION (this); - return m_ecmpRootExits.size (); + NS_LOG_FUNCTION(this); + return m_ecmpRootExits.size(); } uint32_t -SPFVertex::GetNChildren () const +SPFVertex::GetNChildren() const { - NS_LOG_FUNCTION (this); - return m_children.size (); + NS_LOG_FUNCTION(this); + return m_children.size(); } SPFVertex* -SPFVertex::GetChild (uint32_t n) const +SPFVertex::GetChild(uint32_t n) const { - NS_LOG_FUNCTION (this << n); - uint32_t j = 0; + NS_LOG_FUNCTION(this << n); + uint32_t j = 0; - for ( ListOfSPFVertex_t::const_iterator i = m_children.begin (); - i != m_children.end (); - i++, j++) + for (ListOfSPFVertex_t::const_iterator i = m_children.begin(); i != m_children.end(); i++, j++) { - if (j == n) + if (j == n) { - return *i; + return *i; } } - NS_ASSERT_MSG (false, "Index out of range."); - return nullptr; + NS_ASSERT_MSG(false, "Index out of range."); + return nullptr; } uint32_t -SPFVertex::AddChild (SPFVertex* child) +SPFVertex::AddChild(SPFVertex* child) { - NS_LOG_FUNCTION (this << child); - m_children.push_back (child); - return m_children.size (); + NS_LOG_FUNCTION(this << child); + m_children.push_back(child); + return m_children.size(); } void -SPFVertex::SetVertexProcessed (bool value) +SPFVertex::SetVertexProcessed(bool value) { - NS_LOG_FUNCTION (this << value); - m_vertexProcessed = value; + NS_LOG_FUNCTION(this << value); + m_vertexProcessed = value; } bool -SPFVertex::IsVertexProcessed () const +SPFVertex::IsVertexProcessed() const { - NS_LOG_FUNCTION (this); - return m_vertexProcessed; + NS_LOG_FUNCTION(this); + return m_vertexProcessed; } void -SPFVertex::ClearVertexProcessed () +SPFVertex::ClearVertexProcessed() { - NS_LOG_FUNCTION (this); - for (uint32_t i = 0; i < this->GetNChildren (); i++) + NS_LOG_FUNCTION(this); + for (uint32_t i = 0; i < this->GetNChildren(); i++) { - this->GetChild (i)->ClearVertexProcessed (); + this->GetChild(i)->ClearVertexProcessed(); } - this->SetVertexProcessed (false); + this->SetVertexProcessed(false); } // --------------------------------------------------------------------------- @@ -422,115 +428,114 @@ SPFVertex::ClearVertexProcessed () // // --------------------------------------------------------------------------- -GlobalRouteManagerLSDB::GlobalRouteManagerLSDB () - : - m_database (), - m_extdatabase () +GlobalRouteManagerLSDB::GlobalRouteManagerLSDB() + : m_database(), + m_extdatabase() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } -GlobalRouteManagerLSDB::~GlobalRouteManagerLSDB () +GlobalRouteManagerLSDB::~GlobalRouteManagerLSDB() { - NS_LOG_FUNCTION (this); - LSDBMap_t::iterator i; - for (i= m_database.begin (); i!= m_database.end (); i++) + NS_LOG_FUNCTION(this); + LSDBMap_t::iterator i; + for (i = m_database.begin(); i != m_database.end(); i++) { - NS_LOG_LOGIC ("free LSA"); - GlobalRoutingLSA* temp = i->second; - delete temp; + NS_LOG_LOGIC("free LSA"); + GlobalRoutingLSA* temp = i->second; + delete temp; } - for (uint32_t j = 0; j < m_extdatabase.size (); j++) + for (uint32_t j = 0; j < m_extdatabase.size(); j++) { - NS_LOG_LOGIC ("free ASexternalLSA"); - GlobalRoutingLSA* temp = m_extdatabase.at (j); - delete temp; + NS_LOG_LOGIC("free ASexternalLSA"); + GlobalRoutingLSA* temp = m_extdatabase.at(j); + delete temp; } - NS_LOG_LOGIC ("clear map"); - m_database.clear (); + NS_LOG_LOGIC("clear map"); + m_database.clear(); } void -GlobalRouteManagerLSDB::Initialize () +GlobalRouteManagerLSDB::Initialize() { - NS_LOG_FUNCTION (this); - LSDBMap_t::iterator i; - for (i= m_database.begin (); i!= m_database.end (); i++) + NS_LOG_FUNCTION(this); + LSDBMap_t::iterator i; + for (i = m_database.begin(); i != m_database.end(); i++) { - GlobalRoutingLSA* temp = i->second; - temp->SetStatus (GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED); + GlobalRoutingLSA* temp = i->second; + temp->SetStatus(GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED); } } void -GlobalRouteManagerLSDB::Insert (Ipv4Address addr, GlobalRoutingLSA* lsa) +GlobalRouteManagerLSDB::Insert(Ipv4Address addr, GlobalRoutingLSA* lsa) { - NS_LOG_FUNCTION (this << addr << lsa); - if (lsa->GetLSType () == GlobalRoutingLSA::ASExternalLSAs) + NS_LOG_FUNCTION(this << addr << lsa); + if (lsa->GetLSType() == GlobalRoutingLSA::ASExternalLSAs) { - m_extdatabase.push_back (lsa); + m_extdatabase.push_back(lsa); } - else + else { - m_database.insert (LSDBPair_t (addr, lsa)); + m_database.insert(LSDBPair_t(addr, lsa)); } } GlobalRoutingLSA* -GlobalRouteManagerLSDB::GetExtLSA (uint32_t index) const +GlobalRouteManagerLSDB::GetExtLSA(uint32_t index) const { - NS_LOG_FUNCTION (this << index); - return m_extdatabase.at (index); + NS_LOG_FUNCTION(this << index); + return m_extdatabase.at(index); } uint32_t -GlobalRouteManagerLSDB::GetNumExtLSAs () const +GlobalRouteManagerLSDB::GetNumExtLSAs() const { - NS_LOG_FUNCTION (this); - return m_extdatabase.size (); + NS_LOG_FUNCTION(this); + return m_extdatabase.size(); } GlobalRoutingLSA* -GlobalRouteManagerLSDB::GetLSA (Ipv4Address addr) const +GlobalRouteManagerLSDB::GetLSA(Ipv4Address addr) const { - NS_LOG_FUNCTION (this << addr); -// -// Look up an LSA by its address. -// - LSDBMap_t::const_iterator i; - for (i= m_database.begin (); i!= m_database.end (); i++) + NS_LOG_FUNCTION(this << addr); + // + // Look up an LSA by its address. + // + LSDBMap_t::const_iterator i; + for (i = m_database.begin(); i != m_database.end(); i++) { - if (i->first == addr) + if (i->first == addr) { - return i->second; + return i->second; } } - return nullptr; + return nullptr; } GlobalRoutingLSA* -GlobalRouteManagerLSDB::GetLSAByLinkData (Ipv4Address addr) const +GlobalRouteManagerLSDB::GetLSAByLinkData(Ipv4Address addr) const { - NS_LOG_FUNCTION (this << addr); -// -// Look up an LSA by its address. -// - LSDBMap_t::const_iterator i; - for (i= m_database.begin (); i!= m_database.end (); i++) + NS_LOG_FUNCTION(this << addr); + // + // Look up an LSA by its address. + // + LSDBMap_t::const_iterator i; + for (i = m_database.begin(); i != m_database.end(); i++) { - GlobalRoutingLSA* temp = i->second; -// Iterate among temp's Link Records - for (uint32_t j = 0; j < temp->GetNLinkRecords (); j++) + GlobalRoutingLSA* temp = i->second; + // Iterate among temp's Link Records + for (uint32_t j = 0; j < temp->GetNLinkRecords(); j++) { - GlobalRoutingLinkRecord *lr = temp->GetLinkRecord (j); - if ( lr->GetLinkType () == GlobalRoutingLinkRecord::TransitNetwork && - lr->GetLinkData () == addr) + GlobalRoutingLinkRecord* lr = temp->GetLinkRecord(j); + if (lr->GetLinkType() == GlobalRoutingLinkRecord::TransitNetwork && + lr->GetLinkData() == addr) { - return temp; + return temp; } } } - return nullptr; + return nullptr; } // --------------------------------------------------------------------------- @@ -539,66 +544,65 @@ GlobalRouteManagerLSDB::GetLSAByLinkData (Ipv4Address addr) const // // --------------------------------------------------------------------------- -GlobalRouteManagerImpl::GlobalRouteManagerImpl () - : - m_spfroot (nullptr) +GlobalRouteManagerImpl::GlobalRouteManagerImpl() + : m_spfroot(nullptr) { - NS_LOG_FUNCTION (this); - m_lsdb = new GlobalRouteManagerLSDB (); + NS_LOG_FUNCTION(this); + m_lsdb = new GlobalRouteManagerLSDB(); } -GlobalRouteManagerImpl::~GlobalRouteManagerImpl () +GlobalRouteManagerImpl::~GlobalRouteManagerImpl() { - NS_LOG_FUNCTION (this); - if (m_lsdb) + NS_LOG_FUNCTION(this); + if (m_lsdb) { - delete m_lsdb; + delete m_lsdb; } } void -GlobalRouteManagerImpl::DebugUseLsdb (GlobalRouteManagerLSDB* lsdb) +GlobalRouteManagerImpl::DebugUseLsdb(GlobalRouteManagerLSDB* lsdb) { - NS_LOG_FUNCTION (this << lsdb); - if (m_lsdb) + NS_LOG_FUNCTION(this << lsdb); + if (m_lsdb) { - delete m_lsdb; + delete m_lsdb; } - m_lsdb = lsdb; + m_lsdb = lsdb; } void -GlobalRouteManagerImpl::DeleteGlobalRoutes () +GlobalRouteManagerImpl::DeleteGlobalRoutes() { - NS_LOG_FUNCTION (this); - NodeList::Iterator listEnd = NodeList::End (); - for (NodeList::Iterator i = NodeList::Begin (); i != listEnd; i++) + NS_LOG_FUNCTION(this); + NodeList::Iterator listEnd = NodeList::End(); + for (NodeList::Iterator i = NodeList::Begin(); i != listEnd; i++) { - Ptr node = *i; - Ptr router = node->GetObject (); - if (!router) + Ptr node = *i; + Ptr router = node->GetObject(); + if (!router) { - continue; + continue; } - Ptr gr = router->GetRoutingProtocol (); - uint32_t j = 0; - uint32_t nRoutes = gr->GetNRoutes (); - NS_LOG_LOGIC ("Deleting " << gr->GetNRoutes ()<< " routes from node " << node->GetId ()); - // Each time we delete route 0, the route index shifts downward - // We can delete all routes if we delete the route numbered 0 - // nRoutes times - for (j = 0; j < nRoutes; j++) + Ptr gr = router->GetRoutingProtocol(); + uint32_t j = 0; + uint32_t nRoutes = gr->GetNRoutes(); + NS_LOG_LOGIC("Deleting " << gr->GetNRoutes() << " routes from node " << node->GetId()); + // Each time we delete route 0, the route index shifts downward + // We can delete all routes if we delete the route numbered 0 + // nRoutes times + for (j = 0; j < nRoutes; j++) { - NS_LOG_LOGIC ("Deleting global route " << j << " from node " << node->GetId ()); - gr->RemoveRoute (0); + NS_LOG_LOGIC("Deleting global route " << j << " from node " << node->GetId()); + gr->RemoveRoute(0); } - NS_LOG_LOGIC ("Deleted " << j << " global routes from node "<< node->GetId ()); + NS_LOG_LOGIC("Deleted " << j << " global routes from node " << node->GetId()); } - if (m_lsdb) + if (m_lsdb) { - NS_LOG_LOGIC ("Deleting LSDB, creating new one"); - delete m_lsdb; - m_lsdb = new GlobalRouteManagerLSDB (); + NS_LOG_LOGIC("Deleting LSDB, creating new one"); + delete m_lsdb; + m_lsdb = new GlobalRouteManagerLSDB(); } } @@ -612,51 +616,51 @@ GlobalRouteManagerImpl::DeleteGlobalRoutes () // ultimately be computed. // void -GlobalRouteManagerImpl::BuildGlobalRoutingDatabase () +GlobalRouteManagerImpl::BuildGlobalRoutingDatabase() { - NS_LOG_FUNCTION (this); -// -// Walk the list of nodes looking for the GlobalRouter Interface. Nodes with -// global router interfaces are, not too surprisingly, our routers. -// - NodeList::Iterator listEnd = NodeList::End (); - for (NodeList::Iterator i = NodeList::Begin (); i != listEnd; i++) + NS_LOG_FUNCTION(this); + // + // Walk the list of nodes looking for the GlobalRouter Interface. Nodes with + // global router interfaces are, not too surprisingly, our routers. + // + NodeList::Iterator listEnd = NodeList::End(); + for (NodeList::Iterator i = NodeList::Begin(); i != listEnd; i++) { - Ptr node = *i; + Ptr node = *i; - Ptr rtr = node->GetObject (); -// -// Ignore nodes that aren't participating in routing. -// - if (!rtr) + Ptr rtr = node->GetObject(); + // + // Ignore nodes that aren't participating in routing. + // + if (!rtr) { - continue; + continue; } -// -// You must call DiscoverLSAs () before trying to use any routing info or to -// update LSAs. DiscoverLSAs () drives the process of discovering routes in -// the GlobalRouter. Afterward, you may use GetNumLSAs (), which is a very -// computationally inexpensive call. If you call GetNumLSAs () before calling -// DiscoverLSAs () will get zero as the number since no routes have been -// found. -// - Ptr grouting = rtr->GetRoutingProtocol (); - uint32_t numLSAs = rtr->DiscoverLSAs (); - NS_LOG_LOGIC ("Found " << numLSAs << " LSAs"); + // + // You must call DiscoverLSAs () before trying to use any routing info or to + // update LSAs. DiscoverLSAs () drives the process of discovering routes in + // the GlobalRouter. Afterward, you may use GetNumLSAs (), which is a very + // computationally inexpensive call. If you call GetNumLSAs () before calling + // DiscoverLSAs () will get zero as the number since no routes have been + // found. + // + Ptr grouting = rtr->GetRoutingProtocol(); + uint32_t numLSAs = rtr->DiscoverLSAs(); + NS_LOG_LOGIC("Found " << numLSAs << " LSAs"); - for (uint32_t j = 0; j < numLSAs; ++j) + for (uint32_t j = 0; j < numLSAs; ++j) { - GlobalRoutingLSA* lsa = new GlobalRoutingLSA (); -// -// This is the call to actually fetch a Link State Advertisement from the -// router. -// - rtr->GetLSA (j, *lsa); - NS_LOG_LOGIC (*lsa); -// -// Write the newly discovered link state advertisement to the database. -// - m_lsdb->Insert (lsa->GetLinkStateId (), lsa); + GlobalRoutingLSA* lsa = new GlobalRoutingLSA(); + // + // This is the call to actually fetch a Link State Advertisement from the + // router. + // + rtr->GetLSA(j, *lsa); + NS_LOG_LOGIC(*lsa); + // + // Write the newly discovered link state advertisement to the database. + // + m_lsdb->Insert(lsa->GetLinkStateId(), lsa); } } } @@ -695,43 +699,42 @@ GlobalRouteManagerImpl::BuildGlobalRoutingDatabase () // list becomes empty. // void -GlobalRouteManagerImpl::InitializeRoutes () +GlobalRouteManagerImpl::InitializeRoutes() { - NS_LOG_FUNCTION (this); -// -// Walk the list of nodes in the system. -// - NS_LOG_INFO ("About to start SPF calculation"); - NodeList::Iterator listEnd = NodeList::End (); - for (NodeList::Iterator i = NodeList::Begin (); i != listEnd; i++) + NS_LOG_FUNCTION(this); + // + // Walk the list of nodes in the system. + // + NS_LOG_INFO("About to start SPF calculation"); + NodeList::Iterator listEnd = NodeList::End(); + for (NodeList::Iterator i = NodeList::Begin(); i != listEnd; i++) { - Ptr node = *i; -// -// Look for the GlobalRouter interface that indicates that the node is -// participating in routing. -// - Ptr rtr = - node->GetObject (); + Ptr node = *i; + // + // Look for the GlobalRouter interface that indicates that the node is + // participating in routing. + // + Ptr rtr = node->GetObject(); #ifdef NS3_MPI - uint32_t systemId = Simulator::GetSystemId (); - // Ignore nodes that are not assigned to our systemId (distributed sim) - if (node->GetSystemId () != systemId) + uint32_t systemId = Simulator::GetSystemId(); + // Ignore nodes that are not assigned to our systemId (distributed sim) + if (node->GetSystemId() != systemId) { - continue; + continue; } #endif -// -// if the node has a global router interface, then run the global routing -// algorithms. -// - if (rtr && rtr->GetNumLSAs () ) + // + // if the node has a global router interface, then run the global routing + // algorithms. + // + if (rtr && rtr->GetNumLSAs()) { - SPFCalculate (rtr->GetRouterId ()); + SPFCalculate(rtr->GetRouterId()); } } - NS_LOG_INFO ("Finished SPF calculation"); + NS_LOG_INFO("Finished SPF calculation"); } // @@ -748,226 +751,220 @@ GlobalRouteManagerImpl::InitializeRoutes () // vertex already on the candidate list, store the new (lower) cost. // void -GlobalRouteManagerImpl::SPFNext (SPFVertex* v, CandidateQueue& candidate) +GlobalRouteManagerImpl::SPFNext(SPFVertex* v, CandidateQueue& candidate) { - NS_LOG_FUNCTION (this << v << &candidate); + NS_LOG_FUNCTION(this << v << &candidate); - SPFVertex* w = nullptr; - GlobalRoutingLSA* w_lsa = nullptr; - GlobalRoutingLinkRecord *l = nullptr; - uint32_t distance = 0; - uint32_t numRecordsInVertex = 0; -// -// V points to a Router-LSA or Network-LSA -// Loop over the links in router LSA or attached routers in Network LSA -// - if (v->GetVertexType () == SPFVertex::VertexRouter) + SPFVertex* w = nullptr; + GlobalRoutingLSA* w_lsa = nullptr; + GlobalRoutingLinkRecord* l = nullptr; + uint32_t distance = 0; + uint32_t numRecordsInVertex = 0; + // + // V points to a Router-LSA or Network-LSA + // Loop over the links in router LSA or attached routers in Network LSA + // + if (v->GetVertexType() == SPFVertex::VertexRouter) { - numRecordsInVertex = v->GetLSA ()->GetNLinkRecords (); + numRecordsInVertex = v->GetLSA()->GetNLinkRecords(); } - if (v->GetVertexType () == SPFVertex::VertexNetwork) + if (v->GetVertexType() == SPFVertex::VertexNetwork) { - numRecordsInVertex = v->GetLSA ()->GetNAttachedRouters (); + numRecordsInVertex = v->GetLSA()->GetNAttachedRouters(); } - for (uint32_t i = 0; i < numRecordsInVertex; i++) + for (uint32_t i = 0; i < numRecordsInVertex; i++) { -// Get w_lsa: In case of V is Router-LSA - if (v->GetVertexType () == SPFVertex::VertexRouter) + // Get w_lsa: In case of V is Router-LSA + if (v->GetVertexType() == SPFVertex::VertexRouter) { - NS_LOG_LOGIC ("Examining link " << i << " of " << - v->GetVertexId () << "'s " << - v->GetLSA ()->GetNLinkRecords () << " link records"); -// -// (a) If this is a link to a stub network, examine the next link in V's LSA. -// Links to stub networks will be considered in the second stage of the -// shortest path calculation. -// - l = v->GetLSA ()->GetLinkRecord (i); - NS_ASSERT (l != nullptr); - if (l->GetLinkType () == GlobalRoutingLinkRecord::StubNetwork) + NS_LOG_LOGIC("Examining link " << i << " of " << v->GetVertexId() << "'s " + << v->GetLSA()->GetNLinkRecords() << " link records"); + // + // (a) If this is a link to a stub network, examine the next link in V's LSA. + // Links to stub networks will be considered in the second stage of the + // shortest path calculation. + // + l = v->GetLSA()->GetLinkRecord(i); + NS_ASSERT(l != nullptr); + if (l->GetLinkType() == GlobalRoutingLinkRecord::StubNetwork) { - NS_LOG_LOGIC ("Found a Stub record to " << l->GetLinkId ()); - continue; + NS_LOG_LOGIC("Found a Stub record to " << l->GetLinkId()); + continue; } -// -// (b) Otherwise, W is a transit vertex (router or transit network). Look up -// the vertex W's LSA (router-LSA or network-LSA) in Area A's link state -// database. -// - if (l->GetLinkType () == GlobalRoutingLinkRecord::PointToPoint) + // + // (b) Otherwise, W is a transit vertex (router or transit network). Look up + // the vertex W's LSA (router-LSA or network-LSA) in Area A's link state + // database. + // + if (l->GetLinkType() == GlobalRoutingLinkRecord::PointToPoint) { -// -// Lookup the link state advertisement of the new link -- we call it in -// the link state database. -// - w_lsa = m_lsdb->GetLSA (l->GetLinkId ()); - NS_ASSERT (w_lsa); - NS_LOG_LOGIC ("Found a P2P record from " << - v->GetVertexId () << " to " << w_lsa->GetLinkStateId ()); + // + // Lookup the link state advertisement of the new link -- we call it in + // the link state database. + // + w_lsa = m_lsdb->GetLSA(l->GetLinkId()); + NS_ASSERT(w_lsa); + NS_LOG_LOGIC("Found a P2P record from " << v->GetVertexId() << " to " + << w_lsa->GetLinkStateId()); } - else if (l->GetLinkType () == - GlobalRoutingLinkRecord::TransitNetwork) + else if (l->GetLinkType() == GlobalRoutingLinkRecord::TransitNetwork) { - w_lsa = m_lsdb->GetLSA (l->GetLinkId ()); - NS_ASSERT (w_lsa); - NS_LOG_LOGIC ("Found a Transit record from " << - v->GetVertexId () << " to " << w_lsa->GetLinkStateId ()); + w_lsa = m_lsdb->GetLSA(l->GetLinkId()); + NS_ASSERT(w_lsa); + NS_LOG_LOGIC("Found a Transit record from " << v->GetVertexId() << " to " + << w_lsa->GetLinkStateId()); } - else + else { - NS_ASSERT_MSG (0, "illegal Link Type"); + NS_ASSERT_MSG(0, "illegal Link Type"); } } -// Get w_lsa: In case of V is Network-LSA - if (v->GetVertexType () == SPFVertex::VertexNetwork) + // Get w_lsa: In case of V is Network-LSA + if (v->GetVertexType() == SPFVertex::VertexNetwork) { - w_lsa = m_lsdb->GetLSAByLinkData - (v->GetLSA ()->GetAttachedRouter (i)); - if (!w_lsa) + w_lsa = m_lsdb->GetLSAByLinkData(v->GetLSA()->GetAttachedRouter(i)); + if (!w_lsa) { - continue; + continue; } - NS_LOG_LOGIC ("Found a Network LSA from " << - v->GetVertexId () << " to " << w_lsa->GetLinkStateId ()); + NS_LOG_LOGIC("Found a Network LSA from " << v->GetVertexId() << " to " + << w_lsa->GetLinkStateId()); } -// Note: w_lsa at this point may be either RouterLSA or NetworkLSA -// -// (c) If vertex W is already on the shortest-path tree, examine the next -// link in the LSA. -// -// If the link is to a router that is already in the shortest path first tree -// then we have it covered -- ignore it. -// - if (w_lsa->GetStatus () == GlobalRoutingLSA::LSA_SPF_IN_SPFTREE) + // Note: w_lsa at this point may be either RouterLSA or NetworkLSA + // + // (c) If vertex W is already on the shortest-path tree, examine the next + // link in the LSA. + // + // If the link is to a router that is already in the shortest path first tree + // then we have it covered -- ignore it. + // + if (w_lsa->GetStatus() == GlobalRoutingLSA::LSA_SPF_IN_SPFTREE) { - NS_LOG_LOGIC ("Skipping -> LSA "<< - w_lsa->GetLinkStateId () << " already in SPF tree"); - continue; + NS_LOG_LOGIC("Skipping -> LSA " << w_lsa->GetLinkStateId() << " already in SPF tree"); + continue; } -// -// (d) Calculate the link state cost D of the resulting path from the root to -// vertex W. D is equal to the sum of the link state cost of the (already -// calculated) shortest path to vertex V and the advertised cost of the link -// between vertices V and W. -// - if (v->GetLSA ()->GetLSType () == GlobalRoutingLSA::RouterLSA) + // + // (d) Calculate the link state cost D of the resulting path from the root to + // vertex W. D is equal to the sum of the link state cost of the (already + // calculated) shortest path to vertex V and the advertised cost of the link + // between vertices V and W. + // + if (v->GetLSA()->GetLSType() == GlobalRoutingLSA::RouterLSA) { - NS_ASSERT (l != nullptr); - distance = v->GetDistanceFromRoot () + l->GetMetric (); + NS_ASSERT(l != nullptr); + distance = v->GetDistanceFromRoot() + l->GetMetric(); } - else + else { - distance = v->GetDistanceFromRoot (); + distance = v->GetDistanceFromRoot(); } - NS_LOG_LOGIC ("Considering w_lsa " << w_lsa->GetLinkStateId ()); + NS_LOG_LOGIC("Considering w_lsa " << w_lsa->GetLinkStateId()); -// Is there already vertex w in candidate list? - if (w_lsa->GetStatus () == GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED) + // Is there already vertex w in candidate list? + if (w_lsa->GetStatus() == GlobalRoutingLSA::LSA_SPF_NOT_EXPLORED) { -// Calculate nexthop to w -// We need to figure out how to actually get to the new router represented -// by . This will (among other things) find the next hop address to send -// packets destined for this network to, and also find the outbound interface -// used to forward the packets. + // Calculate nexthop to w + // We need to figure out how to actually get to the new router represented + // by . This will (among other things) find the next hop address to send + // packets destined for this network to, and also find the outbound interface + // used to forward the packets. -// prepare vertex w - w = new SPFVertex (w_lsa); - if (SPFNexthopCalculation (v, w, l, distance)) + // prepare vertex w + w = new SPFVertex(w_lsa); + if (SPFNexthopCalculation(v, w, l, distance)) { - w_lsa->SetStatus (GlobalRoutingLSA::LSA_SPF_CANDIDATE); -// -// Push this new vertex onto the priority queue (ordered by distance from the -// root node). -// - candidate.Push (w); - NS_LOG_LOGIC ("Pushing " << - w->GetVertexId () << ", parent vertexId: " << - v->GetVertexId () << ", distance: " << - w->GetDistanceFromRoot ()); + w_lsa->SetStatus(GlobalRoutingLSA::LSA_SPF_CANDIDATE); + // + // Push this new vertex onto the priority queue (ordered by distance from the + // root node). + // + candidate.Push(w); + NS_LOG_LOGIC("Pushing " << w->GetVertexId() + << ", parent vertexId: " << v->GetVertexId() + << ", distance: " << w->GetDistanceFromRoot()); } - else + else { - NS_ASSERT_MSG (0, - "SPFNexthopCalculation never " - << "return false, but it does now!"); + NS_ASSERT_MSG(0, + "SPFNexthopCalculation never " << "return false, but it does now!"); } } - else if (w_lsa->GetStatus () == GlobalRoutingLSA::LSA_SPF_CANDIDATE) + else if (w_lsa->GetStatus() == GlobalRoutingLSA::LSA_SPF_CANDIDATE) { -// -// We have already considered the link represented by . What wse have to -// do now is to decide if this new router represents a route with a shorter -// distance metric. -// -// So, locate the vertex in the candidate queue and take a look at the -// distance. + // + // We have already considered the link represented by . What wse have to + // do now is to decide if this new router represents a route with a shorter + // distance metric. + // + // So, locate the vertex in the candidate queue and take a look at the + // distance. -/* (quagga-0.98.6) W is already on the candidate list; call it cw. -* Compare the previously calculated cost (cw->distance) -* with the cost we just determined (w->distance) to see -* if we've found a shorter path. -*/ - SPFVertex* cw; - cw = candidate.Find (w_lsa->GetLinkStateId ()); - if (cw->GetDistanceFromRoot () < distance) + /* (quagga-0.98.6) W is already on the candidate list; call it cw. + * Compare the previously calculated cost (cw->distance) + * with the cost we just determined (w->distance) to see + * if we've found a shorter path. + */ + SPFVertex* cw; + cw = candidate.Find(w_lsa->GetLinkStateId()); + if (cw->GetDistanceFromRoot() < distance) { -// -// This is not a shorter path, so don't do anything. -// - continue; + // + // This is not a shorter path, so don't do anything. + // + continue; } - else if (cw->GetDistanceFromRoot () == distance) + else if (cw->GetDistanceFromRoot() == distance) { -// -// This path is one with an equal cost. -// - NS_LOG_LOGIC ("Equal cost multiple paths found."); + // + // This path is one with an equal cost. + // + NS_LOG_LOGIC("Equal cost multiple paths found."); -// At this point, there are two instances 'w' and 'cw' of the -// same vertex, the vertex that is currently being considered -// for adding into the shortest path tree. 'w' is the instance -// as seen from the root via vertex 'v', and 'cw' is the instance -// as seen from the root via some other vertices other than 'v'. -// These two instances are being merged in the following code. -// In particular, the parent nodes, the next hops, and the root's -// output interfaces of the two instances are being merged. -// -// Note that this is functionally equivalent to calling -// ospf_nexthop_merge (cw->nexthop, w->nexthop) in quagga-0.98.6 -// (ospf_spf.c::859), although the detail implementation -// is very different from quagga (blame ns3::GlobalRouteManagerImpl) + // At this point, there are two instances 'w' and 'cw' of the + // same vertex, the vertex that is currently being considered + // for adding into the shortest path tree. 'w' is the instance + // as seen from the root via vertex 'v', and 'cw' is the instance + // as seen from the root via some other vertices other than 'v'. + // These two instances are being merged in the following code. + // In particular, the parent nodes, the next hops, and the root's + // output interfaces of the two instances are being merged. + // + // Note that this is functionally equivalent to calling + // ospf_nexthop_merge (cw->nexthop, w->nexthop) in quagga-0.98.6 + // (ospf_spf.c::859), although the detail implementation + // is very different from quagga (blame ns3::GlobalRouteManagerImpl) -// prepare vertex w - w = new SPFVertex (w_lsa); - SPFNexthopCalculation (v, w, l, distance); - cw->MergeRootExitDirections (w); - cw->MergeParent (w); -// SPFVertexAddParent (w) is necessary as the destructor of -// SPFVertex checks if the vertex and its parent is linked -// bidirectionally - SPFVertexAddParent (w); - delete w; + // prepare vertex w + w = new SPFVertex(w_lsa); + SPFNexthopCalculation(v, w, l, distance); + cw->MergeRootExitDirections(w); + cw->MergeParent(w); + // SPFVertexAddParent (w) is necessary as the destructor of + // SPFVertex checks if the vertex and its parent is linked + // bidirectionally + SPFVertexAddParent(w); + delete w; } - else // cw->GetDistanceFromRoot () > w->GetDistanceFromRoot () + else // cw->GetDistanceFromRoot () > w->GetDistanceFromRoot () { -// -// this path represents a new, lower-cost path to (the vertex we found in -// the current link record of the link state advertisement of the current root -// (vertex ) -// -// N.B. the nexthop_calculation is conditional, if it finds a valid nexthop -// it will call spf_add_parents, which will flush the old parents -// - if (SPFNexthopCalculation (v, cw, l, distance)) + // + // this path represents a new, lower-cost path to (the vertex we found in + // the current link record of the link state advertisement of the current root + // (vertex ) + // + // N.B. the nexthop_calculation is conditional, if it finds a valid nexthop + // it will call spf_add_parents, which will flush the old parents + // + if (SPFNexthopCalculation(v, cw, l, distance)) { -// -// If we've changed the cost to get to the vertex represented by , we -// must reorder the priority queue keyed to that cost. -// - candidate.Reorder (); + // + // If we've changed the cost to get to the vertex represented by , we + // must reorder the priority queue keyed to that cost. + // + candidate.Reorder(); } } // new lower cost path found } // end W is already on the candidate list @@ -985,179 +982,175 @@ GlobalRouteManagerImpl::SPFNext (SPFVertex* v, CandidateQueue& candidate) // For now, this is greatly simplified from the quagga code // int -GlobalRouteManagerImpl::SPFNexthopCalculation ( - SPFVertex* v, - SPFVertex* w, - GlobalRoutingLinkRecord* l, - uint32_t distance) +GlobalRouteManagerImpl::SPFNexthopCalculation(SPFVertex* v, + SPFVertex* w, + GlobalRoutingLinkRecord* l, + uint32_t distance) { - NS_LOG_FUNCTION (this << v << w << l << distance); -// -// If w is a NetworkVertex, l should be null -/* - if (w->GetVertexType () == SPFVertex::VertexNetwork && l) - { - NS_ASSERT_MSG (0, "Error: SPFNexthopCalculation parameter problem"); - } -*/ - -// -// The vertex m_spfroot is a distinguished vertex representing the node at -// the root of the calculations. That is, it is the node for which we are -// calculating the routes. -// -// There are two distinct cases for calculating the next hop information. -// First, if we're considering a hop from the root to an "adjacent" network -// (one that is on the other side of a point-to-point link connected to the -// root), then we need to store the information needed to forward down that -// link. The second case is if the network is not directly adjacent. In that -// case we need to use the forwarding information from the vertex on the path -// to the destination that is directly adjacent [node 1] in both cases of the -// diagram below. -// -// (1) [root] -> [point-to-point] -> [node 1] -// (2) [root] -> [point-to-point] -> [node 1] -> [point-to-point] -> [node 2] -// -// We call the propagation of next hop information down vertices of a path -// "inheriting" the next hop information. -// -// The point-to-point link information is only useful in this calculation when -// we are examining the root node. -// - if (v == m_spfroot) - { -// -// In this case is the root node, which means it is the starting point -// for the packets forwarded by that node. This also means that the next hop -// address of packets headed for some arbitrary off-network destination must -// be the destination at the other end of one of the links off of the root -// node if this root node is a router. We then need to see if this node -// is a router. -// - if (w->GetVertexType () == SPFVertex::VertexRouter) + NS_LOG_FUNCTION(this << v << w << l << distance); + // + // If w is a NetworkVertex, l should be null + /* + if (w->GetVertexType () == SPFVertex::VertexNetwork && l) { -// -// In the case of point-to-point links, the link data field (m_linkData) of a -// Global Router Link Record contains the local IP address. If we look at the -// link record describing the link from the perspecive of (the remote -// node from the viewpoint of ) back to the root node, we can discover the -// IP address of the router to which is adjacent. This is a distinguished -// address -- the next hop address to get from to and all networks -// accessed through that path. -// -// SPFGetNextLink () is a little odd. used in this way it is just going to -// return the link record describing the link from to . Think of it as -// SPFGetLink. -// - NS_ASSERT (l); - GlobalRoutingLinkRecord *linkRemote = nullptr; - linkRemote = SPFGetNextLink (w, v, linkRemote); -// -// At this point, is the Global Router Link Record describing the point- -// to point link from to from the perspective of ; and -// is the Global Router Link Record describing that same link from the -// perspective of (back to ). Now we can just copy the next hop -// address from the m_linkData member variable. -// -// The next hop member variable we put in has the sense "in order to get -// from the root node to the host represented by vertex , you have to send -// the packet to the next hop address specified in w->m_nextHop. -// - Ipv4Address nextHop = linkRemote->GetLinkData (); -// -// Now find the outgoing interface corresponding to the point to point link -// from the perspective of -- remember that is the link "from" -// "to" . -// - uint32_t outIf = FindOutgoingInterfaceId (l->GetLinkData ()); + NS_ASSERT_MSG (0, "Error: SPFNexthopCalculation parameter problem"); + } + */ - w->SetRootExitDirection (nextHop, outIf); - w->SetDistanceFromRoot (distance); - w->SetParent (v); - NS_LOG_LOGIC ("Next hop from " << - v->GetVertexId () << " to " << w->GetVertexId () << - " goes through next hop " << nextHop << - " via outgoing interface " << outIf << - " with distance " << distance); - } // end W is a router vertes - else + // + // The vertex m_spfroot is a distinguished vertex representing the node at + // the root of the calculations. That is, it is the node for which we are + // calculating the routes. + // + // There are two distinct cases for calculating the next hop information. + // First, if we're considering a hop from the root to an "adjacent" network + // (one that is on the other side of a point-to-point link connected to the + // root), then we need to store the information needed to forward down that + // link. The second case is if the network is not directly adjacent. In that + // case we need to use the forwarding information from the vertex on the path + // to the destination that is directly adjacent [node 1] in both cases of the + // diagram below. + // + // (1) [root] -> [point-to-point] -> [node 1] + // (2) [root] -> [point-to-point] -> [node 1] -> [point-to-point] -> [node 2] + // + // We call the propagation of next hop information down vertices of a path + // "inheriting" the next hop information. + // + // The point-to-point link information is only useful in this calculation when + // we are examining the root node. + // + if (v == m_spfroot) + { + // + // In this case is the root node, which means it is the starting point + // for the packets forwarded by that node. This also means that the next hop + // address of packets headed for some arbitrary off-network destination must + // be the destination at the other end of one of the links off of the root + // node if this root node is a router. We then need to see if this node + // is a router. + // + if (w->GetVertexType() == SPFVertex::VertexRouter) { - NS_ASSERT (w->GetVertexType () == SPFVertex::VertexNetwork); -// W is a directly connected network; no next hop is required - GlobalRoutingLSA* w_lsa = w->GetLSA (); - NS_ASSERT (w_lsa->GetLSType () == GlobalRoutingLSA::NetworkLSA); -// Find outgoing interface ID for this network - uint32_t outIf = FindOutgoingInterfaceId (w_lsa->GetLinkStateId (), - w_lsa->GetNetworkLSANetworkMask () ); -// Set the next hop to 0.0.0.0 meaning "not exist" - Ipv4Address nextHop = Ipv4Address::GetZero (); - w->SetRootExitDirection (nextHop, outIf); - w->SetDistanceFromRoot (distance); - w->SetParent (v); - NS_LOG_LOGIC ("Next hop from " << - v->GetVertexId () << " to network " << w->GetVertexId () << - " via outgoing interface " << outIf << - " with distance " << distance); - return 1; + // + // In the case of point-to-point links, the link data field (m_linkData) of a + // Global Router Link Record contains the local IP address. If we look at the + // link record describing the link from the perspecive of (the remote + // node from the viewpoint of ) back to the root node, we can discover the + // IP address of the router to which is adjacent. This is a distinguished + // address -- the next hop address to get from to and all networks + // accessed through that path. + // + // SPFGetNextLink () is a little odd. used in this way it is just going to + // return the link record describing the link from to . Think of it as + // SPFGetLink. + // + NS_ASSERT(l); + GlobalRoutingLinkRecord* linkRemote = nullptr; + linkRemote = SPFGetNextLink(w, v, linkRemote); + // + // At this point, is the Global Router Link Record describing the point- + // to point link from to from the perspective of ; and + // is the Global Router Link Record describing that same link from the + // perspective of (back to ). Now we can just copy the next hop + // address from the m_linkData member variable. + // + // The next hop member variable we put in has the sense "in order to get + // from the root node to the host represented by vertex , you have to send + // the packet to the next hop address specified in w->m_nextHop. + // + Ipv4Address nextHop = linkRemote->GetLinkData(); + // + // Now find the outgoing interface corresponding to the point to point link + // from the perspective of -- remember that is the link "from" + // "to" . + // + uint32_t outIf = FindOutgoingInterfaceId(l->GetLinkData()); + + w->SetRootExitDirection(nextHop, outIf); + w->SetDistanceFromRoot(distance); + w->SetParent(v); + NS_LOG_LOGIC("Next hop from " << v->GetVertexId() << " to " << w->GetVertexId() + << " goes through next hop " << nextHop + << " via outgoing interface " << outIf + << " with distance " << distance); + } // end W is a router vertes + else + { + NS_ASSERT(w->GetVertexType() == SPFVertex::VertexNetwork); + // W is a directly connected network; no next hop is required + GlobalRoutingLSA* w_lsa = w->GetLSA(); + NS_ASSERT(w_lsa->GetLSType() == GlobalRoutingLSA::NetworkLSA); + // Find outgoing interface ID for this network + uint32_t outIf = + FindOutgoingInterfaceId(w_lsa->GetLinkStateId(), w_lsa->GetNetworkLSANetworkMask()); + // Set the next hop to 0.0.0.0 meaning "not exist" + Ipv4Address nextHop = Ipv4Address::GetZero(); + w->SetRootExitDirection(nextHop, outIf); + w->SetDistanceFromRoot(distance); + w->SetParent(v); + NS_LOG_LOGIC("Next hop from " << v->GetVertexId() << " to network " << w->GetVertexId() + << " via outgoing interface " << outIf + << " with distance " << distance); + return 1; } } // end v is the root - else if (v->GetVertexType () == SPFVertex::VertexNetwork) + else if (v->GetVertexType() == SPFVertex::VertexNetwork) { -// See if any of v's parents are the root - if (v->GetParent () == m_spfroot) + // See if any of v's parents are the root + if (v->GetParent() == m_spfroot) { -// 16.1.1 para 5. ...the parent vertex is a network that -// directly connects the calculating router to the destination -// router. The list of next hops is then determined by -// examining the destination's router-LSA... - NS_ASSERT (w->GetVertexType () == SPFVertex::VertexRouter); - GlobalRoutingLinkRecord *linkRemote = nullptr; - while ((linkRemote = SPFGetNextLink (w, v, linkRemote))) + // 16.1.1 para 5. ...the parent vertex is a network that + // directly connects the calculating router to the destination + // router. The list of next hops is then determined by + // examining the destination's router-LSA... + NS_ASSERT(w->GetVertexType() == SPFVertex::VertexRouter); + GlobalRoutingLinkRecord* linkRemote = nullptr; + while ((linkRemote = SPFGetNextLink(w, v, linkRemote))) { -/* ...For each link in the router-LSA that points back to the - * parent network, the link's Link Data field provides the IP - * address of a next hop router. The outgoing interface to - * use can then be derived from the next hop IP address (or - * it can be inherited from the parent network). - */ - Ipv4Address nextHop = linkRemote->GetLinkData (); - uint32_t outIf = v->GetRootExitDirection ().second; - w->SetRootExitDirection (nextHop, outIf); - NS_LOG_LOGIC ("Next hop from " << - v->GetVertexId () << " to " << w->GetVertexId () << - " goes through next hop " << nextHop << - " via outgoing interface " << outIf); + /* ...For each link in the router-LSA that points back to the + * parent network, the link's Link Data field provides the IP + * address of a next hop router. The outgoing interface to + * use can then be derived from the next hop IP address (or + * it can be inherited from the parent network). + */ + Ipv4Address nextHop = linkRemote->GetLinkData(); + uint32_t outIf = v->GetRootExitDirection().second; + w->SetRootExitDirection(nextHop, outIf); + NS_LOG_LOGIC("Next hop from " << v->GetVertexId() << " to " << w->GetVertexId() + << " goes through next hop " << nextHop + << " via outgoing interface " << outIf); } } - else + else { - w->SetRootExitDirection (v->GetRootExitDirection ()); + w->SetRootExitDirection(v->GetRootExitDirection()); } } - else + else { -// -// If we're calculating the next hop information from a node (v) that is -// *not* the root, then we need to "inherit" the information needed to -// forward the packet from the vertex closer to the root. That is, we'll -// still send packets to the next hop address of the router adjacent to the -// root on the path toward . -// -// Above, when we were considering the root node, we calculated the next hop -// address and outgoing interface required to get off of the root network. -// At this point, we are further away from the root network along one of the -// (shortest) paths. So the next hop and outoing interface remain the same -// (are inherited). -// - w->InheritAllRootExitDirections (v); + // + // If we're calculating the next hop information from a node (v) that is + // *not* the root, then we need to "inherit" the information needed to + // forward the packet from the vertex closer to the root. That is, we'll + // still send packets to the next hop address of the router adjacent to the + // root on the path toward . + // + // Above, when we were considering the root node, we calculated the next hop + // address and outgoing interface required to get off of the root network. + // At this point, we are further away from the root network along one of the + // (shortest) paths. So the next hop and outoing interface remain the same + // (are inherited). + // + w->InheritAllRootExitDirections(v); } -// -// In all cases, we need valid values for the distance metric and a parent. -// - w->SetDistanceFromRoot (distance); - w->SetParent (v); + // + // In all cases, we need valid values for the distance metric and a parent. + // + w->SetDistanceFromRoot(distance); + w->SetParent(v); - return 1; + return 1; } // @@ -1173,88 +1166,87 @@ GlobalRouteManagerImpl::SPFNexthopCalculation ( // representing a possible *second* link from to . // GlobalRoutingLinkRecord* -GlobalRouteManagerImpl::SPFGetNextLink ( - SPFVertex* v, - SPFVertex* w, - GlobalRoutingLinkRecord* prev_link) +GlobalRouteManagerImpl::SPFGetNextLink(SPFVertex* v, + SPFVertex* w, + GlobalRoutingLinkRecord* prev_link) { - NS_LOG_FUNCTION (this << v << w << prev_link); + NS_LOG_FUNCTION(this << v << w << prev_link); - bool skip = true; - bool found_prev_link = false; - GlobalRoutingLinkRecord* l; -// -// If prev_link is 0, we are really looking for the first link, not the next -// link. -// - if (prev_link == nullptr) + bool skip = true; + bool found_prev_link = false; + GlobalRoutingLinkRecord* l; + // + // If prev_link is 0, we are really looking for the first link, not the next + // link. + // + if (prev_link == nullptr) { - skip = false; - found_prev_link = true; + skip = false; + found_prev_link = true; } -// -// Iterate through the Global Router Link Records advertised by the vertex -// looking for records representing the point-to-point links off of this -// vertex. -// - for (uint32_t i = 0; i < v->GetLSA ()->GetNLinkRecords (); ++i) + // + // Iterate through the Global Router Link Records advertised by the vertex + // looking for records representing the point-to-point links off of this + // vertex. + // + for (uint32_t i = 0; i < v->GetLSA()->GetNLinkRecords(); ++i) { - l = v->GetLSA ()->GetLinkRecord (i); -// -// The link ID of a link record representing a point-to-point link is set to -// the router ID of the neighboring router -- the router to which the link -// connects from the perspective of in this case. The vertex ID is also -// set to the router ID (using the link state advertisement of a router node). -// We're just checking to see if the link is actually the link from to -// . -// - if (l->GetLinkId () == w->GetVertexId ()) + l = v->GetLSA()->GetLinkRecord(i); + // + // The link ID of a link record representing a point-to-point link is set to + // the router ID of the neighboring router -- the router to which the link + // connects from the perspective of in this case. The vertex ID is also + // set to the router ID (using the link state advertisement of a router node). + // We're just checking to see if the link is actually the link from to + // . + // + if (l->GetLinkId() == w->GetVertexId()) { - if (!found_prev_link) + if (!found_prev_link) { - NS_LOG_LOGIC ("Skipping links before prev_link found"); - found_prev_link = true; - continue; + NS_LOG_LOGIC("Skipping links before prev_link found"); + found_prev_link = true; + continue; } - NS_LOG_LOGIC ("Found matching link l: linkId = " << - l->GetLinkId () << " linkData = " << l->GetLinkData ()); -// -// If skip is false, don't (not too surprisingly) skip the link found -- it's -// the one we're interested in. That's either because we didn't pass in a -// previous link, and we're interested in the first one, or because we've -// skipped a previous link and moved forward to the next (which is then the -// one we want). -// - if (skip == false) + NS_LOG_LOGIC("Found matching link l: linkId = " << l->GetLinkId() + << " linkData = " << l->GetLinkData()); + // + // If skip is false, don't (not too surprisingly) skip the link found -- it's + // the one we're interested in. That's either because we didn't pass in a + // previous link, and we're interested in the first one, or because we've + // skipped a previous link and moved forward to the next (which is then the + // one we want). + // + if (skip == false) { - NS_LOG_LOGIC ("Returning the found link"); - return l; + NS_LOG_LOGIC("Returning the found link"); + return l; } - else + else { -// -// Skip is true and we've found a link from to . We want the next one. -// Setting skip to false gets us the next point-to-point global router link -// record in the LSA from . -// - NS_LOG_LOGIC ("Skipping the found link"); - skip = false; - continue; + // + // Skip is true and we've found a link from to . We want the next one. + // Setting skip to false gets us the next point-to-point global router link + // record in the LSA from . + // + NS_LOG_LOGIC("Skipping the found link"); + skip = false; + continue; } } } - return nullptr; + return nullptr; } // // Used for unit tests. // void -GlobalRouteManagerImpl::DebugSPFCalculate (Ipv4Address root) +GlobalRouteManagerImpl::DebugSPFCalculate(Ipv4Address root) { - NS_LOG_FUNCTION (this << root); - SPFCalculate (root); + NS_LOG_FUNCTION(this << root); + SPFCalculate(root); } // @@ -1264,278 +1256,280 @@ GlobalRouteManagerImpl::DebugSPFCalculate (Ipv4Address root) // to be run // bool -GlobalRouteManagerImpl::CheckForStubNode (Ipv4Address root) +GlobalRouteManagerImpl::CheckForStubNode(Ipv4Address root) { - NS_LOG_FUNCTION (this << root); - GlobalRoutingLSA *rlsa = m_lsdb->GetLSA (root); - Ipv4Address myRouterId = rlsa->GetLinkStateId (); - int transits = 0; - GlobalRoutingLinkRecord *transitLink = nullptr; - for (uint32_t i = 0; i < rlsa->GetNLinkRecords (); i++) + NS_LOG_FUNCTION(this << root); + GlobalRoutingLSA* rlsa = m_lsdb->GetLSA(root); + Ipv4Address myRouterId = rlsa->GetLinkStateId(); + int transits = 0; + GlobalRoutingLinkRecord* transitLink = nullptr; + for (uint32_t i = 0; i < rlsa->GetNLinkRecords(); i++) { - GlobalRoutingLinkRecord *l = rlsa->GetLinkRecord (i); - if (l->GetLinkType () == GlobalRoutingLinkRecord::TransitNetwork) + GlobalRoutingLinkRecord* l = rlsa->GetLinkRecord(i); + if (l->GetLinkType() == GlobalRoutingLinkRecord::TransitNetwork) { - transits++; - transitLink = l; + transits++; + transitLink = l; } - else if (l->GetLinkType () == GlobalRoutingLinkRecord::PointToPoint) + else if (l->GetLinkType() == GlobalRoutingLinkRecord::PointToPoint) { - transits++; - transitLink = l; + transits++; + transitLink = l; } } - if (transits == 0) + if (transits == 0) { - // This router is not connected to any router. Probably, global - // routing should not be called for this node, but we can just raise - // a warning here and return true. - NS_LOG_WARN ("all nodes should have at least one transit link:" << root ); - return true; + // This router is not connected to any router. Probably, global + // routing should not be called for this node, but we can just raise + // a warning here and return true. + NS_LOG_WARN("all nodes should have at least one transit link:" << root); + return true; } - if (transits == 1) + if (transits == 1) { - if (transitLink->GetLinkType () == GlobalRoutingLinkRecord::TransitNetwork) + if (transitLink->GetLinkType() == GlobalRoutingLinkRecord::TransitNetwork) { - // Install default route to next hop router - // What is the next hop? We need to check all neighbors on the link. - // If there is a single router that has two transit links, then - // that is the default next hop. If there are more than one - // routers on link with multiple transit links, return false. - // Not yet implemented, so simply return false - NS_LOG_LOGIC ("TBD: Would have inserted default for transit"); - return false; + // Install default route to next hop router + // What is the next hop? We need to check all neighbors on the link. + // If there is a single router that has two transit links, then + // that is the default next hop. If there are more than one + // routers on link with multiple transit links, return false. + // Not yet implemented, so simply return false + NS_LOG_LOGIC("TBD: Would have inserted default for transit"); + return false; } - else if (transitLink->GetLinkType () == GlobalRoutingLinkRecord::PointToPoint) + else if (transitLink->GetLinkType() == GlobalRoutingLinkRecord::PointToPoint) { - // Install default route to next hop - // The link record LinkID is the router ID of the peer. - // The Link Data is the local IP interface address - GlobalRoutingLSA *w_lsa = m_lsdb->GetLSA (transitLink->GetLinkId ()); - uint32_t nLinkRecords = w_lsa->GetNLinkRecords (); - for (uint32_t j = 0; j < nLinkRecords; ++j) + // Install default route to next hop + // The link record LinkID is the router ID of the peer. + // The Link Data is the local IP interface address + GlobalRoutingLSA* w_lsa = m_lsdb->GetLSA(transitLink->GetLinkId()); + uint32_t nLinkRecords = w_lsa->GetNLinkRecords(); + for (uint32_t j = 0; j < nLinkRecords; ++j) { - // - // We are only concerned about point-to-point links - // - GlobalRoutingLinkRecord *lr = w_lsa->GetLinkRecord (j); - if (lr->GetLinkType () != GlobalRoutingLinkRecord::PointToPoint) + // + // We are only concerned about point-to-point links + // + GlobalRoutingLinkRecord* lr = w_lsa->GetLinkRecord(j); + if (lr->GetLinkType() != GlobalRoutingLinkRecord::PointToPoint) { - continue; + continue; } - // Find the link record that corresponds to our routerId - if (lr->GetLinkId () == myRouterId) + // Find the link record that corresponds to our routerId + if (lr->GetLinkId() == myRouterId) { - // Next hop is stored in the LinkID field of lr - Ptr router = rlsa->GetNode ()->GetObject (); - NS_ASSERT (router); - Ptr gr = router->GetRoutingProtocol (); - NS_ASSERT (gr); - gr->AddNetworkRouteTo (Ipv4Address ("0.0.0.0"), Ipv4Mask ("0.0.0.0"), lr->GetLinkData (), - FindOutgoingInterfaceId (transitLink->GetLinkData ())); - NS_LOG_LOGIC ("Inserting default route for node " << myRouterId << " to next hop " << - lr->GetLinkData () << " via interface " << - FindOutgoingInterfaceId (transitLink->GetLinkData ())); - return true; + // Next hop is stored in the LinkID field of lr + Ptr router = rlsa->GetNode()->GetObject(); + NS_ASSERT(router); + Ptr gr = router->GetRoutingProtocol(); + NS_ASSERT(gr); + gr->AddNetworkRouteTo(Ipv4Address("0.0.0.0"), + Ipv4Mask("0.0.0.0"), + lr->GetLinkData(), + FindOutgoingInterfaceId(transitLink->GetLinkData())); + NS_LOG_LOGIC("Inserting default route for node " + << myRouterId << " to next hop " << lr->GetLinkData() + << " via interface " + << FindOutgoingInterfaceId(transitLink->GetLinkData())); + return true; } } } } - return false; + return false; } // quagga ospf_spf_calculate void -GlobalRouteManagerImpl::SPFCalculate (Ipv4Address root) +GlobalRouteManagerImpl::SPFCalculate(Ipv4Address root) { - NS_LOG_FUNCTION (this << root); + NS_LOG_FUNCTION(this << root); - SPFVertex *v; -// -// Initialize the Link State Database. -// - m_lsdb->Initialize (); -// -// The candidate queue is a priority queue of SPFVertex objects, with the top -// of the queue being the closest vertex in terms of distance from the root -// of the tree. Initially, this queue is empty. -// - CandidateQueue candidate; - NS_ASSERT (candidate.Size () == 0); -// -// Initialize the shortest-path tree to only contain the router doing the -// calculation. Each router (and corresponding network) is a vertex in the -// shortest path first (SPF) tree. -// - v = new SPFVertex (m_lsdb->GetLSA (root)); -// -// This vertex is the root of the SPF tree and it is distance 0 from the root. -// We also mark this vertex as being in the SPF tree. -// - m_spfroot= v; - v->SetDistanceFromRoot (0); - v->GetLSA ()->SetStatus (GlobalRoutingLSA::LSA_SPF_IN_SPFTREE); - NS_LOG_LOGIC ("Starting SPFCalculate for node " << root); + SPFVertex* v; + // + // Initialize the Link State Database. + // + m_lsdb->Initialize(); + // + // The candidate queue is a priority queue of SPFVertex objects, with the top + // of the queue being the closest vertex in terms of distance from the root + // of the tree. Initially, this queue is empty. + // + CandidateQueue candidate; + NS_ASSERT(candidate.Size() == 0); + // + // Initialize the shortest-path tree to only contain the router doing the + // calculation. Each router (and corresponding network) is a vertex in the + // shortest path first (SPF) tree. + // + v = new SPFVertex(m_lsdb->GetLSA(root)); + // + // This vertex is the root of the SPF tree and it is distance 0 from the root. + // We also mark this vertex as being in the SPF tree. + // + m_spfroot = v; + v->SetDistanceFromRoot(0); + v->GetLSA()->SetStatus(GlobalRoutingLSA::LSA_SPF_IN_SPFTREE); + NS_LOG_LOGIC("Starting SPFCalculate for node " << root); -// -// Optimize SPF calculation, for ns-3. -// We do not need to calculate SPF for every node in the network if this -// node has only one interface through which another router can be -// reached. Instead, short-circuit this computation and just install -// a default route in the CheckForStubNode() method. -// - if (NodeList::GetNNodes () > 0 && CheckForStubNode (root)) + // + // Optimize SPF calculation, for ns-3. + // We do not need to calculate SPF for every node in the network if this + // node has only one interface through which another router can be + // reached. Instead, short-circuit this computation and just install + // a default route in the CheckForStubNode() method. + // + if (NodeList::GetNNodes() > 0 && CheckForStubNode(root)) { - NS_LOG_LOGIC ("SPFCalculate truncated for stub node " << root); - delete m_spfroot; - return; + NS_LOG_LOGIC("SPFCalculate truncated for stub node " << root); + delete m_spfroot; + return; } - for (;;) + for (;;) { -// -// The operations we need to do are given in the OSPF RFC which we reference -// as we go along. -// -// RFC2328 16.1. (2). -// -// We examine the Global Router Link Records in the Link State -// Advertisements of the current vertex. If there are any point-to-point -// links to unexplored adjacent vertices we add them to the tree and update -// the distance and next hop information on how to get there. We also add -// the new vertices to the candidate queue (the priority queue ordered by -// shortest path). If the new vertices represent shorter paths, we use them -// and update the path cost. -// - SPFNext (v, candidate); -// -// RFC2328 16.1. (3). -// -// If at this step the candidate list is empty, the shortest-path tree (of -// transit vertices) has been completely built and this stage of the -// procedure terminates. -// - if (candidate.Size () == 0) + // + // The operations we need to do are given in the OSPF RFC which we reference + // as we go along. + // + // RFC2328 16.1. (2). + // + // We examine the Global Router Link Records in the Link State + // Advertisements of the current vertex. If there are any point-to-point + // links to unexplored adjacent vertices we add them to the tree and update + // the distance and next hop information on how to get there. We also add + // the new vertices to the candidate queue (the priority queue ordered by + // shortest path). If the new vertices represent shorter paths, we use them + // and update the path cost. + // + SPFNext(v, candidate); + // + // RFC2328 16.1. (3). + // + // If at this step the candidate list is empty, the shortest-path tree (of + // transit vertices) has been completely built and this stage of the + // procedure terminates. + // + if (candidate.Size() == 0) { - break; + break; } -// -// Choose the vertex belonging to the candidate list that is closest to the -// root, and add it to the shortest-path tree (removing it from the candidate -// list in the process). -// -// Recall that in the previous step, we created SPFVertex structures for each -// of the routers found in the Global Router Link Records and added tehm to -// the candidate list. -// - NS_LOG_LOGIC (candidate); - v = candidate.Pop (); - NS_LOG_LOGIC ("Popped vertex " << v->GetVertexId ()); -// -// Update the status field of the vertex to indicate that it is in the SPF -// tree. -// - v->GetLSA ()->SetStatus (GlobalRoutingLSA::LSA_SPF_IN_SPFTREE); -// -// The current vertex has a parent pointer. By calling this rather oddly -// named method (blame quagga) we add the current vertex to the list of -// children of that parent vertex. In the next hop calculation called during -// SPFNext, the parent pointer was set but the vertex has been orphaned up -// to now. -// - SPFVertexAddParent (v); -// -// Note that when there is a choice of vertices closest to the root, network -// vertices must be chosen before router vertices in order to necessarily -// find all equal-cost paths. -// -// RFC2328 16.1. (4). -// -// This is the method that actually adds the routes. It'll walk the list -// of nodes in the system, looking for the node corresponding to the router -// ID of the root of the tree -- that is the router we're building the routes -// for. It looks for the Ipv4 interface of that node and remembers it. So -// we are only actually adding routes to that one node at the root of the SPF -// tree. -// -// We're going to pop of a pointer to every vertex in the tree except the -// root in order of distance from the root. For each of the vertices, we call -// SPFIntraAddRouter (). Down in SPFIntraAddRouter, we look at all of the -// point-to-point Global Router Link Records (the links to nodes adjacent to -// the node represented by the vertex). We add a route to the IP address -// specified by the m_linkData field of each of those link records. This will -// be the *local* IP address associated with the interface attached to the -// link. We use the outbound interface and next hop information present in -// the vertex which have possibly been inherited from the root. -// -// To summarize, we're going to look at the node represented by and loop -// through its point-to-point links, adding a *host* route to the local IP -// address (at the side) for each of those links. -// - if (v->GetVertexType () == SPFVertex::VertexRouter) + // + // Choose the vertex belonging to the candidate list that is closest to the + // root, and add it to the shortest-path tree (removing it from the candidate + // list in the process). + // + // Recall that in the previous step, we created SPFVertex structures for each + // of the routers found in the Global Router Link Records and added tehm to + // the candidate list. + // + NS_LOG_LOGIC(candidate); + v = candidate.Pop(); + NS_LOG_LOGIC("Popped vertex " << v->GetVertexId()); + // + // Update the status field of the vertex to indicate that it is in the SPF + // tree. + // + v->GetLSA()->SetStatus(GlobalRoutingLSA::LSA_SPF_IN_SPFTREE); + // + // The current vertex has a parent pointer. By calling this rather oddly + // named method (blame quagga) we add the current vertex to the list of + // children of that parent vertex. In the next hop calculation called during + // SPFNext, the parent pointer was set but the vertex has been orphaned up + // to now. + // + SPFVertexAddParent(v); + // + // Note that when there is a choice of vertices closest to the root, network + // vertices must be chosen before router vertices in order to necessarily + // find all equal-cost paths. + // + // RFC2328 16.1. (4). + // + // This is the method that actually adds the routes. It'll walk the list + // of nodes in the system, looking for the node corresponding to the router + // ID of the root of the tree -- that is the router we're building the routes + // for. It looks for the Ipv4 interface of that node and remembers it. So + // we are only actually adding routes to that one node at the root of the SPF + // tree. + // + // We're going to pop of a pointer to every vertex in the tree except the + // root in order of distance from the root. For each of the vertices, we call + // SPFIntraAddRouter (). Down in SPFIntraAddRouter, we look at all of the + // point-to-point Global Router Link Records (the links to nodes adjacent to + // the node represented by the vertex). We add a route to the IP address + // specified by the m_linkData field of each of those link records. This will + // be the *local* IP address associated with the interface attached to the + // link. We use the outbound interface and next hop information present in + // the vertex which have possibly been inherited from the root. + // + // To summarize, we're going to look at the node represented by and loop + // through its point-to-point links, adding a *host* route to the local IP + // address (at the side) for each of those links. + // + if (v->GetVertexType() == SPFVertex::VertexRouter) { - SPFIntraAddRouter (v); + SPFIntraAddRouter(v); } - else if (v->GetVertexType () == SPFVertex::VertexNetwork) + else if (v->GetVertexType() == SPFVertex::VertexNetwork) { - SPFIntraAddTransit (v); + SPFIntraAddTransit(v); } - else + else { - NS_ASSERT_MSG (0, "illegal SPFVertex type"); + NS_ASSERT_MSG(0, "illegal SPFVertex type"); } -// -// RFC2328 16.1. (5). -// -// Iterate the algorithm by returning to Step 2 until there are no more -// candidate vertices. + // + // RFC2328 16.1. (5). + // + // Iterate the algorithm by returning to Step 2 until there are no more + // candidate vertices. - } // end for loop + } // end for loop -// Second stage of SPF calculation procedure - SPFProcessStubs (m_spfroot); - for (uint32_t i = 0; i < m_lsdb->GetNumExtLSAs (); i++) + // Second stage of SPF calculation procedure + SPFProcessStubs(m_spfroot); + for (uint32_t i = 0; i < m_lsdb->GetNumExtLSAs(); i++) { - m_spfroot->ClearVertexProcessed (); - GlobalRoutingLSA *extlsa = m_lsdb->GetExtLSA (i); - NS_LOG_LOGIC ("Processing External LSA with id " << extlsa->GetLinkStateId ()); - ProcessASExternals (m_spfroot, extlsa); + m_spfroot->ClearVertexProcessed(); + GlobalRoutingLSA* extlsa = m_lsdb->GetExtLSA(i); + NS_LOG_LOGIC("Processing External LSA with id " << extlsa->GetLinkStateId()); + ProcessASExternals(m_spfroot, extlsa); } -// -// We're all done setting the routing information for the node at the root of -// the SPF tree. Delete all of the vertices and corresponding resources. Go -// possibly do it again for the next router. -// - delete m_spfroot; - m_spfroot = nullptr; + // + // We're all done setting the routing information for the node at the root of + // the SPF tree. Delete all of the vertices and corresponding resources. Go + // possibly do it again for the next router. + // + delete m_spfroot; + m_spfroot = nullptr; } void -GlobalRouteManagerImpl::ProcessASExternals (SPFVertex* v, GlobalRoutingLSA* extlsa) +GlobalRouteManagerImpl::ProcessASExternals(SPFVertex* v, GlobalRoutingLSA* extlsa) { - NS_LOG_FUNCTION (this << v << extlsa); - NS_LOG_LOGIC ("Processing external for destination " << - extlsa->GetLinkStateId () << - ", for router " << v->GetVertexId () << - ", advertised by " << extlsa->GetAdvertisingRouter ()); - if (v->GetVertexType () == SPFVertex::VertexRouter) + NS_LOG_FUNCTION(this << v << extlsa); + NS_LOG_LOGIC("Processing external for destination " + << extlsa->GetLinkStateId() << ", for router " << v->GetVertexId() + << ", advertised by " << extlsa->GetAdvertisingRouter()); + if (v->GetVertexType() == SPFVertex::VertexRouter) { - GlobalRoutingLSA *rlsa = v->GetLSA (); - NS_LOG_LOGIC ("Processing router LSA with id " << rlsa->GetLinkStateId ()); - if ((rlsa->GetLinkStateId ()) == (extlsa->GetAdvertisingRouter ())) + GlobalRoutingLSA* rlsa = v->GetLSA(); + NS_LOG_LOGIC("Processing router LSA with id " << rlsa->GetLinkStateId()); + if ((rlsa->GetLinkStateId()) == (extlsa->GetAdvertisingRouter())) { - NS_LOG_LOGIC ("Found advertising router to destination"); - SPFAddASExternal (extlsa,v); + NS_LOG_LOGIC("Found advertising router to destination"); + SPFAddASExternal(extlsa, v); } } - for (uint32_t i = 0; i < v->GetNChildren (); i++) + for (uint32_t i = 0; i < v->GetNChildren(); i++) { - if (!v->GetChild (i)->IsVertexProcessed ()) + if (!v->GetChild(i)->IsVertexProcessed()) { - NS_LOG_LOGIC ("Vertex's child " << i << " not yet processed, processing..."); - ProcessASExternals (v->GetChild (i), extlsa); - v->GetChild (i)->SetVertexProcessed (true); + NS_LOG_LOGIC("Vertex's child " << i << " not yet processed, processing..."); + ProcessASExternals(v->GetChild(i), extlsa); + v->GetChild(i)->SetVertexProcessed(true); } } } @@ -1546,295 +1540,289 @@ GlobalRouteManagerImpl::ProcessASExternals (SPFVertex* v, GlobalRoutingLSA* extl // void -GlobalRouteManagerImpl::SPFAddASExternal (GlobalRoutingLSA *extlsa, SPFVertex *v) +GlobalRouteManagerImpl::SPFAddASExternal(GlobalRoutingLSA* extlsa, SPFVertex* v) { - NS_LOG_FUNCTION (this << extlsa << v); + NS_LOG_FUNCTION(this << extlsa << v); - NS_ASSERT_MSG (m_spfroot, "GlobalRouteManagerImpl::SPFAddASExternal (): Root pointer not set"); -// Two cases to consider: We are advertising the external ourselves -// => No need to add anything -// OR find best path to the advertising router - if (v->GetVertexId () == m_spfroot->GetVertexId ()) + NS_ASSERT_MSG(m_spfroot, "GlobalRouteManagerImpl::SPFAddASExternal (): Root pointer not set"); + // Two cases to consider: We are advertising the external ourselves + // => No need to add anything + // OR find best path to the advertising router + if (v->GetVertexId() == m_spfroot->GetVertexId()) { - NS_LOG_LOGIC ("External is on local host: " - << v->GetVertexId () << "; returning"); - return; + NS_LOG_LOGIC("External is on local host: " << v->GetVertexId() << "; returning"); + return; } - NS_LOG_LOGIC ("External is on remote host: " - << extlsa->GetAdvertisingRouter () << "; installing"); + NS_LOG_LOGIC("External is on remote host: " << extlsa->GetAdvertisingRouter() + << "; installing"); - Ipv4Address routerId = m_spfroot->GetVertexId (); + Ipv4Address routerId = m_spfroot->GetVertexId(); - NS_LOG_LOGIC ("Vertex ID = " << routerId); -// -// We need to walk the list of nodes looking for the one that has the router -// ID corresponding to the root vertex. This is the one we're going to write -// the routing information to. -// - NodeList::Iterator i = NodeList::Begin (); - NodeList::Iterator listEnd = NodeList::End (); - for (; i != listEnd; i++) + NS_LOG_LOGIC("Vertex ID = " << routerId); + // + // We need to walk the list of nodes looking for the one that has the router + // ID corresponding to the root vertex. This is the one we're going to write + // the routing information to. + // + NodeList::Iterator i = NodeList::Begin(); + NodeList::Iterator listEnd = NodeList::End(); + for (; i != listEnd; i++) { - Ptr node = *i; -// -// The router ID is accessible through the GlobalRouter interface, so we need -// to QI for that interface. If there's no GlobalRouter interface, the node -// in question cannot be the router we want, so we continue. -// - Ptr rtr = node->GetObject (); + Ptr node = *i; + // + // The router ID is accessible through the GlobalRouter interface, so we need + // to QI for that interface. If there's no GlobalRouter interface, the node + // in question cannot be the router we want, so we continue. + // + Ptr rtr = node->GetObject(); - if (!rtr) + if (!rtr) { - NS_LOG_LOGIC ("No GlobalRouter interface on node " << node->GetId ()); - continue; + NS_LOG_LOGIC("No GlobalRouter interface on node " << node->GetId()); + continue; } -// -// If the router ID of the current node is equal to the router ID of the -// root of the SPF tree, then this node is the one for which we need to -// write the routing tables. -// - NS_LOG_LOGIC ("Considering router " << rtr->GetRouterId ()); + // + // If the router ID of the current node is equal to the router ID of the + // root of the SPF tree, then this node is the one for which we need to + // write the routing tables. + // + NS_LOG_LOGIC("Considering router " << rtr->GetRouterId()); - if (rtr->GetRouterId () == routerId) + if (rtr->GetRouterId() == routerId) { - NS_LOG_LOGIC ("Setting routes for node " << node->GetId ()); -// -// Routing information is updated using the Ipv4 interface. We need to QI -// for that interface. If the node is acting as an IP version 4 router, it -// should absolutely have an Ipv4 interface. -// - Ptr ipv4 = node->GetObject (); - NS_ASSERT_MSG (ipv4, - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "QI for interface failed"); -// -// Get the Global Router Link State Advertisement from the vertex we're -// adding the routes to. The LSA will have a number of attached Global Router -// Link Records corresponding to links off of that vertex / node. We're going -// to be interested in the records corresponding to point-to-point links. -// - NS_ASSERT_MSG (v->GetLSA (), - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "Expected valid LSA in SPFVertex* v"); - Ipv4Mask tempmask = extlsa->GetNetworkLSANetworkMask (); - Ipv4Address tempip = extlsa->GetLinkStateId (); - tempip = tempip.CombineMask (tempmask); + NS_LOG_LOGIC("Setting routes for node " << node->GetId()); + // + // Routing information is updated using the Ipv4 interface. We need to QI + // for that interface. If the node is acting as an IP version 4 router, it + // should absolutely have an Ipv4 interface. + // + Ptr ipv4 = node->GetObject(); + NS_ASSERT_MSG(ipv4, + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "QI for interface failed"); + // + // Get the Global Router Link State Advertisement from the vertex we're + // adding the routes to. The LSA will have a number of attached Global Router + // Link Records corresponding to links off of that vertex / node. We're going + // to be interested in the records corresponding to point-to-point links. + // + NS_ASSERT_MSG(v->GetLSA(), + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "Expected valid LSA in SPFVertex* v"); + Ipv4Mask tempmask = extlsa->GetNetworkLSANetworkMask(); + Ipv4Address tempip = extlsa->GetLinkStateId(); + tempip = tempip.CombineMask(tempmask); -// -// Here's why we did all of that work. We're going to add a host route to the -// host address found in the m_linkData field of the point-to-point link -// record. In the case of a point-to-point link, this is the local IP address -// of the node connected to the link. Each of these point-to-point links -// will correspond to a local interface that has an IP address to which -// the node at the root of the SPF tree can send packets. The vertex -// (corresponding to the node that has these links and interfaces) has -// an m_nextHop address precalculated for us that is the address to which the -// root node should send packets to be forwarded to these IP addresses. -// Similarly, the vertex has an m_rootOif (outbound interface index) to -// which the packets should be send for forwarding. -// - Ptr router = node->GetObject (); - if (!router) + // + // Here's why we did all of that work. We're going to add a host route to the + // host address found in the m_linkData field of the point-to-point link + // record. In the case of a point-to-point link, this is the local IP address + // of the node connected to the link. Each of these point-to-point links + // will correspond to a local interface that has an IP address to which + // the node at the root of the SPF tree can send packets. The vertex + // (corresponding to the node that has these links and interfaces) has + // an m_nextHop address precalculated for us that is the address to which the + // root node should send packets to be forwarded to these IP addresses. + // Similarly, the vertex has an m_rootOif (outbound interface index) to + // which the packets should be send for forwarding. + // + Ptr router = node->GetObject(); + if (!router) { - continue; + continue; } - Ptr gr = router->GetRoutingProtocol (); - NS_ASSERT (gr); - // walk through all next-hop-IPs and out-going-interfaces for reaching - // the stub network gateway 'v' from the root node - for (uint32_t i = 0; i < v->GetNRootExitDirections (); i++) + Ptr gr = router->GetRoutingProtocol(); + NS_ASSERT(gr); + // walk through all next-hop-IPs and out-going-interfaces for reaching + // the stub network gateway 'v' from the root node + for (uint32_t i = 0; i < v->GetNRootExitDirections(); i++) { - SPFVertex::NodeExit_t exit = v->GetRootExitDirection (i); - Ipv4Address nextHop = exit.first; - int32_t outIf = exit.second; - if (outIf >= 0) + SPFVertex::NodeExit_t exit = v->GetRootExitDirection(i); + Ipv4Address nextHop = exit.first; + int32_t outIf = exit.second; + if (outIf >= 0) { - gr->AddASExternalRouteTo (tempip, tempmask, nextHop, outIf); - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " add external network route to " << tempip << - " using next hop " << nextHop << - " via interface " << outIf); + gr->AddASExternalRouteTo(tempip, tempmask, nextHop, outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " add external network route to " << tempip + << " using next hop " << nextHop << " via interface " + << outIf); } - else + else { - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " NOT able to add network route to " << tempip << - " using next hop " << nextHop << - " since outgoing interface id is negative"); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " NOT able to add network route to " << tempip + << " using next hop " << nextHop + << " since outgoing interface id is negative"); } } - return; + return; } // if } // for } - // Processing logic from RFC 2328, page 166 and quagga ospf_spf_process_stubs () // stub link records will exist for point-to-point interfaces and for // broadcast interfaces for which no neighboring router can be found void -GlobalRouteManagerImpl::SPFProcessStubs (SPFVertex* v) +GlobalRouteManagerImpl::SPFProcessStubs(SPFVertex* v) { - NS_LOG_FUNCTION (this << v); - NS_LOG_LOGIC ("Processing stubs for " << v->GetVertexId ()); - if (v->GetVertexType () == SPFVertex::VertexRouter) + NS_LOG_FUNCTION(this << v); + NS_LOG_LOGIC("Processing stubs for " << v->GetVertexId()); + if (v->GetVertexType() == SPFVertex::VertexRouter) { - GlobalRoutingLSA *rlsa = v->GetLSA (); - NS_LOG_LOGIC ("Processing router LSA with id " << rlsa->GetLinkStateId ()); - for (uint32_t i = 0; i < rlsa->GetNLinkRecords (); i++) + GlobalRoutingLSA* rlsa = v->GetLSA(); + NS_LOG_LOGIC("Processing router LSA with id " << rlsa->GetLinkStateId()); + for (uint32_t i = 0; i < rlsa->GetNLinkRecords(); i++) { - NS_LOG_LOGIC ("Examining link " << i << " of " << - v->GetVertexId () << "'s " << - v->GetLSA ()->GetNLinkRecords () << " link records"); - GlobalRoutingLinkRecord *l = v->GetLSA ()->GetLinkRecord (i); - if (l->GetLinkType () == GlobalRoutingLinkRecord::StubNetwork) + NS_LOG_LOGIC("Examining link " << i << " of " << v->GetVertexId() << "'s " + << v->GetLSA()->GetNLinkRecords() << " link records"); + GlobalRoutingLinkRecord* l = v->GetLSA()->GetLinkRecord(i); + if (l->GetLinkType() == GlobalRoutingLinkRecord::StubNetwork) { - NS_LOG_LOGIC ("Found a Stub record to " << l->GetLinkId ()); - SPFIntraAddStub (l, v); - continue; + NS_LOG_LOGIC("Found a Stub record to " << l->GetLinkId()); + SPFIntraAddStub(l, v); + continue; } } } - for (uint32_t i = 0; i < v->GetNChildren (); i++) + for (uint32_t i = 0; i < v->GetNChildren(); i++) { - if (!v->GetChild (i)->IsVertexProcessed ()) + if (!v->GetChild(i)->IsVertexProcessed()) { - SPFProcessStubs (v->GetChild (i)); - v->GetChild (i)->SetVertexProcessed (true); + SPFProcessStubs(v->GetChild(i)); + v->GetChild(i)->SetVertexProcessed(true); } } } // RFC2328 16.1. second stage. void -GlobalRouteManagerImpl::SPFIntraAddStub (GlobalRoutingLinkRecord *l, SPFVertex* v) +GlobalRouteManagerImpl::SPFIntraAddStub(GlobalRoutingLinkRecord* l, SPFVertex* v) { - NS_LOG_FUNCTION (this << l << v); + NS_LOG_FUNCTION(this << l << v); - NS_ASSERT_MSG (m_spfroot, - "GlobalRouteManagerImpl::SPFIntraAddStub (): Root pointer not set"); + NS_ASSERT_MSG(m_spfroot, "GlobalRouteManagerImpl::SPFIntraAddStub (): Root pointer not set"); - // XXX simplifed logic for the moment. There are two cases to consider: - // 1) the stub network is on this router; do nothing for now - // (already handled above) - // 2) the stub network is on a remote router, so I should use the - // same next hop that I use to get to vertex v - if (v->GetVertexId () == m_spfroot->GetVertexId ()) + // XXX simplifed logic for the moment. There are two cases to consider: + // 1) the stub network is on this router; do nothing for now + // (already handled above) + // 2) the stub network is on a remote router, so I should use the + // same next hop that I use to get to vertex v + if (v->GetVertexId() == m_spfroot->GetVertexId()) { - NS_LOG_LOGIC ("Stub is on local host: " << v->GetVertexId () << "; returning"); - return; + NS_LOG_LOGIC("Stub is on local host: " << v->GetVertexId() << "; returning"); + return; } - NS_LOG_LOGIC ("Stub is on remote host: " << v->GetVertexId () << "; installing"); -// -// The root of the Shortest Path First tree is the router to which we are -// going to write the actual routing table entries. The vertex corresponding -// to this router has a vertex ID which is the router ID of that node. We're -// going to use this ID to discover which node it is that we're actually going -// to update. -// - Ipv4Address routerId = m_spfroot->GetVertexId (); + NS_LOG_LOGIC("Stub is on remote host: " << v->GetVertexId() << "; installing"); + // + // The root of the Shortest Path First tree is the router to which we are + // going to write the actual routing table entries. The vertex corresponding + // to this router has a vertex ID which is the router ID of that node. We're + // going to use this ID to discover which node it is that we're actually going + // to update. + // + Ipv4Address routerId = m_spfroot->GetVertexId(); - NS_LOG_LOGIC ("Vertex ID = " << routerId); -// -// We need to walk the list of nodes looking for the one that has the router -// ID corresponding to the root vertex. This is the one we're going to write -// the routing information to. -// - NodeList::Iterator i = NodeList::Begin (); - NodeList::Iterator listEnd = NodeList::End (); - for (; i != listEnd; i++) + NS_LOG_LOGIC("Vertex ID = " << routerId); + // + // We need to walk the list of nodes looking for the one that has the router + // ID corresponding to the root vertex. This is the one we're going to write + // the routing information to. + // + NodeList::Iterator i = NodeList::Begin(); + NodeList::Iterator listEnd = NodeList::End(); + for (; i != listEnd; i++) { - Ptr node = *i; -// -// The router ID is accessible through the GlobalRouter interface, so we need -// to QI for that interface. If there's no GlobalRouter interface, the node -// in question cannot be the router we want, so we continue. -// - Ptr rtr = - node->GetObject (); + Ptr node = *i; + // + // The router ID is accessible through the GlobalRouter interface, so we need + // to QI for that interface. If there's no GlobalRouter interface, the node + // in question cannot be the router we want, so we continue. + // + Ptr rtr = node->GetObject(); - if (!rtr) + if (!rtr) { - NS_LOG_LOGIC ("No GlobalRouter interface on node " << - node->GetId ()); - continue; + NS_LOG_LOGIC("No GlobalRouter interface on node " << node->GetId()); + continue; } -// -// If the router ID of the current node is equal to the router ID of the -// root of the SPF tree, then this node is the one for which we need to -// write the routing tables. -// - NS_LOG_LOGIC ("Considering router " << rtr->GetRouterId ()); + // + // If the router ID of the current node is equal to the router ID of the + // root of the SPF tree, then this node is the one for which we need to + // write the routing tables. + // + NS_LOG_LOGIC("Considering router " << rtr->GetRouterId()); - if (rtr->GetRouterId () == routerId) + if (rtr->GetRouterId() == routerId) { - NS_LOG_LOGIC ("Setting routes for node " << node->GetId ()); -// -// Routing information is updated using the Ipv4 interface. We need to QI -// for that interface. If the node is acting as an IP version 4 router, it -// should absolutely have an Ipv4 interface. -// - Ptr ipv4 = node->GetObject (); - NS_ASSERT_MSG (ipv4, - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "QI for interface failed"); -// -// Get the Global Router Link State Advertisement from the vertex we're -// adding the routes to. The LSA will have a number of attached Global Router -// Link Records corresponding to links off of that vertex / node. We're going -// to be interested in the records corresponding to point-to-point links. -// - NS_ASSERT_MSG (v->GetLSA (), - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "Expected valid LSA in SPFVertex* v"); - Ipv4Mask tempmask (l->GetLinkData ().Get ()); - Ipv4Address tempip = l->GetLinkId (); - tempip = tempip.CombineMask (tempmask); -// -// Here's why we did all of that work. We're going to add a host route to the -// host address found in the m_linkData field of the point-to-point link -// record. In the case of a point-to-point link, this is the local IP address -// of the node connected to the link. Each of these point-to-point links -// will correspond to a local interface that has an IP address to which -// the node at the root of the SPF tree can send packets. The vertex -// (corresponding to the node that has these links and interfaces) has -// an m_nextHop address precalculated for us that is the address to which the -// root node should send packets to be forwarded to these IP addresses. -// Similarly, the vertex has an m_rootOif (outbound interface index) to -// which the packets should be send for forwarding. -// + NS_LOG_LOGIC("Setting routes for node " << node->GetId()); + // + // Routing information is updated using the Ipv4 interface. We need to QI + // for that interface. If the node is acting as an IP version 4 router, it + // should absolutely have an Ipv4 interface. + // + Ptr ipv4 = node->GetObject(); + NS_ASSERT_MSG(ipv4, + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "QI for interface failed"); + // + // Get the Global Router Link State Advertisement from the vertex we're + // adding the routes to. The LSA will have a number of attached Global Router + // Link Records corresponding to links off of that vertex / node. We're going + // to be interested in the records corresponding to point-to-point links. + // + NS_ASSERT_MSG(v->GetLSA(), + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "Expected valid LSA in SPFVertex* v"); + Ipv4Mask tempmask(l->GetLinkData().Get()); + Ipv4Address tempip = l->GetLinkId(); + tempip = tempip.CombineMask(tempmask); + // + // Here's why we did all of that work. We're going to add a host route to the + // host address found in the m_linkData field of the point-to-point link + // record. In the case of a point-to-point link, this is the local IP address + // of the node connected to the link. Each of these point-to-point links + // will correspond to a local interface that has an IP address to which + // the node at the root of the SPF tree can send packets. The vertex + // (corresponding to the node that has these links and interfaces) has + // an m_nextHop address precalculated for us that is the address to which the + // root node should send packets to be forwarded to these IP addresses. + // Similarly, the vertex has an m_rootOif (outbound interface index) to + // which the packets should be send for forwarding. + // - Ptr router = node->GetObject (); - if (!router) + Ptr router = node->GetObject(); + if (!router) { - continue; + continue; } - Ptr gr = router->GetRoutingProtocol (); - NS_ASSERT (gr); - // walk through all next-hop-IPs and out-going-interfaces for reaching - // the stub network gateway 'v' from the root node - for (uint32_t i = 0; i < v->GetNRootExitDirections (); i++) + Ptr gr = router->GetRoutingProtocol(); + NS_ASSERT(gr); + // walk through all next-hop-IPs and out-going-interfaces for reaching + // the stub network gateway 'v' from the root node + for (uint32_t i = 0; i < v->GetNRootExitDirections(); i++) { - SPFVertex::NodeExit_t exit = v->GetRootExitDirection (i); - Ipv4Address nextHop = exit.first; - int32_t outIf = exit.second; - if (outIf >= 0) + SPFVertex::NodeExit_t exit = v->GetRootExitDirection(i); + Ipv4Address nextHop = exit.first; + int32_t outIf = exit.second; + if (outIf >= 0) { - gr->AddNetworkRouteTo (tempip, tempmask, nextHop, outIf); - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " add network route to " << tempip << - " using next hop " << nextHop << - " via interface " << outIf); + gr->AddNetworkRouteTo(tempip, tempmask, nextHop, outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " add network route to " << tempip + << " using next hop " << nextHop << " via interface " + << outIf); } - else + else { - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " NOT able to add network route to " << tempip << - " using next hop " << nextHop << - " since outgoing interface id is negative"); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " NOT able to add network route to " << tempip + << " using next hop " << nextHop + << " since outgoing interface id is negative"); } } - return; + return; } // if } // for } @@ -1847,58 +1835,57 @@ GlobalRouteManagerImpl::SPFIntraAddStub (GlobalRoutingLinkRecord *l, SPFVertex* // for routing assumes -1 to be a legal return value) // int32_t -GlobalRouteManagerImpl::FindOutgoingInterfaceId (Ipv4Address a, Ipv4Mask amask) +GlobalRouteManagerImpl::FindOutgoingInterfaceId(Ipv4Address a, Ipv4Mask amask) { - NS_LOG_FUNCTION (this << a << amask); -// -// We have an IP address and a vertex ID of the root of the SPF tree. -// The question is what interface index does this address correspond to. -// The answer is a little complicated since we have to find a pointer to -// the node corresponding to the vertex ID, find the Ipv4 interface on that -// node in order to iterate the interfaces and find the one corresponding to -// the address in question. -// - Ipv4Address routerId = m_spfroot->GetVertexId (); -// -// Walk the list of nodes in the system looking for the one corresponding to -// the node at the root of the SPF tree. This is the node for which we are -// building the routing table. -// - NodeList::Iterator i = NodeList::Begin (); - NodeList::Iterator listEnd = NodeList::End (); - for (; i != listEnd; i++) + NS_LOG_FUNCTION(this << a << amask); + // + // We have an IP address and a vertex ID of the root of the SPF tree. + // The question is what interface index does this address correspond to. + // The answer is a little complicated since we have to find a pointer to + // the node corresponding to the vertex ID, find the Ipv4 interface on that + // node in order to iterate the interfaces and find the one corresponding to + // the address in question. + // + Ipv4Address routerId = m_spfroot->GetVertexId(); + // + // Walk the list of nodes in the system looking for the one corresponding to + // the node at the root of the SPF tree. This is the node for which we are + // building the routing table. + // + NodeList::Iterator i = NodeList::Begin(); + NodeList::Iterator listEnd = NodeList::End(); + for (; i != listEnd; i++) { - Ptr node = *i; + Ptr node = *i; - Ptr rtr = - node->GetObject (); -// -// If the node doesn't have a GlobalRouter interface it can't be the one -// we're interested in. -// - if (!rtr) + Ptr rtr = node->GetObject(); + // + // If the node doesn't have a GlobalRouter interface it can't be the one + // we're interested in. + // + if (!rtr) { - continue; + continue; } - if (rtr->GetRouterId () == routerId) + if (rtr->GetRouterId() == routerId) { -// -// This is the node we're building the routing table for. We're going to need -// the Ipv4 interface to look for the ipv4 interface index. Since this node -// is participating in routing IP version 4 packets, it certainly must have -// an Ipv4 interface. -// - Ptr ipv4 = node->GetObject (); - NS_ASSERT_MSG (ipv4, - "GlobalRouteManagerImpl::FindOutgoingInterfaceId (): " - "GetObject for interface failed"); -// -// Look through the interfaces on this node for one that has the IP address -// we're looking for. If we find one, return the corresponding interface -// index, or -1 if not found. -// - int32_t interface = ipv4->GetInterfaceForPrefix (a, amask); + // + // This is the node we're building the routing table for. We're going to need + // the Ipv4 interface to look for the ipv4 interface index. Since this node + // is participating in routing IP version 4 packets, it certainly must have + // an Ipv4 interface. + // + Ptr ipv4 = node->GetObject(); + NS_ASSERT_MSG(ipv4, + "GlobalRouteManagerImpl::FindOutgoingInterfaceId (): " + "GetObject for interface failed"); + // + // Look through the interfaces on this node for one that has the IP address + // we're looking for. If we find one, return the corresponding interface + // index, or -1 if not found. + // + int32_t interface = ipv4->GetInterfaceForPrefix(a, amask); #if 0 if (interface < 0) @@ -1907,14 +1894,14 @@ GlobalRouteManagerImpl::FindOutgoingInterfaceId (Ipv4Address a, Ipv4Mask amask) "Expected an interface associated with address a:" << a); } #endif - return interface; + return interface; } } -// -// Couldn't find it. -// - NS_LOG_LOGIC ("FindOutgoingInterfaceId():Can't find root node " << routerId); - return -1; + // + // Couldn't find it. + // + NS_LOG_LOGIC("FindOutgoingInterfaceId():Can't find root node " << routerId); + return -1; } // @@ -1934,253 +1921,249 @@ GlobalRouteManagerImpl::FindOutgoingInterfaceId (Ipv4Address a, Ipv4Mask amask) // route. // void -GlobalRouteManagerImpl::SPFIntraAddRouter (SPFVertex* v) +GlobalRouteManagerImpl::SPFIntraAddRouter(SPFVertex* v) { - NS_LOG_FUNCTION (this << v); + NS_LOG_FUNCTION(this << v); - NS_ASSERT_MSG (m_spfroot, - "GlobalRouteManagerImpl::SPFIntraAddRouter (): Root pointer not set"); -// -// The root of the Shortest Path First tree is the router to which we are -// going to write the actual routing table entries. The vertex corresponding -// to this router has a vertex ID which is the router ID of that node. We're -// going to use this ID to discover which node it is that we're actually going -// to update. -// - Ipv4Address routerId = m_spfroot->GetVertexId (); + NS_ASSERT_MSG(m_spfroot, "GlobalRouteManagerImpl::SPFIntraAddRouter (): Root pointer not set"); + // + // The root of the Shortest Path First tree is the router to which we are + // going to write the actual routing table entries. The vertex corresponding + // to this router has a vertex ID which is the router ID of that node. We're + // going to use this ID to discover which node it is that we're actually going + // to update. + // + Ipv4Address routerId = m_spfroot->GetVertexId(); - NS_LOG_LOGIC ("Vertex ID = " << routerId); -// -// We need to walk the list of nodes looking for the one that has the router -// ID corresponding to the root vertex. This is the one we're going to write -// the routing information to. -// - NodeList::Iterator i = NodeList::Begin (); - NodeList::Iterator listEnd = NodeList::End (); - for (; i != listEnd; i++) + NS_LOG_LOGIC("Vertex ID = " << routerId); + // + // We need to walk the list of nodes looking for the one that has the router + // ID corresponding to the root vertex. This is the one we're going to write + // the routing information to. + // + NodeList::Iterator i = NodeList::Begin(); + NodeList::Iterator listEnd = NodeList::End(); + for (; i != listEnd; i++) { - Ptr node = *i; -// -// The router ID is accessible through the GlobalRouter interface, so we need -// to GetObject for that interface. If there's no GlobalRouter interface, -// the node in question cannot be the router we want, so we continue. -// - Ptr rtr = - node->GetObject (); + Ptr node = *i; + // + // The router ID is accessible through the GlobalRouter interface, so we need + // to GetObject for that interface. If there's no GlobalRouter interface, + // the node in question cannot be the router we want, so we continue. + // + Ptr rtr = node->GetObject(); - if (!rtr) + if (!rtr) { - NS_LOG_LOGIC ("No GlobalRouter interface on node " << - node->GetId ()); - continue; + NS_LOG_LOGIC("No GlobalRouter interface on node " << node->GetId()); + continue; } -// -// If the router ID of the current node is equal to the router ID of the -// root of the SPF tree, then this node is the one for which we need to -// write the routing tables. -// - NS_LOG_LOGIC ("Considering router " << rtr->GetRouterId ()); + // + // If the router ID of the current node is equal to the router ID of the + // root of the SPF tree, then this node is the one for which we need to + // write the routing tables. + // + NS_LOG_LOGIC("Considering router " << rtr->GetRouterId()); - if (rtr->GetRouterId () == routerId) + if (rtr->GetRouterId() == routerId) { - NS_LOG_LOGIC ("Setting routes for node " << node->GetId ()); -// -// Routing information is updated using the Ipv4 interface. We need to -// GetObject for that interface. If the node is acting as an IP version 4 -// router, it should absolutely have an Ipv4 interface. -// - Ptr ipv4 = node->GetObject (); - NS_ASSERT_MSG (ipv4, - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "GetObject for interface failed"); -// -// Get the Global Router Link State Advertisement from the vertex we're -// adding the routes to. The LSA will have a number of attached Global Router -// Link Records corresponding to links off of that vertex / node. We're going -// to be interested in the records corresponding to point-to-point links. -// - GlobalRoutingLSA *lsa = v->GetLSA (); - NS_ASSERT_MSG (lsa, - "GlobalRouteManagerImpl::SPFIntraAddRouter (): " - "Expected valid LSA in SPFVertex* v"); + NS_LOG_LOGIC("Setting routes for node " << node->GetId()); + // + // Routing information is updated using the Ipv4 interface. We need to + // GetObject for that interface. If the node is acting as an IP version 4 + // router, it should absolutely have an Ipv4 interface. + // + Ptr ipv4 = node->GetObject(); + NS_ASSERT_MSG(ipv4, + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "GetObject for interface failed"); + // + // Get the Global Router Link State Advertisement from the vertex we're + // adding the routes to. The LSA will have a number of attached Global Router + // Link Records corresponding to links off of that vertex / node. We're going + // to be interested in the records corresponding to point-to-point links. + // + GlobalRoutingLSA* lsa = v->GetLSA(); + NS_ASSERT_MSG(lsa, + "GlobalRouteManagerImpl::SPFIntraAddRouter (): " + "Expected valid LSA in SPFVertex* v"); - uint32_t nLinkRecords = lsa->GetNLinkRecords (); -// -// Iterate through the link records on the vertex to which we're going to add -// routes. To make sure we're being clear, we're going to add routing table -// entries to the tables on the node corresping to the root of the SPF tree. -// These entries will have routes to the IP addresses we find from looking at -// the local side of the point-to-point links found on the node described by -// the vertex . -// - NS_LOG_LOGIC (" Node " << node->GetId () << - " found " << nLinkRecords << " link records in LSA " << lsa << "with LinkStateId "<< lsa->GetLinkStateId ()); - for (uint32_t j = 0; j < nLinkRecords; ++j) + uint32_t nLinkRecords = lsa->GetNLinkRecords(); + // + // Iterate through the link records on the vertex to which we're going to add + // routes. To make sure we're being clear, we're going to add routing table + // entries to the tables on the node corresping to the root of the SPF tree. + // These entries will have routes to the IP addresses we find from looking at + // the local side of the point-to-point links found on the node described by + // the vertex . + // + NS_LOG_LOGIC(" Node " << node->GetId() << " found " << nLinkRecords + << " link records in LSA " << lsa << "with LinkStateId " + << lsa->GetLinkStateId()); + for (uint32_t j = 0; j < nLinkRecords; ++j) { -// -// We are only concerned about point-to-point links -// - GlobalRoutingLinkRecord *lr = lsa->GetLinkRecord (j); - if (lr->GetLinkType () != GlobalRoutingLinkRecord::PointToPoint) + // + // We are only concerned about point-to-point links + // + GlobalRoutingLinkRecord* lr = lsa->GetLinkRecord(j); + if (lr->GetLinkType() != GlobalRoutingLinkRecord::PointToPoint) { - continue; + continue; } -// -// Here's why we did all of that work. We're going to add a host route to the -// host address found in the m_linkData field of the point-to-point link -// record. In the case of a point-to-point link, this is the local IP address -// of the node connected to the link. Each of these point-to-point links -// will correspond to a local interface that has an IP address to which -// the node at the root of the SPF tree can send packets. The vertex -// (corresponding to the node that has these links and interfaces) has -// an m_nextHop address precalculated for us that is the address to which the -// root node should send packets to be forwarded to these IP addresses. -// Similarly, the vertex has an m_rootOif (outbound interface index) to -// which the packets should be send for forwarding. -// - Ptr router = node->GetObject (); - if (!router) + // + // Here's why we did all of that work. We're going to add a host route to the + // host address found in the m_linkData field of the point-to-point link + // record. In the case of a point-to-point link, this is the local IP address + // of the node connected to the link. Each of these point-to-point links + // will correspond to a local interface that has an IP address to which + // the node at the root of the SPF tree can send packets. The vertex + // (corresponding to the node that has these links and interfaces) has + // an m_nextHop address precalculated for us that is the address to which the + // root node should send packets to be forwarded to these IP addresses. + // Similarly, the vertex has an m_rootOif (outbound interface index) to + // which the packets should be send for forwarding. + // + Ptr router = node->GetObject(); + if (!router) { - continue; + continue; } - Ptr gr = router->GetRoutingProtocol (); - NS_ASSERT (gr); - // walk through all available exit directions due to ECMP, - // and add host route for each of the exit direction toward - // the vertex 'v' - for (uint32_t i = 0; i < v->GetNRootExitDirections (); i++) + Ptr gr = router->GetRoutingProtocol(); + NS_ASSERT(gr); + // walk through all available exit directions due to ECMP, + // and add host route for each of the exit direction toward + // the vertex 'v' + for (uint32_t i = 0; i < v->GetNRootExitDirections(); i++) { - SPFVertex::NodeExit_t exit = v->GetRootExitDirection (i); - Ipv4Address nextHop = exit.first; - int32_t outIf = exit.second; - if (outIf >= 0) + SPFVertex::NodeExit_t exit = v->GetRootExitDirection(i); + Ipv4Address nextHop = exit.first; + int32_t outIf = exit.second; + if (outIf >= 0) { - gr->AddHostRouteTo (lr->GetLinkData (), nextHop, - outIf); - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " adding host route to " << lr->GetLinkData () << - " using next hop " << nextHop << - " and outgoing interface " << outIf); + gr->AddHostRouteTo(lr->GetLinkData(), nextHop, outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " adding host route to " << lr->GetLinkData() + << " using next hop " << nextHop + << " and outgoing interface " << outIf); } - else + else { - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " NOT able to add host route to " << lr->GetLinkData () << - " using next hop " << nextHop << - " since outgoing interface id is negative " << outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " NOT able to add host route to " + << lr->GetLinkData() << " using next hop " << nextHop + << " since outgoing interface id is negative " + << outIf); } } // for all routes from the root the vertex 'v' } -// -// Done adding the routes for the selected node. -// - return; + // + // Done adding the routes for the selected node. + // + return; } } } + void -GlobalRouteManagerImpl::SPFIntraAddTransit (SPFVertex* v) +GlobalRouteManagerImpl::SPFIntraAddTransit(SPFVertex* v) { - NS_LOG_FUNCTION (this << v); + NS_LOG_FUNCTION(this << v); - NS_ASSERT_MSG (m_spfroot, - "GlobalRouteManagerImpl::SPFIntraAddTransit (): Root pointer not set"); -// -// The root of the Shortest Path First tree is the router to which we are -// going to write the actual routing table entries. The vertex corresponding -// to this router has a vertex ID which is the router ID of that node. We're -// going to use this ID to discover which node it is that we're actually going -// to update. -// - Ipv4Address routerId = m_spfroot->GetVertexId (); + NS_ASSERT_MSG(m_spfroot, "GlobalRouteManagerImpl::SPFIntraAddTransit (): Root pointer not set"); + // + // The root of the Shortest Path First tree is the router to which we are + // going to write the actual routing table entries. The vertex corresponding + // to this router has a vertex ID which is the router ID of that node. We're + // going to use this ID to discover which node it is that we're actually going + // to update. + // + Ipv4Address routerId = m_spfroot->GetVertexId(); - NS_LOG_LOGIC ("Vertex ID = " << routerId); -// -// We need to walk the list of nodes looking for the one that has the router -// ID corresponding to the root vertex. This is the one we're going to write -// the routing information to. -// - NodeList::Iterator i = NodeList::Begin (); - NodeList::Iterator listEnd = NodeList::End (); - for (; i != listEnd; i++) + NS_LOG_LOGIC("Vertex ID = " << routerId); + // + // We need to walk the list of nodes looking for the one that has the router + // ID corresponding to the root vertex. This is the one we're going to write + // the routing information to. + // + NodeList::Iterator i = NodeList::Begin(); + NodeList::Iterator listEnd = NodeList::End(); + for (; i != listEnd; i++) { - Ptr node = *i; -// -// The router ID is accessible through the GlobalRouter interface, so we need -// to GetObject for that interface. If there's no GlobalRouter interface, -// the node in question cannot be the router we want, so we continue. -// - Ptr rtr = - node->GetObject (); + Ptr node = *i; + // + // The router ID is accessible through the GlobalRouter interface, so we need + // to GetObject for that interface. If there's no GlobalRouter interface, + // the node in question cannot be the router we want, so we continue. + // + Ptr rtr = node->GetObject(); - if (!rtr) + if (!rtr) { - NS_LOG_LOGIC ("No GlobalRouter interface on node " << - node->GetId ()); - continue; + NS_LOG_LOGIC("No GlobalRouter interface on node " << node->GetId()); + continue; } -// -// If the router ID of the current node is equal to the router ID of the -// root of the SPF tree, then this node is the one for which we need to -// write the routing tables. -// - NS_LOG_LOGIC ("Considering router " << rtr->GetRouterId ()); + // + // If the router ID of the current node is equal to the router ID of the + // root of the SPF tree, then this node is the one for which we need to + // write the routing tables. + // + NS_LOG_LOGIC("Considering router " << rtr->GetRouterId()); - if (rtr->GetRouterId () == routerId) + if (rtr->GetRouterId() == routerId) { - NS_LOG_LOGIC ("setting routes for node " << node->GetId ()); -// -// Routing information is updated using the Ipv4 interface. We need to -// GetObject for that interface. If the node is acting as an IP version 4 -// router, it should absolutely have an Ipv4 interface. -// - Ptr ipv4 = node->GetObject (); - NS_ASSERT_MSG (ipv4, - "GlobalRouteManagerImpl::SPFIntraAddTransit (): " - "GetObject for interface failed"); -// -// Get the Global Router Link State Advertisement from the vertex we're -// adding the routes to. The LSA will have a number of attached Global Router -// Link Records corresponding to links off of that vertex / node. We're going -// to be interested in the records corresponding to point-to-point links. -// - GlobalRoutingLSA *lsa = v->GetLSA (); - NS_ASSERT_MSG (lsa, - "GlobalRouteManagerImpl::SPFIntraAddTransit (): " - "Expected valid LSA in SPFVertex* v"); - Ipv4Mask tempmask = lsa->GetNetworkLSANetworkMask (); - Ipv4Address tempip = lsa->GetLinkStateId (); - tempip = tempip.CombineMask (tempmask); - Ptr router = node->GetObject (); - if (!router) + NS_LOG_LOGIC("setting routes for node " << node->GetId()); + // + // Routing information is updated using the Ipv4 interface. We need to + // GetObject for that interface. If the node is acting as an IP version 4 + // router, it should absolutely have an Ipv4 interface. + // + Ptr ipv4 = node->GetObject(); + NS_ASSERT_MSG(ipv4, + "GlobalRouteManagerImpl::SPFIntraAddTransit (): " + "GetObject for interface failed"); + // + // Get the Global Router Link State Advertisement from the vertex we're + // adding the routes to. The LSA will have a number of attached Global Router + // Link Records corresponding to links off of that vertex / node. We're going + // to be interested in the records corresponding to point-to-point links. + // + GlobalRoutingLSA* lsa = v->GetLSA(); + NS_ASSERT_MSG(lsa, + "GlobalRouteManagerImpl::SPFIntraAddTransit (): " + "Expected valid LSA in SPFVertex* v"); + Ipv4Mask tempmask = lsa->GetNetworkLSANetworkMask(); + Ipv4Address tempip = lsa->GetLinkStateId(); + tempip = tempip.CombineMask(tempmask); + Ptr router = node->GetObject(); + if (!router) { - continue; + continue; } - Ptr gr = router->GetRoutingProtocol (); - NS_ASSERT (gr); - // walk through all available exit directions due to ECMP, - // and add host route for each of the exit direction toward - // the vertex 'v' - for (uint32_t i = 0; i < v->GetNRootExitDirections (); i++) + Ptr gr = router->GetRoutingProtocol(); + NS_ASSERT(gr); + // walk through all available exit directions due to ECMP, + // and add host route for each of the exit direction toward + // the vertex 'v' + for (uint32_t i = 0; i < v->GetNRootExitDirections(); i++) { - SPFVertex::NodeExit_t exit = v->GetRootExitDirection (i); - Ipv4Address nextHop = exit.first; - int32_t outIf = exit.second; + SPFVertex::NodeExit_t exit = v->GetRootExitDirection(i); + Ipv4Address nextHop = exit.first; + int32_t outIf = exit.second; - if (outIf >= 0) + if (outIf >= 0) { - gr->AddNetworkRouteTo (tempip, tempmask, nextHop, outIf); - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " add network route to " << tempip << - " using next hop " << nextHop << - " via interface " << outIf); + gr->AddNetworkRouteTo(tempip, tempmask, nextHop, outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " add network route to " << tempip + << " using next hop " << nextHop << " via interface " + << outIf); } - else + else { - NS_LOG_LOGIC ("(Route " << i << ") Node " << node->GetId () << - " NOT able to add network route to " << tempip << - " using next hop " << nextHop << - " since outgoing interface id is negative " << outIf); + NS_LOG_LOGIC("(Route " << i << ") Node " << node->GetId() + << " NOT able to add network route to " << tempip + << " using next hop " << nextHop + << " since outgoing interface id is negative " << outIf); } } } @@ -2197,22 +2180,20 @@ GlobalRouteManagerImpl::SPFIntraAddTransit (SPFVertex* v) // already has set and adds itself to that vertex's list of children. // void -GlobalRouteManagerImpl::SPFVertexAddParent (SPFVertex* v) +GlobalRouteManagerImpl::SPFVertexAddParent(SPFVertex* v) { - NS_LOG_FUNCTION (this << v); + NS_LOG_FUNCTION(this << v); - for (uint32_t i=0;;) + for (uint32_t i = 0;;) { - SPFVertex* parent; - // check if all parents of vertex v - if ((parent = v->GetParent (i++)) == nullptr) + SPFVertex* parent; + // check if all parents of vertex v + if ((parent = v->GetParent(i++)) == nullptr) { - break; + break; } - parent->AddChild (v); + parent->AddChild(v); } } } // namespace ns3 - - diff --git a/src/internet/model/ipv4-end-point-demux.cc b/src/internet/model/ipv4-end-point-demux.cc index 26e613648..b3ae6d267 100644 --- a/src/internet/model/ipv4-end-point-demux.cc +++ b/src/internet/model/ipv4-end-point-demux.cc @@ -19,155 +19,158 @@ */ #include "ipv4-end-point-demux.h" + #include "ipv4-end-point.h" #include "ipv4-interface-address.h" + #include "ns3/log.h" - -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("Ipv4EndPointDemux"); - -Ipv4EndPointDemux::Ipv4EndPointDemux () - : m_ephemeral (1024), m_portLast (65535), m_portFirst (1024) +namespace ns3 { - NS_LOG_FUNCTION (this); + +NS_LOG_COMPONENT_DEFINE("Ipv4EndPointDemux"); + +Ipv4EndPointDemux::Ipv4EndPointDemux() + : m_ephemeral(1024), + m_portLast(65535), + m_portFirst(1024) +{ + NS_LOG_FUNCTION(this); } -Ipv4EndPointDemux::~Ipv4EndPointDemux () +Ipv4EndPointDemux::~Ipv4EndPointDemux() { - NS_LOG_FUNCTION (this); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - Ipv4EndPoint *endPoint = *i; - delete endPoint; + Ipv4EndPoint* endPoint = *i; + delete endPoint; } - m_endPoints.clear (); + m_endPoints.clear(); } bool -Ipv4EndPointDemux::LookupPortLocal (uint16_t port) +Ipv4EndPointDemux::LookupPortLocal(uint16_t port) { - NS_LOG_FUNCTION (this << port); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << port); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == port) + if ((*i)->GetLocalPort() == port) { - return true; + return true; } } - return false; + return false; } bool -Ipv4EndPointDemux::LookupLocal (Ptr boundNetDevice, Ipv4Address addr, uint16_t port) +Ipv4EndPointDemux::LookupLocal(Ptr boundNetDevice, Ipv4Address addr, uint16_t port) { - NS_LOG_FUNCTION (this << addr << port); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << addr << port); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == port && - (*i)->GetLocalAddress () == addr && - (*i)->GetBoundNetDevice () == boundNetDevice) + if ((*i)->GetLocalPort() == port && (*i)->GetLocalAddress() == addr && + (*i)->GetBoundNetDevice() == boundNetDevice) { - return true; + return true; } } - return false; + return false; } -Ipv4EndPoint * -Ipv4EndPointDemux::Allocate () +Ipv4EndPoint* +Ipv4EndPointDemux::Allocate() { - NS_LOG_FUNCTION (this); - uint16_t port = AllocateEphemeralPort (); - if (port == 0) + NS_LOG_FUNCTION(this); + uint16_t port = AllocateEphemeralPort(); + if (port == 0) { - NS_LOG_WARN ("Ephemeral port allocation failed."); - return nullptr; + NS_LOG_WARN("Ephemeral port allocation failed."); + return nullptr; } - Ipv4EndPoint *endPoint = new Ipv4EndPoint (Ipv4Address::GetAny (), port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv4EndPoint* endPoint = new Ipv4EndPoint(Ipv4Address::GetAny(), port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv4EndPoint * -Ipv4EndPointDemux::Allocate (Ipv4Address address) +Ipv4EndPoint* +Ipv4EndPointDemux::Allocate(Ipv4Address address) { - NS_LOG_FUNCTION (this << address); - uint16_t port = AllocateEphemeralPort (); - if (port == 0) + NS_LOG_FUNCTION(this << address); + uint16_t port = AllocateEphemeralPort(); + if (port == 0) { - NS_LOG_WARN ("Ephemeral port allocation failed."); - return nullptr; + NS_LOG_WARN("Ephemeral port allocation failed."); + return nullptr; } - Ipv4EndPoint *endPoint = new Ipv4EndPoint (address, port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv4EndPoint* endPoint = new Ipv4EndPoint(address, port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv4EndPoint * -Ipv4EndPointDemux::Allocate (Ptr boundNetDevice, uint16_t port) +Ipv4EndPoint* +Ipv4EndPointDemux::Allocate(Ptr boundNetDevice, uint16_t port) { - NS_LOG_FUNCTION (this << port << boundNetDevice); + NS_LOG_FUNCTION(this << port << boundNetDevice); - return Allocate (boundNetDevice, Ipv4Address::GetAny (), port); + return Allocate(boundNetDevice, Ipv4Address::GetAny(), port); } -Ipv4EndPoint * -Ipv4EndPointDemux::Allocate (Ptr boundNetDevice, Ipv4Address address, uint16_t port) +Ipv4EndPoint* +Ipv4EndPointDemux::Allocate(Ptr boundNetDevice, Ipv4Address address, uint16_t port) { - NS_LOG_FUNCTION (this << address << port << boundNetDevice); - if (LookupLocal (boundNetDevice, address, port) || LookupLocal (nullptr, address, port)) + NS_LOG_FUNCTION(this << address << port << boundNetDevice); + if (LookupLocal(boundNetDevice, address, port) || LookupLocal(nullptr, address, port)) { - NS_LOG_WARN ("Duplicated endpoint."); - return nullptr; + NS_LOG_WARN("Duplicated endpoint."); + return nullptr; } - Ipv4EndPoint *endPoint = new Ipv4EndPoint (address, port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv4EndPoint* endPoint = new Ipv4EndPoint(address, port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv4EndPoint * -Ipv4EndPointDemux::Allocate (Ptr boundNetDevice, - Ipv4Address localAddress, uint16_t localPort, - Ipv4Address peerAddress, uint16_t peerPort) +Ipv4EndPoint* +Ipv4EndPointDemux::Allocate(Ptr boundNetDevice, + Ipv4Address localAddress, + uint16_t localPort, + Ipv4Address peerAddress, + uint16_t peerPort) { - NS_LOG_FUNCTION (this << localAddress << localPort << peerAddress << peerPort << boundNetDevice); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << localAddress << localPort << peerAddress << peerPort << boundNetDevice); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == localPort && - (*i)->GetLocalAddress () == localAddress && - (*i)->GetPeerPort () == peerPort && - (*i)->GetPeerAddress () == peerAddress && - ((*i)->GetBoundNetDevice () == boundNetDevice || !(*i)->GetBoundNetDevice ())) + if ((*i)->GetLocalPort() == localPort && (*i)->GetLocalAddress() == localAddress && + (*i)->GetPeerPort() == peerPort && (*i)->GetPeerAddress() == peerAddress && + ((*i)->GetBoundNetDevice() == boundNetDevice || !(*i)->GetBoundNetDevice())) { - NS_LOG_WARN ("Duplicated endpoint."); - return nullptr; + NS_LOG_WARN("Duplicated endpoint."); + return nullptr; } } - Ipv4EndPoint *endPoint = new Ipv4EndPoint (localAddress, localPort); - endPoint->SetPeer (peerAddress, peerPort); - m_endPoints.push_back (endPoint); + Ipv4EndPoint* endPoint = new Ipv4EndPoint(localAddress, localPort); + endPoint->SetPeer(peerAddress, peerPort); + m_endPoints.push_back(endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); - return endPoint; + return endPoint; } void -Ipv4EndPointDemux::DeAllocate (Ipv4EndPoint *endPoint) +Ipv4EndPointDemux::DeAllocate(Ipv4EndPoint* endPoint) { - NS_LOG_FUNCTION (this << endPoint); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << endPoint); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if (*i == endPoint) + if (*i == endPoint) { - delete endPoint; - m_endPoints.erase (i); - break; + delete endPoint; + m_endPoints.erase(i); + break; } } } @@ -176,247 +179,255 @@ Ipv4EndPointDemux::DeAllocate (Ipv4EndPoint *endPoint) * return list of all available Endpoints */ Ipv4EndPointDemux::EndPoints -Ipv4EndPointDemux::GetAllEndPoints () +Ipv4EndPointDemux::GetAllEndPoints() { - NS_LOG_FUNCTION (this); - EndPoints ret; + NS_LOG_FUNCTION(this); + EndPoints ret; - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - Ipv4EndPoint* endP = *i; - ret.push_back (endP); + Ipv4EndPoint* endP = *i; + ret.push_back(endP); } - return ret; + return ret; } - /* * If we have an exact match, we return it. * Otherwise, if we find a generic match, we return it. * Otherwise, we return 0. */ Ipv4EndPointDemux::EndPoints -Ipv4EndPointDemux::Lookup (Ipv4Address daddr, uint16_t dport, - Ipv4Address saddr, uint16_t sport, - Ptr incomingInterface) +Ipv4EndPointDemux::Lookup(Ipv4Address daddr, + uint16_t dport, + Ipv4Address saddr, + uint16_t sport, + Ptr incomingInterface) { - NS_LOG_FUNCTION (this << daddr << dport << saddr << sport << incomingInterface); + NS_LOG_FUNCTION(this << daddr << dport << saddr << sport << incomingInterface); - EndPoints retval1; // Matches exact on local port, wildcards on others - EndPoints retval2; // Matches exact on local port/adder, wildcards on others - EndPoints retval3; // Matches all but local address - EndPoints retval4; // Exact match on all 4 + EndPoints retval1; // Matches exact on local port, wildcards on others + EndPoints retval2; // Matches exact on local port/adder, wildcards on others + EndPoints retval3; // Matches all but local address + EndPoints retval4; // Exact match on all 4 - NS_LOG_DEBUG ("Looking up endpoint for destination address " << daddr << ":" << dport); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_DEBUG("Looking up endpoint for destination address " << daddr << ":" << dport); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - Ipv4EndPoint* endP = *i; + Ipv4EndPoint* endP = *i; - NS_LOG_DEBUG ("Looking at endpoint dport=" << endP->GetLocalPort () - << " daddr=" << endP->GetLocalAddress () - << " sport=" << endP->GetPeerPort () - << " saddr=" << endP->GetPeerAddress ()); + NS_LOG_DEBUG("Looking at endpoint dport=" + << endP->GetLocalPort() << " daddr=" << endP->GetLocalAddress() + << " sport=" << endP->GetPeerPort() << " saddr=" << endP->GetPeerAddress()); - if (!endP->IsRxEnabled ()) + if (!endP->IsRxEnabled()) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint can not receive packets"); - continue; + NS_LOG_LOGIC("Skipping endpoint " << &endP + << " because endpoint can not receive packets"); + continue; } - if (endP->GetLocalPort () != dport) + if (endP->GetLocalPort() != dport) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint dport " - << endP->GetLocalPort () - << " does not match packet dport " << dport); - continue; + NS_LOG_LOGIC("Skipping endpoint " << &endP << " because endpoint dport " + << endP->GetLocalPort() + << " does not match packet dport " << dport); + continue; } - if (endP->GetBoundNetDevice ()) + if (endP->GetBoundNetDevice()) { - if (endP->GetBoundNetDevice () != incomingInterface->GetDevice ()) + if (endP->GetBoundNetDevice() != incomingInterface->GetDevice()) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint is bound to specific device and" - << endP->GetBoundNetDevice () - << " does not match packet device " << incomingInterface->GetDevice ()); - continue; + NS_LOG_LOGIC("Skipping endpoint " + << &endP << " because endpoint is bound to specific device and" + << endP->GetBoundNetDevice() << " does not match packet device " + << incomingInterface->GetDevice()); + continue; } } - bool localAddressMatchesExact = false; - bool localAddressIsAny = false; - bool localAddressIsSubnetAny = false; + bool localAddressMatchesExact = false; + bool localAddressIsAny = false; + bool localAddressIsSubnetAny = false; - // We have 3 cases: - // 1) Exact local / destination address match - // 2) Local endpoint bound to Any -> matches anything - // 3) Local endpoint bound to x.y.z.0 -> matches Subnet-directed broadcast packet (e.g., x.y.z.255 in a /24 net) and direct destination match. + // We have 3 cases: + // 1) Exact local / destination address match + // 2) Local endpoint bound to Any -> matches anything + // 3) Local endpoint bound to x.y.z.0 -> matches Subnet-directed broadcast packet (e.g., + // x.y.z.255 in a /24 net) and direct destination match. - if (endP->GetLocalAddress () == daddr) + if (endP->GetLocalAddress() == daddr) { - // Case 1: - localAddressMatchesExact = true; + // Case 1: + localAddressMatchesExact = true; } - else if (endP->GetLocalAddress () == Ipv4Address::GetAny ()) + else if (endP->GetLocalAddress() == Ipv4Address::GetAny()) { - // Case 2: - localAddressIsAny = true; + // Case 2: + localAddressIsAny = true; } - else + else { - // Case 3: - for (uint32_t i = 0; i < incomingInterface->GetNAddresses (); i++) + // Case 3: + for (uint32_t i = 0; i < incomingInterface->GetNAddresses(); i++) { - Ipv4InterfaceAddress addr = incomingInterface->GetAddress (i); + Ipv4InterfaceAddress addr = incomingInterface->GetAddress(i); - Ipv4Address addrNetpart = addr.GetLocal ().CombineMask (addr.GetMask ()); - if (endP->GetLocalAddress () == addrNetpart) + Ipv4Address addrNetpart = addr.GetLocal().CombineMask(addr.GetMask()); + if (endP->GetLocalAddress() == addrNetpart) { - NS_LOG_LOGIC ("Endpoint is SubnetDirectedAny " << endP->GetLocalAddress () << "/" << addr.GetMask ().GetPrefixLength ()); + NS_LOG_LOGIC("Endpoint is SubnetDirectedAny " + << endP->GetLocalAddress() << "/" + << addr.GetMask().GetPrefixLength()); - Ipv4Address daddrNetPart = daddr.CombineMask (addr.GetMask ()); - if (addrNetpart == daddrNetPart) + Ipv4Address daddrNetPart = daddr.CombineMask(addr.GetMask()); + if (addrNetpart == daddrNetPart) { - localAddressIsSubnetAny = true; + localAddressIsSubnetAny = true; } } } - // if no match here, keep looking - if (!localAddressIsSubnetAny) + // if no match here, keep looking + if (!localAddressIsSubnetAny) { - continue; + continue; } } - bool remotePortMatchesExact = endP->GetPeerPort () == sport; - bool remotePortMatchesWildCard = endP->GetPeerPort () == 0; - bool remoteAddressMatchesExact = endP->GetPeerAddress () == saddr; - bool remoteAddressMatchesWildCard = endP->GetPeerAddress () == Ipv4Address::GetAny (); + bool remotePortMatchesExact = endP->GetPeerPort() == sport; + bool remotePortMatchesWildCard = endP->GetPeerPort() == 0; + bool remoteAddressMatchesExact = endP->GetPeerAddress() == saddr; + bool remoteAddressMatchesWildCard = endP->GetPeerAddress() == Ipv4Address::GetAny(); - // If remote does not match either with exact or wildcard, - // skip this one - if (!(remotePortMatchesExact || remotePortMatchesWildCard)) + // If remote does not match either with exact or wildcard, + // skip this one + if (!(remotePortMatchesExact || remotePortMatchesWildCard)) { - continue; + continue; } - if (!(remoteAddressMatchesExact || remoteAddressMatchesWildCard)) + if (!(remoteAddressMatchesExact || remoteAddressMatchesWildCard)) { - continue; + continue; } - bool localAddressMatchesWildCard = localAddressIsAny || localAddressIsSubnetAny; + bool localAddressMatchesWildCard = localAddressIsAny || localAddressIsSubnetAny; - if (localAddressMatchesExact && remoteAddressMatchesExact && remotePortMatchesExact) + if (localAddressMatchesExact && remoteAddressMatchesExact && remotePortMatchesExact) { // All 4 match - this is the case of an open TCP connection, for example. - NS_LOG_LOGIC ("Found an endpoint for case 4, adding " << endP->GetLocalAddress () << ":" << endP->GetLocalPort ()); - retval4.push_back (endP); + NS_LOG_LOGIC("Found an endpoint for case 4, adding " << endP->GetLocalAddress() << ":" + << endP->GetLocalPort()); + retval4.push_back(endP); } - if (localAddressMatchesWildCard && remoteAddressMatchesExact && remotePortMatchesExact) + if (localAddressMatchesWildCard && remoteAddressMatchesExact && remotePortMatchesExact) { // All but local address - no idea what this case could be. - NS_LOG_LOGIC ("Found an endpoint for case 3, adding " << endP->GetLocalAddress () << ":" << endP->GetLocalPort ()); - retval3.push_back (endP); + NS_LOG_LOGIC("Found an endpoint for case 3, adding " << endP->GetLocalAddress() << ":" + << endP->GetLocalPort()); + retval3.push_back(endP); } - if (localAddressMatchesExact && remoteAddressMatchesWildCard && remotePortMatchesWildCard) + if (localAddressMatchesExact && remoteAddressMatchesWildCard && remotePortMatchesWildCard) { // Only local port and local address matches exactly - Not yet opened connection - NS_LOG_LOGIC ("Found an endpoint for case 2, adding " << endP->GetLocalAddress () << ":" << endP->GetLocalPort ()); - retval2.push_back (endP); + NS_LOG_LOGIC("Found an endpoint for case 2, adding " << endP->GetLocalAddress() << ":" + << endP->GetLocalPort()); + retval2.push_back(endP); } - if (localAddressMatchesWildCard && remoteAddressMatchesWildCard && remotePortMatchesWildCard) + if (localAddressMatchesWildCard && remoteAddressMatchesWildCard && + remotePortMatchesWildCard) { // Only local port matches exactly - Endpoint open to "any" connection - NS_LOG_LOGIC ("Found an endpoint for case 1, adding " << endP->GetLocalAddress () << ":" << endP->GetLocalPort ()); - retval1.push_back (endP); + NS_LOG_LOGIC("Found an endpoint for case 1, adding " << endP->GetLocalAddress() << ":" + << endP->GetLocalPort()); + retval1.push_back(endP); } } - // Here we find the most exact match - EndPoints retval; - if (!retval4.empty ()) + // Here we find the most exact match + EndPoints retval; + if (!retval4.empty()) { - retval = retval4; + retval = retval4; } - else if (!retval3.empty ()) + else if (!retval3.empty()) { - retval = retval3; + retval = retval3; } - else if (!retval2.empty ()) + else if (!retval2.empty()) { - retval = retval2; + retval = retval2; } - else + else { - retval = retval1; + retval = retval1; } - NS_ABORT_MSG_IF (retval.size () > 1, "Too many endpoints - perhaps you created too many sockets without binding them to different NetDevices."); - return retval; // might be empty if no matches + NS_ABORT_MSG_IF(retval.size() > 1, + "Too many endpoints - perhaps you created too many sockets without binding " + "them to different NetDevices."); + return retval; // might be empty if no matches } -Ipv4EndPoint * -Ipv4EndPointDemux::SimpleLookup (Ipv4Address daddr, - uint16_t dport, - Ipv4Address saddr, - uint16_t sport) +Ipv4EndPoint* +Ipv4EndPointDemux::SimpleLookup(Ipv4Address daddr, + uint16_t dport, + Ipv4Address saddr, + uint16_t sport) { - NS_LOG_FUNCTION (this << daddr << dport << saddr << sport); + NS_LOG_FUNCTION(this << daddr << dport << saddr << sport); - // this code is a copy/paste version of an old BSD ip stack lookup - // function. - uint32_t genericity = 3; - Ipv4EndPoint *generic = nullptr; - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + // this code is a copy/paste version of an old BSD ip stack lookup + // function. + uint32_t genericity = 3; + Ipv4EndPoint* generic = nullptr; + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () != dport) + if ((*i)->GetLocalPort() != dport) { - continue; + continue; } - if ((*i)->GetLocalAddress () == daddr && - (*i)->GetPeerPort () == sport && - (*i)->GetPeerAddress () == saddr) + if ((*i)->GetLocalAddress() == daddr && (*i)->GetPeerPort() == sport && + (*i)->GetPeerAddress() == saddr) { - /* this is an exact match. */ - return *i; + /* this is an exact match. */ + return *i; } - uint32_t tmp = 0; - if ((*i)->GetLocalAddress () == Ipv4Address::GetAny ()) + uint32_t tmp = 0; + if ((*i)->GetLocalAddress() == Ipv4Address::GetAny()) { - tmp++; + tmp++; } - if ((*i)->GetPeerAddress () == Ipv4Address::GetAny ()) + if ((*i)->GetPeerAddress() == Ipv4Address::GetAny()) { - tmp++; + tmp++; } - if (tmp < genericity) + if (tmp < genericity) { - generic = (*i); - genericity = tmp; + generic = (*i); + genericity = tmp; } } - return generic; + return generic; } + uint16_t -Ipv4EndPointDemux::AllocateEphemeralPort () +Ipv4EndPointDemux::AllocateEphemeralPort() { - // Similar to counting up logic in netinet/in_pcb.c - NS_LOG_FUNCTION (this); - uint16_t port = m_ephemeral; - int count = m_portLast - m_portFirst; - do + // Similar to counting up logic in netinet/in_pcb.c + NS_LOG_FUNCTION(this); + uint16_t port = m_ephemeral; + int count = m_portLast - m_portFirst; + do { - if (count-- < 0) + if (count-- < 0) { - return 0; + return 0; } - ++port; - if (port < m_portFirst || port > m_portLast) + ++port; + if (port < m_portFirst || port > m_portLast) { - port = m_portFirst; + port = m_portFirst; } - } while (LookupPortLocal (port)); - m_ephemeral = port; - return port; + } while (LookupPortLocal(port)); + m_ephemeral = port; + return port; } } // namespace ns3 - diff --git a/src/internet/model/ipv4-global-routing.cc b/src/internet/model/ipv4-global-routing.cc index 43ba885f1..2fec0e781 100644 --- a/src/internet/model/ipv4-global-routing.cc +++ b/src/internet/model/ipv4-global-routing.cc @@ -16,609 +16,593 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -#include -#include -#include "ns3/names.h" -#include "ns3/log.h" -#include "ns3/simulator.h" -#include "ns3/object.h" -#include "ns3/packet.h" -#include "ns3/net-device.h" +#include "ipv4-global-routing.h" + +#include "global-route-manager.h" +#include "ipv4-queue-disc-item.h" + +#include "ns3/boolean.h" #include "ns3/ipv4-route.h" #include "ns3/ipv4-routing-table-entry.h" -#include "ns3/boolean.h" +#include "ns3/log.h" +#include "ns3/names.h" +#include "ns3/net-device.h" #include "ns3/node.h" -#include "ipv4-queue-disc-item.h" -#include "ipv4-global-routing.h" -#include "global-route-manager.h" +#include "ns3/object.h" +#include "ns3/packet.h" +#include "ns3/simulator.h" -namespace ns3 { +#include +#include -NS_LOG_COMPONENT_DEFINE ("Ipv4GlobalRouting"); +namespace ns3 +{ -NS_OBJECT_ENSURE_REGISTERED (Ipv4GlobalRouting); +NS_LOG_COMPONENT_DEFINE("Ipv4GlobalRouting"); + +NS_OBJECT_ENSURE_REGISTERED(Ipv4GlobalRouting); TypeId -Ipv4GlobalRouting::GetTypeId () +Ipv4GlobalRouting::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv4GlobalRouting") - .SetParent () - .SetGroupName ("Internet") - .AddAttribute ("RandomEcmpRouting", - "Set to true if packets are randomly routed among ECMP; set to false for using only one route consistently", - BooleanValue (false), - MakeBooleanAccessor (&Ipv4GlobalRouting::m_randomEcmpRouting), - MakeBooleanChecker ()) - .AddAttribute ("FlowEcmpRouting", - "Set to true if flows are randomly routed among ECMP; set to false for using only one route consistently", - BooleanValue (false), - MakeBooleanAccessor (&Ipv4GlobalRouting::m_flowEcmpRouting), - MakeBooleanChecker ()) - .AddAttribute ("RespondToInterfaceEvents", - "Set to true if you want to dynamically recompute the global routes upon Interface notification events (up/down, or add/remove address)", - BooleanValue (false), - MakeBooleanAccessor (&Ipv4GlobalRouting::m_respondToInterfaceEvents), - MakeBooleanChecker ()) - ; - return tid; + static TypeId tid = + TypeId("ns3::Ipv4GlobalRouting") + .SetParent() + .SetGroupName("Internet") + .AddAttribute("RandomEcmpRouting", + "Set to true if packets are randomly routed among ECMP; set to false for " + "using only one route consistently", + BooleanValue(false), + MakeBooleanAccessor(&Ipv4GlobalRouting::m_randomEcmpRouting), + MakeBooleanChecker()) + .AddAttribute("FlowEcmpRouting", + "Set to true if flows are randomly routed among ECMP; set to false for " + "using only one route consistently", + BooleanValue(false), + MakeBooleanAccessor(&Ipv4GlobalRouting::m_flowEcmpRouting), + MakeBooleanChecker()) + .AddAttribute("RespondToInterfaceEvents", + "Set to true if you want to dynamically recompute the global routes upon " + "Interface notification events (up/down, or add/remove address)", + BooleanValue(false), + MakeBooleanAccessor(&Ipv4GlobalRouting::m_respondToInterfaceEvents), + MakeBooleanChecker()); + return tid; } -Ipv4GlobalRouting::Ipv4GlobalRouting () - : m_randomEcmpRouting (false), - m_respondToInterfaceEvents (false) +Ipv4GlobalRouting::Ipv4GlobalRouting() + : m_randomEcmpRouting(false), + m_respondToInterfaceEvents(false) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_rand = CreateObject (); + m_rand = CreateObject(); } -Ipv4GlobalRouting::~Ipv4GlobalRouting () +Ipv4GlobalRouting::~Ipv4GlobalRouting() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } void -Ipv4GlobalRouting::AddHostRouteTo (Ipv4Address dest, - Ipv4Address nextHop, - uint32_t interface) +Ipv4GlobalRouting::AddHostRouteTo(Ipv4Address dest, Ipv4Address nextHop, uint32_t interface) { - NS_LOG_FUNCTION (this << dest << nextHop << interface); - Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); - *route = Ipv4RoutingTableEntry::CreateHostRouteTo (dest, nextHop, interface); - m_hostRoutes.push_back (route); + NS_LOG_FUNCTION(this << dest << nextHop << interface); + Ipv4RoutingTableEntry* route = new Ipv4RoutingTableEntry(); + *route = Ipv4RoutingTableEntry::CreateHostRouteTo(dest, nextHop, interface); + m_hostRoutes.push_back(route); } void -Ipv4GlobalRouting::AddHostRouteTo (Ipv4Address dest, - uint32_t interface) +Ipv4GlobalRouting::AddHostRouteTo(Ipv4Address dest, uint32_t interface) { - NS_LOG_FUNCTION (this << dest << interface); - Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); - *route = Ipv4RoutingTableEntry::CreateHostRouteTo (dest, interface); - m_hostRoutes.push_back (route); + NS_LOG_FUNCTION(this << dest << interface); + Ipv4RoutingTableEntry* route = new Ipv4RoutingTableEntry(); + *route = Ipv4RoutingTableEntry::CreateHostRouteTo(dest, interface); + m_hostRoutes.push_back(route); } void -Ipv4GlobalRouting::AddNetworkRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - Ipv4Address nextHop, - uint32_t interface) +Ipv4GlobalRouting::AddNetworkRouteTo(Ipv4Address network, + Ipv4Mask networkMask, + Ipv4Address nextHop, + uint32_t interface) { - NS_LOG_FUNCTION (this << network << networkMask << nextHop << interface); - Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); - *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo (network, - networkMask, - nextHop, - interface); - m_networkRoutes.push_back (route); + NS_LOG_FUNCTION(this << network << networkMask << nextHop << interface); + Ipv4RoutingTableEntry* route = new Ipv4RoutingTableEntry(); + *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, nextHop, interface); + m_networkRoutes.push_back(route); } void -Ipv4GlobalRouting::AddNetworkRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - uint32_t interface) +Ipv4GlobalRouting::AddNetworkRouteTo(Ipv4Address network, Ipv4Mask networkMask, uint32_t interface) { - NS_LOG_FUNCTION (this << network << networkMask << interface); - Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); - *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo (network, - networkMask, - interface); - m_networkRoutes.push_back (route); + NS_LOG_FUNCTION(this << network << networkMask << interface); + Ipv4RoutingTableEntry* route = new Ipv4RoutingTableEntry(); + *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, interface); + m_networkRoutes.push_back(route); } void -Ipv4GlobalRouting::AddASExternalRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - Ipv4Address nextHop, - uint32_t interface) +Ipv4GlobalRouting::AddASExternalRouteTo(Ipv4Address network, + Ipv4Mask networkMask, + Ipv4Address nextHop, + uint32_t interface) { - NS_LOG_FUNCTION (this << network << networkMask << nextHop << interface); - Ipv4RoutingTableEntry *route = new Ipv4RoutingTableEntry (); - *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo (network, - networkMask, - nextHop, - interface); - m_ASexternalRoutes.push_back (route); + NS_LOG_FUNCTION(this << network << networkMask << nextHop << interface); + Ipv4RoutingTableEntry* route = new Ipv4RoutingTableEntry(); + *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, nextHop, interface); + m_ASexternalRoutes.push_back(route); } - Ptr -Ipv4GlobalRouting::LookupGlobal (Ipv4Address dest, uint32_t flowHash, Ptr oif) +Ipv4GlobalRouting::LookupGlobal(Ipv4Address dest, uint32_t flowHash, Ptr oif) { - NS_LOG_FUNCTION (this << dest << oif); - NS_LOG_LOGIC ("Looking for route for destination " << dest); - Ptr rtentry = nullptr; - // store all available routes that bring packets to their destination - typedef std::vector RouteVec_t; - RouteVec_t allRoutes; + NS_LOG_FUNCTION(this << dest << oif); + NS_LOG_LOGIC("Looking for route for destination " << dest); + Ptr rtentry = nullptr; + // store all available routes that bring packets to their destination + typedef std::vector RouteVec_t; + RouteVec_t allRoutes; - NS_LOG_LOGIC ("Number of m_hostRoutes = " << m_hostRoutes.size ()); - for (HostRoutesCI i = m_hostRoutes.begin (); - i != m_hostRoutes.end (); - i++) + NS_LOG_LOGIC("Number of m_hostRoutes = " << m_hostRoutes.size()); + for (HostRoutesCI i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++) { - NS_ASSERT ((*i)->IsHost ()); - if ((*i)->GetDest () == dest) + NS_ASSERT((*i)->IsHost()); + if ((*i)->GetDest() == dest) { - if (oif) + if (oif) { - if (oif != m_ipv4->GetNetDevice ((*i)->GetInterface ())) + if (oif != m_ipv4->GetNetDevice((*i)->GetInterface())) { - NS_LOG_LOGIC ("Not on requested interface, skipping"); - continue; + NS_LOG_LOGIC("Not on requested interface, skipping"); + continue; } } - allRoutes.push_back (*i); - NS_LOG_LOGIC (allRoutes.size () << "Found global host route" << *i); + allRoutes.push_back(*i); + NS_LOG_LOGIC(allRoutes.size() << "Found global host route" << *i); } } - if (allRoutes.size () == 0) // if no host route is found + if (allRoutes.size() == 0) // if no host route is found { - NS_LOG_LOGIC ("Number of m_networkRoutes" << m_networkRoutes.size ()); - for (NetworkRoutesI j = m_networkRoutes.begin (); - j != m_networkRoutes.end (); - j++) + NS_LOG_LOGIC("Number of m_networkRoutes" << m_networkRoutes.size()); + for (NetworkRoutesI j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++) { - Ipv4Mask mask = (*j)->GetDestNetworkMask (); - Ipv4Address entry = (*j)->GetDestNetwork (); - if (mask.IsMatch (dest, entry)) + Ipv4Mask mask = (*j)->GetDestNetworkMask(); + Ipv4Address entry = (*j)->GetDestNetwork(); + if (mask.IsMatch(dest, entry)) { - if (oif) + if (oif) { - if (oif != m_ipv4->GetNetDevice ((*j)->GetInterface ())) + if (oif != m_ipv4->GetNetDevice((*j)->GetInterface())) { - NS_LOG_LOGIC ("Not on requested interface, skipping"); - continue; + NS_LOG_LOGIC("Not on requested interface, skipping"); + continue; } } - allRoutes.push_back (*j); - NS_LOG_LOGIC (allRoutes.size () << "Found global network route" << *j); + allRoutes.push_back(*j); + NS_LOG_LOGIC(allRoutes.size() << "Found global network route" << *j); } } } - if (allRoutes.size () == 0) // consider external if no host/network found + if (allRoutes.size() == 0) // consider external if no host/network found { - for (ASExternalRoutesI k = m_ASexternalRoutes.begin (); - k != m_ASexternalRoutes.end (); - k++) + for (ASExternalRoutesI k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++) { - Ipv4Mask mask = (*k)->GetDestNetworkMask (); - Ipv4Address entry = (*k)->GetDestNetwork (); - if (mask.IsMatch (dest, entry)) + Ipv4Mask mask = (*k)->GetDestNetworkMask(); + Ipv4Address entry = (*k)->GetDestNetwork(); + if (mask.IsMatch(dest, entry)) { - NS_LOG_LOGIC ("Found external route" << *k); - if (oif) + NS_LOG_LOGIC("Found external route" << *k); + if (oif) { - if (oif != m_ipv4->GetNetDevice ((*k)->GetInterface ())) + if (oif != m_ipv4->GetNetDevice((*k)->GetInterface())) { - NS_LOG_LOGIC ("Not on requested interface, skipping"); - continue; + NS_LOG_LOGIC("Not on requested interface, skipping"); + continue; } } - allRoutes.push_back (*k); - break; + allRoutes.push_back(*k); + break; } } } - if (allRoutes.size () > 0 ) // if route(s) is found + if (allRoutes.size() > 0) // if route(s) is found { - // pick up one of the routes uniformly at random if random - // ECMP routing is enabled, or always select the first route - // consistently if random ECMP routing is disabled - uint32_t selectIndex; - if (m_flowEcmpRouting) + // pick up one of the routes uniformly at random if random + // ECMP routing is enabled, or always select the first route + // consistently if random ECMP routing is disabled + uint32_t selectIndex; + if (m_flowEcmpRouting) { - selectIndex = flowHash % allRoutes.size (); + selectIndex = flowHash % allRoutes.size(); } - else if (m_randomEcmpRouting) + else if (m_randomEcmpRouting) { - selectIndex = m_rand->GetInteger (0, allRoutes.size ()-1); + selectIndex = m_rand->GetInteger(0, allRoutes.size() - 1); } - else + else { - selectIndex = 0; + selectIndex = 0; } - Ipv4RoutingTableEntry* route = allRoutes.at (selectIndex); - // create a Ipv4Route object from the selected routing table entry - rtentry = Create (); - rtentry->SetDestination (route->GetDest ()); - /// \todo handle multi-address case - rtentry->SetSource (m_ipv4->GetAddress (route->GetInterface (), 0).GetLocal ()); - rtentry->SetGateway (route->GetGateway ()); - uint32_t interfaceIdx = route->GetInterface (); - rtentry->SetOutputDevice (m_ipv4->GetNetDevice (interfaceIdx)); - return rtentry; + Ipv4RoutingTableEntry* route = allRoutes.at(selectIndex); + // create a Ipv4Route object from the selected routing table entry + rtentry = Create(); + rtentry->SetDestination(route->GetDest()); + /// \todo handle multi-address case + rtentry->SetSource(m_ipv4->GetAddress(route->GetInterface(), 0).GetLocal()); + rtentry->SetGateway(route->GetGateway()); + uint32_t interfaceIdx = route->GetInterface(); + rtentry->SetOutputDevice(m_ipv4->GetNetDevice(interfaceIdx)); + return rtentry; } - else + else { - return nullptr; + return nullptr; } } uint32_t -Ipv4GlobalRouting::GetNRoutes () const +Ipv4GlobalRouting::GetNRoutes() const { - NS_LOG_FUNCTION (this); - uint32_t n = 0; - n += m_hostRoutes.size (); - n += m_networkRoutes.size (); - n += m_ASexternalRoutes.size (); - return n; + NS_LOG_FUNCTION(this); + uint32_t n = 0; + n += m_hostRoutes.size(); + n += m_networkRoutes.size(); + n += m_ASexternalRoutes.size(); + return n; } -Ipv4RoutingTableEntry * -Ipv4GlobalRouting::GetRoute (uint32_t index) const +Ipv4RoutingTableEntry* +Ipv4GlobalRouting::GetRoute(uint32_t index) const { - NS_LOG_FUNCTION (this << index); - if (index < m_hostRoutes.size ()) + NS_LOG_FUNCTION(this << index); + if (index < m_hostRoutes.size()) { - uint32_t tmp = 0; - for (HostRoutesCI i = m_hostRoutes.begin (); - i != m_hostRoutes.end (); - i++) + uint32_t tmp = 0; + for (HostRoutesCI i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++) { - if (tmp == index) + if (tmp == index) { - return *i; + return *i; } - tmp++; + tmp++; } } - index -= m_hostRoutes.size (); - uint32_t tmp = 0; - if (index < m_networkRoutes.size ()) + index -= m_hostRoutes.size(); + uint32_t tmp = 0; + if (index < m_networkRoutes.size()) { - for (NetworkRoutesCI j = m_networkRoutes.begin (); - j != m_networkRoutes.end (); - j++) + for (NetworkRoutesCI j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++) { - if (tmp == index) + if (tmp == index) { - return *j; + return *j; } - tmp++; + tmp++; } } - index -= m_networkRoutes.size (); - tmp = 0; - for (ASExternalRoutesCI k = m_ASexternalRoutes.begin (); - k != m_ASexternalRoutes.end (); - k++) + index -= m_networkRoutes.size(); + tmp = 0; + for (ASExternalRoutesCI k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++) { - if (tmp == index) + if (tmp == index) { - return *k; + return *k; } - tmp++; + tmp++; } - NS_ASSERT (false); - // quiet compiler. - return nullptr; + NS_ASSERT(false); + // quiet compiler. + return nullptr; } + void -Ipv4GlobalRouting::RemoveRoute (uint32_t index) +Ipv4GlobalRouting::RemoveRoute(uint32_t index) { - NS_LOG_FUNCTION (this << index); - if (index < m_hostRoutes.size ()) + NS_LOG_FUNCTION(this << index); + if (index < m_hostRoutes.size()) { - uint32_t tmp = 0; - for (HostRoutesI i = m_hostRoutes.begin (); - i != m_hostRoutes.end (); - i++) + uint32_t tmp = 0; + for (HostRoutesI i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++) { - if (tmp == index) + if (tmp == index) { - NS_LOG_LOGIC ("Removing route " << index << "; size = " << m_hostRoutes.size ()); - delete *i; - m_hostRoutes.erase (i); - NS_LOG_LOGIC ("Done removing host route " << index << "; host route remaining size = " << m_hostRoutes.size ()); - return; + NS_LOG_LOGIC("Removing route " << index << "; size = " << m_hostRoutes.size()); + delete *i; + m_hostRoutes.erase(i); + NS_LOG_LOGIC("Done removing host route " + << index << "; host route remaining size = " << m_hostRoutes.size()); + return; } - tmp++; + tmp++; } } - index -= m_hostRoutes.size (); - uint32_t tmp = 0; - for (NetworkRoutesI j = m_networkRoutes.begin (); - j != m_networkRoutes.end (); - j++) + index -= m_hostRoutes.size(); + uint32_t tmp = 0; + for (NetworkRoutesI j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++) { - if (tmp == index) + if (tmp == index) { - NS_LOG_LOGIC ("Removing route " << index << "; size = " << m_networkRoutes.size ()); - delete *j; - m_networkRoutes.erase (j); - NS_LOG_LOGIC ("Done removing network route " << index << "; network route remaining size = " << m_networkRoutes.size ()); - return; + NS_LOG_LOGIC("Removing route " << index << "; size = " << m_networkRoutes.size()); + delete *j; + m_networkRoutes.erase(j); + NS_LOG_LOGIC("Done removing network route " + << index << "; network route remaining size = " << m_networkRoutes.size()); + return; } - tmp++; + tmp++; } - index -= m_networkRoutes.size (); - tmp = 0; - for (ASExternalRoutesI k = m_ASexternalRoutes.begin (); - k != m_ASexternalRoutes.end (); - k++) + index -= m_networkRoutes.size(); + tmp = 0; + for (ASExternalRoutesI k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++) { - if (tmp == index) + if (tmp == index) { - NS_LOG_LOGIC ("Removing route " << index << "; size = " << m_ASexternalRoutes.size ()); - delete *k; - m_ASexternalRoutes.erase (k); - NS_LOG_LOGIC ("Done removing network route " << index << "; network route remaining size = " << m_networkRoutes.size ()); - return; + NS_LOG_LOGIC("Removing route " << index << "; size = " << m_ASexternalRoutes.size()); + delete *k; + m_ASexternalRoutes.erase(k); + NS_LOG_LOGIC("Done removing network route " + << index << "; network route remaining size = " << m_networkRoutes.size()); + return; } - tmp++; + tmp++; } - NS_ASSERT (false); + NS_ASSERT(false); } int64_t -Ipv4GlobalRouting::AssignStreams (int64_t stream) +Ipv4GlobalRouting::AssignStreams(int64_t stream) { - NS_LOG_FUNCTION (this << stream); - m_rand->SetStream (stream); - return 1; + NS_LOG_FUNCTION(this << stream); + m_rand->SetStream(stream); + return 1; } void -Ipv4GlobalRouting::DoDispose () +Ipv4GlobalRouting::DoDispose() { - NS_LOG_FUNCTION (this); - for (HostRoutesI i = m_hostRoutes.begin (); - i != m_hostRoutes.end (); - i = m_hostRoutes.erase (i)) + NS_LOG_FUNCTION(this); + for (HostRoutesI i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i = m_hostRoutes.erase(i)) { - delete (*i); + delete (*i); } - for (NetworkRoutesI j = m_networkRoutes.begin (); - j != m_networkRoutes.end (); - j = m_networkRoutes.erase (j)) + for (NetworkRoutesI j = m_networkRoutes.begin(); j != m_networkRoutes.end(); + j = m_networkRoutes.erase(j)) { - delete (*j); + delete (*j); } - for (ASExternalRoutesI l = m_ASexternalRoutes.begin (); - l != m_ASexternalRoutes.end (); - l = m_ASexternalRoutes.erase (l)) + for (ASExternalRoutesI l = m_ASexternalRoutes.begin(); l != m_ASexternalRoutes.end(); + l = m_ASexternalRoutes.erase(l)) { - delete (*l); + delete (*l); } - Ipv4RoutingProtocol::DoDispose (); + Ipv4RoutingProtocol::DoDispose(); } // Formatted like output of "route -n" command void -Ipv4GlobalRouting::PrintRoutingTable (Ptr stream, Time::Unit unit) const +Ipv4GlobalRouting::PrintRoutingTable(Ptr stream, Time::Unit unit) const { - NS_LOG_FUNCTION (this << stream); - std::ostream* os = stream->GetStream (); - // Copy the current ostream state - std::ios oldState (nullptr); - oldState.copyfmt (*os); + NS_LOG_FUNCTION(this << stream); + std::ostream* os = stream->GetStream(); + // Copy the current ostream state + std::ios oldState(nullptr); + oldState.copyfmt(*os); - *os << std::resetiosflags (std::ios::adjustfield) << std::setiosflags (std::ios::left); + *os << std::resetiosflags(std::ios::adjustfield) << std::setiosflags(std::ios::left); - *os << "Node: " << m_ipv4->GetObject ()->GetId () - << ", Time: " << Now().As (unit) - << ", Local time: " << m_ipv4->GetObject ()->GetLocalTime ().As (unit) - << ", Ipv4GlobalRouting table" << std::endl; + *os << "Node: " << m_ipv4->GetObject()->GetId() << ", Time: " << Now().As(unit) + << ", Local time: " << m_ipv4->GetObject()->GetLocalTime().As(unit) + << ", Ipv4GlobalRouting table" << std::endl; - if (GetNRoutes () > 0) + if (GetNRoutes() > 0) { - *os << "Destination Gateway Genmask Flags Metric Ref Use Iface" << std::endl; - for (uint32_t j = 0; j < GetNRoutes (); j++) + *os << "Destination Gateway Genmask Flags Metric Ref Use Iface" + << std::endl; + for (uint32_t j = 0; j < GetNRoutes(); j++) { - std::ostringstream dest; - std::ostringstream gw; - std::ostringstream mask; - std::ostringstream flags; - Ipv4RoutingTableEntry route = GetRoute (j); - dest << route.GetDest (); - *os << std::setw (16) << dest.str (); - gw << route.GetGateway (); - *os << std::setw (16) << gw.str (); - mask << route.GetDestNetworkMask (); - *os << std::setw (16) << mask.str (); - flags << "U"; - if (route.IsHost ()) + std::ostringstream dest; + std::ostringstream gw; + std::ostringstream mask; + std::ostringstream flags; + Ipv4RoutingTableEntry route = GetRoute(j); + dest << route.GetDest(); + *os << std::setw(16) << dest.str(); + gw << route.GetGateway(); + *os << std::setw(16) << gw.str(); + mask << route.GetDestNetworkMask(); + *os << std::setw(16) << mask.str(); + flags << "U"; + if (route.IsHost()) { - flags << "H"; + flags << "H"; } - else if (route.IsGateway ()) + else if (route.IsGateway()) { - flags << "G"; + flags << "G"; } - *os << std::setw (6) << flags.str (); - // Metric not implemented - *os << "-" << " "; - // Ref ct not implemented - *os << "-" << " "; - // Use not implemented - *os << "-" << " "; - if (Names::FindName (m_ipv4->GetNetDevice (route.GetInterface ())) != "") + *os << std::setw(6) << flags.str(); + // Metric not implemented + *os << "-" << " "; + // Ref ct not implemented + *os << "-" << " "; + // Use not implemented + *os << "-" << " "; + if (Names::FindName(m_ipv4->GetNetDevice(route.GetInterface())) != "") { - *os << Names::FindName (m_ipv4->GetNetDevice (route.GetInterface ())); + *os << Names::FindName(m_ipv4->GetNetDevice(route.GetInterface())); } - else + else { - *os << route.GetInterface (); + *os << route.GetInterface(); } - *os << std::endl; + *os << std::endl; } } - *os << std::endl; - // Restore the previous ostream state - (*os).copyfmt (oldState); + *os << std::endl; + // Restore the previous ostream state + (*os).copyfmt(oldState); } Ptr -Ipv4GlobalRouting::RouteOutput (Ptr p, const Ipv4Header &header, Ptr oif, Socket::SocketErrno &sockerr) +Ipv4GlobalRouting::RouteOutput(Ptr p, + const Ipv4Header& header, + Ptr oif, + Socket::SocketErrno& sockerr) { - NS_LOG_FUNCTION (this << p << &header << oif << &sockerr); + NS_LOG_FUNCTION(this << p << &header << oif << &sockerr); - uint32_t flowHash = 0; - if (m_flowEcmpRouting) + uint32_t flowHash = 0; + if (m_flowEcmpRouting) { - flowHash = Ipv4QueueDiscItem (p, Address (), header.GetProtocol (), header).Hash (0); + flowHash = Ipv4QueueDiscItem(p, Address(), header.GetProtocol(), header).Hash(0); } -// -// First, see if this is a multicast packet we have a route for. If we -// have a route, then send the packet down each of the specified interfaces. -// - if (header.GetDestination ().IsMulticast ()) + // + // First, see if this is a multicast packet we have a route for. If we + // have a route, then send the packet down each of the specified interfaces. + // + if (header.GetDestination().IsMulticast()) { - NS_LOG_LOGIC ("Multicast destination-- returning false"); - return nullptr; // Let other routing protocols try to handle this + NS_LOG_LOGIC("Multicast destination-- returning false"); + return nullptr; // Let other routing protocols try to handle this } -// -// See if this is a unicast packet we have a route for. -// - NS_LOG_LOGIC ("Unicast destination- looking up"); - Ptr rtentry = LookupGlobal (header.GetDestination (), flowHash, oif); - if (rtentry) + // + // See if this is a unicast packet we have a route for. + // + NS_LOG_LOGIC("Unicast destination- looking up"); + Ptr rtentry = LookupGlobal(header.GetDestination(), flowHash, oif); + if (rtentry) { - sockerr = Socket::ERROR_NOTERROR; + sockerr = Socket::ERROR_NOTERROR; } - else + else { - sockerr = Socket::ERROR_NOROUTETOHOST; + sockerr = Socket::ERROR_NOROUTETOHOST; } - return rtentry; + return rtentry; } bool -Ipv4GlobalRouting::RouteInput (Ptr p, const Ipv4Header &header, Ptr idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, - LocalDeliverCallback lcb, ErrorCallback ecb) +Ipv4GlobalRouting::RouteInput(Ptr p, + const Ipv4Header& header, + Ptr idev, + UnicastForwardCallback ucb, + MulticastForwardCallback mcb, + LocalDeliverCallback lcb, + ErrorCallback ecb) { - NS_LOG_FUNCTION (this << p << header << header.GetSource () << header.GetDestination () << idev << &lcb << &ecb); + NS_LOG_FUNCTION(this << p << header << header.GetSource() << header.GetDestination() << idev + << &lcb << &ecb); - uint32_t flowHash = 0; - if (m_flowEcmpRouting) + uint32_t flowHash = 0; + if (m_flowEcmpRouting) { - flowHash = Ipv4QueueDiscItem (p->Copy (), Address (), header.GetProtocol (), header).Hash (0); + flowHash = Ipv4QueueDiscItem(p->Copy(), Address(), header.GetProtocol(), header).Hash(0); } - // Check if input device supports IP - NS_ASSERT (m_ipv4->GetInterfaceForDevice (idev) >= 0); - uint32_t iif = m_ipv4->GetInterfaceForDevice (idev); + // Check if input device supports IP + NS_ASSERT(m_ipv4->GetInterfaceForDevice(idev) >= 0); + uint32_t iif = m_ipv4->GetInterfaceForDevice(idev); - if (m_ipv4->IsDestinationAddress (header.GetDestination (), iif)) + if (m_ipv4->IsDestinationAddress(header.GetDestination(), iif)) { - if (!lcb.IsNull ()) + if (!lcb.IsNull()) { - NS_LOG_LOGIC ("Local delivery to " << header.GetDestination ()); - lcb (p, header, iif); - return true; + NS_LOG_LOGIC("Local delivery to " << header.GetDestination()); + lcb(p, header, iif); + return true; } - else + else { - // The local delivery callback is null. This may be a multicast - // or broadcast packet, so return false so that another - // multicast routing protocol can handle it. It should be possible - // to extend this to explicitly check whether it is a unicast - // packet, and invoke the error callback if so - return false; + // The local delivery callback is null. This may be a multicast + // or broadcast packet, so return false so that another + // multicast routing protocol can handle it. It should be possible + // to extend this to explicitly check whether it is a unicast + // packet, and invoke the error callback if so + return false; } } - // Check if input device supports IP forwarding - if (m_ipv4->IsForwarding (iif) == false) + // Check if input device supports IP forwarding + if (m_ipv4->IsForwarding(iif) == false) { - NS_LOG_LOGIC ("Forwarding disabled for this interface"); - ecb (p, header, Socket::ERROR_NOROUTETOHOST); - return true; + NS_LOG_LOGIC("Forwarding disabled for this interface"); + ecb(p, header, Socket::ERROR_NOROUTETOHOST); + return true; } - // Next, try to find a route - NS_LOG_LOGIC ("Unicast destination- looking up global route"); - Ptr rtentry = LookupGlobal (header.GetDestination (), flowHash); - if (rtentry) + // Next, try to find a route + NS_LOG_LOGIC("Unicast destination- looking up global route"); + Ptr rtentry = LookupGlobal(header.GetDestination(), flowHash); + if (rtentry) { - NS_LOG_LOGIC ("Found unicast destination- calling unicast callback"); - ucb (rtentry, p, header); - return true; + NS_LOG_LOGIC("Found unicast destination- calling unicast callback"); + ucb(rtentry, p, header); + return true; } - else + else { - NS_LOG_LOGIC ("Did not find unicast destination- returning false"); - return false; // Let other routing protocols try to handle this - // route request. - } -} -void -Ipv4GlobalRouting::NotifyInterfaceUp (uint32_t i) -{ - NS_LOG_FUNCTION (this << i); - if (m_respondToInterfaceEvents && Simulator::Now ().GetSeconds () > 0) // avoid startup events - { - GlobalRouteManager::DeleteGlobalRoutes (); - GlobalRouteManager::BuildGlobalRoutingDatabase (); - GlobalRouteManager::InitializeRoutes (); + NS_LOG_LOGIC("Did not find unicast destination- returning false"); + return false; // Let other routing protocols try to handle this + // route request. } } void -Ipv4GlobalRouting::NotifyInterfaceDown (uint32_t i) +Ipv4GlobalRouting::NotifyInterfaceUp(uint32_t i) { - NS_LOG_FUNCTION (this << i); - if (m_respondToInterfaceEvents && Simulator::Now ().GetSeconds () > 0) // avoid startup events + NS_LOG_FUNCTION(this << i); + if (m_respondToInterfaceEvents && Simulator::Now().GetSeconds() > 0) // avoid startup events { - GlobalRouteManager::DeleteGlobalRoutes (); - GlobalRouteManager::BuildGlobalRoutingDatabase (); - GlobalRouteManager::InitializeRoutes (); + GlobalRouteManager::DeleteGlobalRoutes(); + GlobalRouteManager::BuildGlobalRoutingDatabase(); + GlobalRouteManager::InitializeRoutes(); } } void -Ipv4GlobalRouting::NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address) +Ipv4GlobalRouting::NotifyInterfaceDown(uint32_t i) { - NS_LOG_FUNCTION (this << interface << address); - if (m_respondToInterfaceEvents && Simulator::Now ().GetSeconds () > 0) // avoid startup events + NS_LOG_FUNCTION(this << i); + if (m_respondToInterfaceEvents && Simulator::Now().GetSeconds() > 0) // avoid startup events { - GlobalRouteManager::DeleteGlobalRoutes (); - GlobalRouteManager::BuildGlobalRoutingDatabase (); - GlobalRouteManager::InitializeRoutes (); + GlobalRouteManager::DeleteGlobalRoutes(); + GlobalRouteManager::BuildGlobalRoutingDatabase(); + GlobalRouteManager::InitializeRoutes(); } } void -Ipv4GlobalRouting::NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address) +Ipv4GlobalRouting::NotifyAddAddress(uint32_t interface, Ipv4InterfaceAddress address) { - NS_LOG_FUNCTION (this << interface << address); - if (m_respondToInterfaceEvents && Simulator::Now ().GetSeconds () > 0) // avoid startup events + NS_LOG_FUNCTION(this << interface << address); + if (m_respondToInterfaceEvents && Simulator::Now().GetSeconds() > 0) // avoid startup events { - GlobalRouteManager::DeleteGlobalRoutes (); - GlobalRouteManager::BuildGlobalRoutingDatabase (); - GlobalRouteManager::InitializeRoutes (); + GlobalRouteManager::DeleteGlobalRoutes(); + GlobalRouteManager::BuildGlobalRoutingDatabase(); + GlobalRouteManager::InitializeRoutes(); } } void -Ipv4GlobalRouting::SetIpv4 (Ptr ipv4) +Ipv4GlobalRouting::NotifyRemoveAddress(uint32_t interface, Ipv4InterfaceAddress address) { - NS_LOG_FUNCTION (this << ipv4); - NS_ASSERT (!m_ipv4 && ipv4); - m_ipv4 = ipv4; + NS_LOG_FUNCTION(this << interface << address); + if (m_respondToInterfaceEvents && Simulator::Now().GetSeconds() > 0) // avoid startup events + { + GlobalRouteManager::DeleteGlobalRoutes(); + GlobalRouteManager::BuildGlobalRoutingDatabase(); + GlobalRouteManager::InitializeRoutes(); + } } +void +Ipv4GlobalRouting::SetIpv4(Ptr ipv4) +{ + NS_LOG_FUNCTION(this << ipv4); + NS_ASSERT(!m_ipv4 && ipv4); + m_ipv4 = ipv4; +} } // namespace ns3 diff --git a/src/internet/model/ipv4-global-routing.h b/src/internet/model/ipv4-global-routing.h index 694b7a37f..94d4d0a77 100644 --- a/src/internet/model/ipv4-global-routing.h +++ b/src/internet/model/ipv4-global-routing.h @@ -20,16 +20,18 @@ #ifndef IPV4_GLOBAL_ROUTING_H #define IPV4_GLOBAL_ROUTING_H -#include -#include #include "ns3/ipv4-address.h" #include "ns3/ipv4-header.h" -#include "ns3/ptr.h" -#include "ns3/ipv4.h" #include "ns3/ipv4-routing-protocol.h" +#include "ns3/ipv4.h" +#include "ns3/ptr.h" #include "ns3/random-variable-stream.h" -namespace ns3 { +#include +#include + +namespace ns3 +{ class Packet; class NetDevice; @@ -40,7 +42,6 @@ class Ipv4RoutingTableEntry; class Ipv4MulticastRoutingTableEntry; class Node; - /** * \ingroup ipv4 * @@ -70,212 +71,220 @@ class Node; */ class Ipv4GlobalRouting : public Ipv4RoutingProtocol { -public: - /** - * \brief Get the type ID. - * \return the object TypeId - */ - static TypeId GetTypeId (); - /** - * \brief Construct an empty Ipv4GlobalRouting routing protocol, - * - * The Ipv4GlobalRouting class supports host and network unicast routes. - * This method initializes the lists containing these routes to empty. - * - * \see Ipv4GlobalRouting - */ - Ipv4GlobalRouting (); - ~Ipv4GlobalRouting () override; + public: + /** + * \brief Get the type ID. + * \return the object TypeId + */ + static TypeId GetTypeId(); + /** + * \brief Construct an empty Ipv4GlobalRouting routing protocol, + * + * The Ipv4GlobalRouting class supports host and network unicast routes. + * This method initializes the lists containing these routes to empty. + * + * \see Ipv4GlobalRouting + */ + Ipv4GlobalRouting(); + ~Ipv4GlobalRouting() override; - // These methods inherited from base class - Ptr RouteOutput (Ptr p, const Ipv4Header &header, Ptr oif, Socket::SocketErrno &sockerr) override; + // These methods inherited from base class + Ptr RouteOutput(Ptr p, + const Ipv4Header& header, + Ptr oif, + Socket::SocketErrno& sockerr) override; - bool RouteInput (Ptr p, const Ipv4Header &header, Ptr idev, - UnicastForwardCallback ucb, MulticastForwardCallback mcb, - LocalDeliverCallback lcb, ErrorCallback ecb) override; - void NotifyInterfaceUp (uint32_t interface) override; - void NotifyInterfaceDown (uint32_t interface) override; - void NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address) override; - void NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address) override; - void SetIpv4 (Ptr ipv4) override; - void PrintRoutingTable (Ptr stream, Time::Unit unit = Time::S) const override; + bool RouteInput(Ptr p, + const Ipv4Header& header, + Ptr idev, + UnicastForwardCallback ucb, + MulticastForwardCallback mcb, + LocalDeliverCallback lcb, + ErrorCallback ecb) override; + void NotifyInterfaceUp(uint32_t interface) override; + void NotifyInterfaceDown(uint32_t interface) override; + void NotifyAddAddress(uint32_t interface, Ipv4InterfaceAddress address) override; + void NotifyRemoveAddress(uint32_t interface, Ipv4InterfaceAddress address) override; + void SetIpv4(Ptr ipv4) override; + void PrintRoutingTable(Ptr stream, + Time::Unit unit = Time::S) const override; - /** - * \brief Add a host route to the global routing table. - * - * \param dest The Ipv4Address destination for this route. - * \param nextHop The Ipv4Address of the next hop in the route. - * \param interface The network interface index used to send packets to the - * destination. - * - * \see Ipv4Address - */ - void AddHostRouteTo (Ipv4Address dest, - Ipv4Address nextHop, - uint32_t interface); - /** - * \brief Add a host route to the global routing table. - * - * \param dest The Ipv4Address destination for this route. - * \param interface The network interface index used to send packets to the - * destination. - * - * \see Ipv4Address - */ - void AddHostRouteTo (Ipv4Address dest, - uint32_t interface); + /** + * \brief Add a host route to the global routing table. + * + * \param dest The Ipv4Address destination for this route. + * \param nextHop The Ipv4Address of the next hop in the route. + * \param interface The network interface index used to send packets to the + * destination. + * + * \see Ipv4Address + */ + void AddHostRouteTo(Ipv4Address dest, Ipv4Address nextHop, uint32_t interface); + /** + * \brief Add a host route to the global routing table. + * + * \param dest The Ipv4Address destination for this route. + * \param interface The network interface index used to send packets to the + * destination. + * + * \see Ipv4Address + */ + void AddHostRouteTo(Ipv4Address dest, uint32_t interface); - /** - * \brief Add a network route to the global routing table. - * - * \param network The Ipv4Address network for this route. - * \param networkMask The Ipv4Mask to extract the network. - * \param nextHop The next hop in the route to the destination network. - * \param interface The network interface index used to send packets to the - * destination. - * - * \see Ipv4Address - */ - void AddNetworkRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - Ipv4Address nextHop, - uint32_t interface); + /** + * \brief Add a network route to the global routing table. + * + * \param network The Ipv4Address network for this route. + * \param networkMask The Ipv4Mask to extract the network. + * \param nextHop The next hop in the route to the destination network. + * \param interface The network interface index used to send packets to the + * destination. + * + * \see Ipv4Address + */ + void AddNetworkRouteTo(Ipv4Address network, + Ipv4Mask networkMask, + Ipv4Address nextHop, + uint32_t interface); - /** - * \brief Add a network route to the global routing table. - * - * \param network The Ipv4Address network for this route. - * \param networkMask The Ipv4Mask to extract the network. - * \param interface The network interface index used to send packets to the - * destination. - * - * \see Ipv4Address - */ - void AddNetworkRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - uint32_t interface); + /** + * \brief Add a network route to the global routing table. + * + * \param network The Ipv4Address network for this route. + * \param networkMask The Ipv4Mask to extract the network. + * \param interface The network interface index used to send packets to the + * destination. + * + * \see Ipv4Address + */ + void AddNetworkRouteTo(Ipv4Address network, Ipv4Mask networkMask, uint32_t interface); - /** - * \brief Add an external route to the global routing table. - * - * \param network The Ipv4Address network for this route. - * \param networkMask The Ipv4Mask to extract the network. - * \param nextHop The next hop Ipv4Address - * \param interface The network interface index used to send packets to the - * destination. - */ - void AddASExternalRouteTo (Ipv4Address network, - Ipv4Mask networkMask, - Ipv4Address nextHop, - uint32_t interface); + /** + * \brief Add an external route to the global routing table. + * + * \param network The Ipv4Address network for this route. + * \param networkMask The Ipv4Mask to extract the network. + * \param nextHop The next hop Ipv4Address + * \param interface The network interface index used to send packets to the + * destination. + */ + void AddASExternalRouteTo(Ipv4Address network, + Ipv4Mask networkMask, + Ipv4Address nextHop, + uint32_t interface); - /** - * \brief Get the number of individual unicast routes that have been added - * to the routing table. - * - * \warning The default route counts as one of the routes. - * \returns the number of routes - */ - uint32_t GetNRoutes () const; + /** + * \brief Get the number of individual unicast routes that have been added + * to the routing table. + * + * \warning The default route counts as one of the routes. + * \returns the number of routes + */ + uint32_t GetNRoutes() const; - /** - * \brief Get a route from the global unicast routing table. - * - * Externally, the unicast global routing table appears simply as a table with - * n entries. The one subtlety of note is that if a default route has been set - * it will appear as the zeroth entry in the table. This means that if you - * add only a default route, the table will have one entry that can be accessed - * either by explicitly calling GetDefaultRoute () or by calling GetRoute (0). - * - * Similarly, if the default route has been set, calling RemoveRoute (0) will - * remove the default route. - * - * \param i The index (into the routing table) of the route to retrieve. If - * the default route has been set, it will occupy index zero. - * \return If route is set, a pointer to that Ipv4RoutingTableEntry is returned, otherwise - * a zero pointer is returned. - * - * \see Ipv4RoutingTableEntry - * \see Ipv4GlobalRouting::RemoveRoute - */ - Ipv4RoutingTableEntry *GetRoute (uint32_t i) const; + /** + * \brief Get a route from the global unicast routing table. + * + * Externally, the unicast global routing table appears simply as a table with + * n entries. The one subtlety of note is that if a default route has been set + * it will appear as the zeroth entry in the table. This means that if you + * add only a default route, the table will have one entry that can be accessed + * either by explicitly calling GetDefaultRoute () or by calling GetRoute (0). + * + * Similarly, if the default route has been set, calling RemoveRoute (0) will + * remove the default route. + * + * \param i The index (into the routing table) of the route to retrieve. If + * the default route has been set, it will occupy index zero. + * \return If route is set, a pointer to that Ipv4RoutingTableEntry is returned, otherwise + * a zero pointer is returned. + * + * \see Ipv4RoutingTableEntry + * \see Ipv4GlobalRouting::RemoveRoute + */ + Ipv4RoutingTableEntry* GetRoute(uint32_t i) const; - /** - * \brief Remove a route from the global unicast routing table. - * - * Externally, the unicast global routing table appears simply as a table with - * n entries. The one subtlety of note is that if a default route has been set - * it will appear as the zeroth entry in the table. This means that if the - * default route has been set, calling RemoveRoute (0) will remove the - * default route. - * - * \param i The index (into the routing table) of the route to remove. If - * the default route has been set, it will occupy index zero. - * - * \see Ipv4RoutingTableEntry - * \see Ipv4GlobalRouting::GetRoute - * \see Ipv4GlobalRouting::AddRoute - */ - void RemoveRoute (uint32_t i); + /** + * \brief Remove a route from the global unicast routing table. + * + * Externally, the unicast global routing table appears simply as a table with + * n entries. The one subtlety of note is that if a default route has been set + * it will appear as the zeroth entry in the table. This means that if the + * default route has been set, calling RemoveRoute (0) will remove the + * default route. + * + * \param i The index (into the routing table) of the route to remove. If + * the default route has been set, it will occupy index zero. + * + * \see Ipv4RoutingTableEntry + * \see Ipv4GlobalRouting::GetRoute + * \see Ipv4GlobalRouting::AddRoute + */ + void RemoveRoute(uint32_t i); - /** - * Assign a fixed random variable stream number to the random variables - * used by this model. Return the number of streams (possibly zero) that - * have been assigned. - * - * \param stream first stream index to use - * \return the number of stream indices assigned by this model - */ - int64_t AssignStreams (int64_t stream); + /** + * Assign a fixed random variable stream number to the random variables + * used by this model. Return the number of streams (possibly zero) that + * have been assigned. + * + * \param stream first stream index to use + * \return the number of stream indices assigned by this model + */ + int64_t AssignStreams(int64_t stream); -protected: - void DoDispose () override; + protected: + void DoDispose() override; -private: - /// Set to true if packets are randomly routed among ECMP; set to false for using only one route consistently - bool m_randomEcmpRouting; - /// Set to true if flows are randomly routed among ECMP; set to false for using only one route consistently - bool m_flowEcmpRouting; - /// Set to true if this interface should respond to interface events by globallly recomputing routes - bool m_respondToInterfaceEvents; - /// A uniform random number generator for randomly routing packets among ECMP - Ptr m_rand; + private: + /// Set to true if packets are randomly routed among ECMP; set to false for using only one route + /// consistently + bool m_randomEcmpRouting; + /// Set to true if flows are randomly routed among ECMP; set to false for using only one route + /// consistently + bool m_flowEcmpRouting; + /// Set to true if this interface should respond to interface events by globallly recomputing + /// routes + bool m_respondToInterfaceEvents; + /// A uniform random number generator for randomly routing packets among ECMP + Ptr m_rand; - /// container of Ipv4RoutingTableEntry (routes to hosts) - typedef std::list HostRoutes; - /// const iterator of container of Ipv4RoutingTableEntry (routes to hosts) - typedef std::list::const_iterator HostRoutesCI; - /// iterator of container of Ipv4RoutingTableEntry (routes to hosts) - typedef std::list::iterator HostRoutesI; + /// container of Ipv4RoutingTableEntry (routes to hosts) + typedef std::list HostRoutes; + /// const iterator of container of Ipv4RoutingTableEntry (routes to hosts) + typedef std::list::const_iterator HostRoutesCI; + /// iterator of container of Ipv4RoutingTableEntry (routes to hosts) + typedef std::list::iterator HostRoutesI; - /// container of Ipv4RoutingTableEntry (routes to networks) - typedef std::list NetworkRoutes; - /// const iterator of container of Ipv4RoutingTableEntry (routes to networks) - typedef std::list::const_iterator NetworkRoutesCI; - /// iterator of container of Ipv4RoutingTableEntry (routes to networks) - typedef std::list::iterator NetworkRoutesI; + /// container of Ipv4RoutingTableEntry (routes to networks) + typedef std::list NetworkRoutes; + /// const iterator of container of Ipv4RoutingTableEntry (routes to networks) + typedef std::list::const_iterator NetworkRoutesCI; + /// iterator of container of Ipv4RoutingTableEntry (routes to networks) + typedef std::list::iterator NetworkRoutesI; - /// container of Ipv4RoutingTableEntry (routes to external AS) - typedef std::list ASExternalRoutes; - /// const iterator of container of Ipv4RoutingTableEntry (routes to external AS) - typedef std::list::const_iterator ASExternalRoutesCI; - /// iterator of container of Ipv4RoutingTableEntry (routes to external AS) - typedef std::list::iterator ASExternalRoutesI; + /// container of Ipv4RoutingTableEntry (routes to external AS) + typedef std::list ASExternalRoutes; + /// const iterator of container of Ipv4RoutingTableEntry (routes to external AS) + typedef std::list::const_iterator ASExternalRoutesCI; + /// iterator of container of Ipv4RoutingTableEntry (routes to external AS) + typedef std::list::iterator ASExternalRoutesI; - /** - * \brief Lookup in the forwarding table for destination. - * \param dest destination address - * \param flowHash flow hash for per-flow ECMP routing - * \param oif output interface if any (put 0 otherwise) - * \return Ipv4Route to route the packet to reach dest address - */ - Ptr LookupGlobal (Ipv4Address dest, uint32_t flowHash = 0, Ptr oif = nullptr); + /** + * \brief Lookup in the forwarding table for destination. + * \param dest destination address + * \param flowHash flow hash for per-flow ECMP routing + * \param oif output interface if any (put 0 otherwise) + * \return Ipv4Route to route the packet to reach dest address + */ + Ptr LookupGlobal(Ipv4Address dest, + uint32_t flowHash = 0, + Ptr oif = nullptr); - HostRoutes m_hostRoutes; //!< Routes to hosts - NetworkRoutes m_networkRoutes; //!< Routes to networks - ASExternalRoutes m_ASexternalRoutes; //!< External routes imported + HostRoutes m_hostRoutes; //!< Routes to hosts + NetworkRoutes m_networkRoutes; //!< Routes to networks + ASExternalRoutes m_ASexternalRoutes; //!< External routes imported - Ptr m_ipv4; //!< associated IPv4 instance + Ptr m_ipv4; //!< associated IPv4 instance }; } // Namespace ns3 diff --git a/src/internet/model/ipv4-packet-info-tag.cc b/src/internet/model/ipv4-packet-info-tag.cc index b71a32719..d52c0c4d7 100644 --- a/src/internet/model/ipv4-packet-info-tag.cc +++ b/src/internet/model/ipv4-packet-info-tag.cc @@ -18,121 +18,123 @@ * Authors: Hajime Tazaki */ - -#include -#include "ns3/ipv4-address.h" #include "ipv4-packet-info-tag.h" + +#include "ns3/ipv4-address.h" #include "ns3/log.h" -namespace ns3 { +#include -NS_LOG_COMPONENT_DEFINE ("Ipv4PacketInfoTag"); - -NS_OBJECT_ENSURE_REGISTERED (Ipv4PacketInfoTag); - -Ipv4PacketInfoTag::Ipv4PacketInfoTag () - : m_addr (Ipv4Address ()), - m_ifindex (0), - m_ttl (0) +namespace ns3 { - NS_LOG_FUNCTION (this); + +NS_LOG_COMPONENT_DEFINE("Ipv4PacketInfoTag"); + +NS_OBJECT_ENSURE_REGISTERED(Ipv4PacketInfoTag); + +Ipv4PacketInfoTag::Ipv4PacketInfoTag() + : m_addr(Ipv4Address()), + m_ifindex(0), + m_ttl(0) +{ + NS_LOG_FUNCTION(this); } void -Ipv4PacketInfoTag::SetAddress (Ipv4Address addr) +Ipv4PacketInfoTag::SetAddress(Ipv4Address addr) { - NS_LOG_FUNCTION (this << addr); - m_addr = addr; + NS_LOG_FUNCTION(this << addr); + m_addr = addr; } Ipv4Address -Ipv4PacketInfoTag::GetAddress () const +Ipv4PacketInfoTag::GetAddress() const { - NS_LOG_FUNCTION (this); - return m_addr; + NS_LOG_FUNCTION(this); + return m_addr; } void -Ipv4PacketInfoTag::SetRecvIf (uint32_t ifindex) +Ipv4PacketInfoTag::SetRecvIf(uint32_t ifindex) { - NS_LOG_FUNCTION (this << ifindex); - m_ifindex = ifindex; + NS_LOG_FUNCTION(this << ifindex); + m_ifindex = ifindex; } uint32_t -Ipv4PacketInfoTag::GetRecvIf () const +Ipv4PacketInfoTag::GetRecvIf() const { - NS_LOG_FUNCTION (this); - return m_ifindex; + NS_LOG_FUNCTION(this); + return m_ifindex; } void -Ipv4PacketInfoTag::SetTtl (uint8_t ttl) +Ipv4PacketInfoTag::SetTtl(uint8_t ttl) { - NS_LOG_FUNCTION (this << static_cast (ttl)); - m_ttl = ttl; + NS_LOG_FUNCTION(this << static_cast(ttl)); + m_ttl = ttl; } uint8_t -Ipv4PacketInfoTag::GetTtl () const +Ipv4PacketInfoTag::GetTtl() const { - NS_LOG_FUNCTION (this); - return m_ttl; + NS_LOG_FUNCTION(this); + return m_ttl; } - - TypeId -Ipv4PacketInfoTag::GetTypeId () +Ipv4PacketInfoTag::GetTypeId() { - static TypeId tid = TypeId ("ns3::Ipv4PacketInfoTag") - .SetParent () - .SetGroupName ("Internet") - .AddConstructor () - ; - return tid; + static TypeId tid = TypeId("ns3::Ipv4PacketInfoTag") + .SetParent() + .SetGroupName("Internet") + .AddConstructor(); + return tid; } + TypeId -Ipv4PacketInfoTag::GetInstanceTypeId () const +Ipv4PacketInfoTag::GetInstanceTypeId() const { - NS_LOG_FUNCTION (this); - return GetTypeId (); + NS_LOG_FUNCTION(this); + return GetTypeId(); } uint32_t -Ipv4PacketInfoTag::GetSerializedSize () const +Ipv4PacketInfoTag::GetSerializedSize() const { - NS_LOG_FUNCTION (this); - return 4 + sizeof (uint32_t) + sizeof (uint8_t); + NS_LOG_FUNCTION(this); + return 4 + sizeof(uint32_t) + sizeof(uint8_t); } + void -Ipv4PacketInfoTag::Serialize (TagBuffer i) const +Ipv4PacketInfoTag::Serialize(TagBuffer i) const { - NS_LOG_FUNCTION (this << &i); - uint8_t buf[4]; - m_addr.Serialize (buf); - i.Write (buf, 4); - i.WriteU32 (m_ifindex); - i.WriteU8 (m_ttl); + NS_LOG_FUNCTION(this << &i); + uint8_t buf[4]; + m_addr.Serialize(buf); + i.Write(buf, 4); + i.WriteU32(m_ifindex); + i.WriteU8(m_ttl); } + void -Ipv4PacketInfoTag::Deserialize (TagBuffer i) +Ipv4PacketInfoTag::Deserialize(TagBuffer i) { - NS_LOG_FUNCTION (this<< &i); - uint8_t buf[4]; - i.Read (buf, 4); - m_addr = Ipv4Address::Deserialize (buf); - m_ifindex = i.ReadU32 (); - m_ttl = i.ReadU8 (); + NS_LOG_FUNCTION(this << &i); + uint8_t buf[4]; + i.Read(buf, 4); + m_addr = Ipv4Address::Deserialize(buf); + m_ifindex = i.ReadU32(); + m_ttl = i.ReadU8(); } + void -Ipv4PacketInfoTag::Print (std::ostream &os) const +Ipv4PacketInfoTag::Print(std::ostream& os) const { - NS_LOG_FUNCTION (this << &os); - os << "Ipv4 PKTINFO [DestAddr: " << m_addr; - os << ", RecvIf:" << (uint32_t) m_ifindex; - os << ", TTL:" << (uint32_t) m_ttl; - os << "] "; + NS_LOG_FUNCTION(this << &os); + os << "Ipv4 PKTINFO [DestAddr: " << m_addr; + os << ", RecvIf:" << (uint32_t)m_ifindex; + os << ", TTL:" << (uint32_t)m_ttl; + os << "] "; } } // namespace ns3 - diff --git a/src/internet/model/ipv6-end-point-demux.cc b/src/internet/model/ipv6-end-point-demux.cc index b9c32d072..540593edd 100644 --- a/src/internet/model/ipv6-end-point-demux.cc +++ b/src/internet/model/ipv6-end-point-demux.cc @@ -19,147 +19,157 @@ */ #include "ipv6-end-point-demux.h" + #include "ipv6-end-point.h" + #include "ns3/log.h" -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("Ipv6EndPointDemux"); - -Ipv6EndPointDemux::Ipv6EndPointDemux () - : m_ephemeral (1024), - m_portFirst (1024), - m_portLast (65535) +namespace ns3 { - NS_LOG_FUNCTION (this); + +NS_LOG_COMPONENT_DEFINE("Ipv6EndPointDemux"); + +Ipv6EndPointDemux::Ipv6EndPointDemux() + : m_ephemeral(1024), + m_portFirst(1024), + m_portLast(65535) +{ + NS_LOG_FUNCTION(this); } -Ipv6EndPointDemux::~Ipv6EndPointDemux () +Ipv6EndPointDemux::~Ipv6EndPointDemux() { - NS_LOG_FUNCTION (this); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - Ipv6EndPoint *endPoint = *i; - delete endPoint; + Ipv6EndPoint* endPoint = *i; + delete endPoint; } - m_endPoints.clear (); + m_endPoints.clear(); } -bool Ipv6EndPointDemux::LookupPortLocal (uint16_t port) +bool +Ipv6EndPointDemux::LookupPortLocal(uint16_t port) { - NS_LOG_FUNCTION (this << port); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << port); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == port) + if ((*i)->GetLocalPort() == port) { - return true; + return true; } } - return false; + return false; } -bool Ipv6EndPointDemux::LookupLocal (Ptr boundNetDevice, Ipv6Address addr, uint16_t port) +bool +Ipv6EndPointDemux::LookupLocal(Ptr boundNetDevice, Ipv6Address addr, uint16_t port) { - NS_LOG_FUNCTION (this << addr << port); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << addr << port); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == port && - (*i)->GetLocalAddress () == addr && - (*i)->GetBoundNetDevice () == boundNetDevice) + if ((*i)->GetLocalPort() == port && (*i)->GetLocalAddress() == addr && + (*i)->GetBoundNetDevice() == boundNetDevice) { - return true; + return true; } } - return false; + return false; } -Ipv6EndPoint* Ipv6EndPointDemux::Allocate () +Ipv6EndPoint* +Ipv6EndPointDemux::Allocate() { - NS_LOG_FUNCTION (this); - uint16_t port = AllocateEphemeralPort (); - if (port == 0) + NS_LOG_FUNCTION(this); + uint16_t port = AllocateEphemeralPort(); + if (port == 0) { - NS_LOG_WARN ("Ephemeral port allocation failed."); - return nullptr; + NS_LOG_WARN("Ephemeral port allocation failed."); + return nullptr; } - Ipv6EndPoint *endPoint = new Ipv6EndPoint (Ipv6Address::GetAny (), port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv6EndPoint* endPoint = new Ipv6EndPoint(Ipv6Address::GetAny(), port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ipv6Address address) +Ipv6EndPoint* +Ipv6EndPointDemux::Allocate(Ipv6Address address) { - NS_LOG_FUNCTION (this << address); - uint16_t port = AllocateEphemeralPort (); - if (port == 0) + NS_LOG_FUNCTION(this << address); + uint16_t port = AllocateEphemeralPort(); + if (port == 0) { - NS_LOG_WARN ("Ephemeral port allocation failed."); - return nullptr; + NS_LOG_WARN("Ephemeral port allocation failed."); + return nullptr; } - Ipv6EndPoint *endPoint = new Ipv6EndPoint (address, port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv6EndPoint* endPoint = new Ipv6EndPoint(address, port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ptr boundNetDevice, uint16_t port) +Ipv6EndPoint* +Ipv6EndPointDemux::Allocate(Ptr boundNetDevice, uint16_t port) { - NS_LOG_FUNCTION (this << boundNetDevice << port); + NS_LOG_FUNCTION(this << boundNetDevice << port); - return Allocate (boundNetDevice, Ipv6Address::GetAny (), port); + return Allocate(boundNetDevice, Ipv6Address::GetAny(), port); } -Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ptr boundNetDevice, Ipv6Address address, uint16_t port) +Ipv6EndPoint* +Ipv6EndPointDemux::Allocate(Ptr boundNetDevice, Ipv6Address address, uint16_t port) { - NS_LOG_FUNCTION (this << boundNetDevice << address << port); - if (LookupLocal (boundNetDevice, address, port) || LookupLocal (nullptr, address, port)) + NS_LOG_FUNCTION(this << boundNetDevice << address << port); + if (LookupLocal(boundNetDevice, address, port) || LookupLocal(nullptr, address, port)) { - NS_LOG_WARN ("Duplicated endpoint."); - return nullptr; + NS_LOG_WARN("Duplicated endpoint."); + return nullptr; } - Ipv6EndPoint *endPoint = new Ipv6EndPoint (address, port); - m_endPoints.push_back (endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); - return endPoint; + Ipv6EndPoint* endPoint = new Ipv6EndPoint(address, port); + m_endPoints.push_back(endPoint); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); + return endPoint; } -Ipv6EndPoint* Ipv6EndPointDemux::Allocate (Ptr boundNetDevice, - Ipv6Address localAddress, uint16_t localPort, - Ipv6Address peerAddress, uint16_t peerPort) +Ipv6EndPoint* +Ipv6EndPointDemux::Allocate(Ptr boundNetDevice, + Ipv6Address localAddress, + uint16_t localPort, + Ipv6Address peerAddress, + uint16_t peerPort) { - NS_LOG_FUNCTION (this << boundNetDevice << localAddress << localPort << peerAddress << peerPort); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this << boundNetDevice << localAddress << localPort << peerAddress << peerPort); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if ((*i)->GetLocalPort () == localPort && - (*i)->GetLocalAddress () == localAddress && - (*i)->GetPeerPort () == peerPort && - (*i)->GetPeerAddress () == peerAddress && - ((*i)->GetBoundNetDevice () == boundNetDevice || !(*i)->GetBoundNetDevice ())) + if ((*i)->GetLocalPort() == localPort && (*i)->GetLocalAddress() == localAddress && + (*i)->GetPeerPort() == peerPort && (*i)->GetPeerAddress() == peerAddress && + ((*i)->GetBoundNetDevice() == boundNetDevice || !(*i)->GetBoundNetDevice())) { - NS_LOG_WARN ("Duplicated endpoint."); - return nullptr; + NS_LOG_WARN("Duplicated endpoint."); + return nullptr; } } - Ipv6EndPoint *endPoint = new Ipv6EndPoint (localAddress, localPort); - endPoint->SetPeer (peerAddress, peerPort); - m_endPoints.push_back (endPoint); + Ipv6EndPoint* endPoint = new Ipv6EndPoint(localAddress, localPort); + endPoint->SetPeer(peerAddress, peerPort); + m_endPoints.push_back(endPoint); - NS_LOG_DEBUG ("Now have >>" << m_endPoints.size () << "<< endpoints."); + NS_LOG_DEBUG("Now have >>" << m_endPoints.size() << "<< endpoints."); - return endPoint; + return endPoint; } -void Ipv6EndPointDemux::DeAllocate (Ipv6EndPoint *endPoint) +void +Ipv6EndPointDemux::DeAllocate(Ipv6EndPoint* endPoint) { - NS_LOG_FUNCTION (this); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_FUNCTION(this); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - if (*i == endPoint) + if (*i == endPoint) { - delete endPoint; - m_endPoints.erase (i); - break; + delete endPoint; + m_endPoints.erase(i); + break; } } } @@ -169,203 +179,202 @@ void Ipv6EndPointDemux::DeAllocate (Ipv6EndPoint *endPoint) * Otherwise, if we find a generic match, we return it. * Otherwise, we return 0. */ -Ipv6EndPointDemux::EndPoints Ipv6EndPointDemux::Lookup (Ipv6Address daddr, uint16_t dport, - Ipv6Address saddr, uint16_t sport, - Ptr incomingInterface) +Ipv6EndPointDemux::EndPoints +Ipv6EndPointDemux::Lookup(Ipv6Address daddr, + uint16_t dport, + Ipv6Address saddr, + uint16_t sport, + Ptr incomingInterface) { - NS_LOG_FUNCTION (this << daddr << dport << saddr << sport << incomingInterface); + NS_LOG_FUNCTION(this << daddr << dport << saddr << sport << incomingInterface); - EndPoints retval1; /* Matches exact on local port, wildcards on others */ - EndPoints retval2; /* Matches exact on local port/adder, wildcards on others */ - EndPoints retval3; /* Matches all but local address */ - EndPoints retval4; /* Exact match on all 4 */ + EndPoints retval1; /* Matches exact on local port, wildcards on others */ + EndPoints retval2; /* Matches exact on local port/adder, wildcards on others */ + EndPoints retval3; /* Matches all but local address */ + EndPoints retval4; /* Exact match on all 4 */ - NS_LOG_DEBUG ("Looking up endpoint for destination address " << daddr); - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + NS_LOG_DEBUG("Looking up endpoint for destination address " << daddr); + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - Ipv6EndPoint* endP = *i; + Ipv6EndPoint* endP = *i; - NS_LOG_DEBUG ("Looking at endpoint dport=" << endP->GetLocalPort () - << " daddr=" << endP->GetLocalAddress () - << " sport=" << endP->GetPeerPort () - << " saddr=" << endP->GetPeerAddress ()); + NS_LOG_DEBUG("Looking at endpoint dport=" + << endP->GetLocalPort() << " daddr=" << endP->GetLocalAddress() + << " sport=" << endP->GetPeerPort() << " saddr=" << endP->GetPeerAddress()); - if (!endP->IsRxEnabled ()) + if (!endP->IsRxEnabled()) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint can not receive packets"); - continue; + NS_LOG_LOGIC("Skipping endpoint " << &endP + << " because endpoint can not receive packets"); + continue; } - if (endP->GetLocalPort () != dport) + if (endP->GetLocalPort() != dport) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint dport " - << endP->GetLocalPort () - << " does not match packet dport " << dport); - continue; + NS_LOG_LOGIC("Skipping endpoint " << &endP << " because endpoint dport " + << endP->GetLocalPort() + << " does not match packet dport " << dport); + continue; } - if (endP->GetBoundNetDevice ()) + if (endP->GetBoundNetDevice()) { - if (!incomingInterface) + if (!incomingInterface) { - continue; + continue; } - if (endP->GetBoundNetDevice () != incomingInterface->GetDevice ()) + if (endP->GetBoundNetDevice() != incomingInterface->GetDevice()) { - NS_LOG_LOGIC ("Skipping endpoint " << &endP - << " because endpoint is bound to specific device and" - << endP->GetBoundNetDevice () - << " does not match packet device " << incomingInterface->GetDevice ()); - continue; + NS_LOG_LOGIC("Skipping endpoint " + << &endP << " because endpoint is bound to specific device and" + << endP->GetBoundNetDevice() << " does not match packet device " + << incomingInterface->GetDevice()); + continue; } } - /* Ipv6Address incomingInterfaceAddr = incomingInterface->GetAddress (); */ - NS_LOG_DEBUG ("dest addr " << daddr); + /* Ipv6Address incomingInterfaceAddr = incomingInterface->GetAddress (); */ + NS_LOG_DEBUG("dest addr " << daddr); - bool localAddressMatchesWildCard = endP->GetLocalAddress () == Ipv6Address::GetAny (); - bool localAddressMatchesExact = endP->GetLocalAddress () == daddr; - bool localAddressMatchesAllRouters = endP->GetLocalAddress () == Ipv6Address::GetAllRoutersMulticast (); + bool localAddressMatchesWildCard = endP->GetLocalAddress() == Ipv6Address::GetAny(); + bool localAddressMatchesExact = endP->GetLocalAddress() == daddr; + bool localAddressMatchesAllRouters = + endP->GetLocalAddress() == Ipv6Address::GetAllRoutersMulticast(); - /* if no match here, keep looking */ - if (!(localAddressMatchesExact || localAddressMatchesWildCard)) + /* if no match here, keep looking */ + if (!(localAddressMatchesExact || localAddressMatchesWildCard)) { - continue; + continue; } - bool remotePeerMatchesExact = endP->GetPeerPort () == sport; - bool remotePeerMatchesWildCard = endP->GetPeerPort () == 0; - bool remoteAddressMatchesExact = endP->GetPeerAddress () == saddr; - bool remoteAddressMatchesWildCard = endP->GetPeerAddress () == Ipv6Address::GetAny (); + bool remotePeerMatchesExact = endP->GetPeerPort() == sport; + bool remotePeerMatchesWildCard = endP->GetPeerPort() == 0; + bool remoteAddressMatchesExact = endP->GetPeerAddress() == saddr; + bool remoteAddressMatchesWildCard = endP->GetPeerAddress() == Ipv6Address::GetAny(); - /* If remote does not match either with exact or wildcard,i - skip this one */ - if (!(remotePeerMatchesExact || remotePeerMatchesWildCard)) + /* If remote does not match either with exact or wildcard,i + skip this one */ + if (!(remotePeerMatchesExact || remotePeerMatchesWildCard)) { - continue; + continue; } - if (!(remoteAddressMatchesExact || remoteAddressMatchesWildCard)) + if (!(remoteAddressMatchesExact || remoteAddressMatchesWildCard)) { - continue; + continue; } - /* Now figure out which return list to add this one to */ - if (localAddressMatchesWildCard - && remotePeerMatchesWildCard - && remoteAddressMatchesWildCard) + /* Now figure out which return list to add this one to */ + if (localAddressMatchesWildCard && remotePeerMatchesWildCard && + remoteAddressMatchesWildCard) { /* Only local port matches exactly */ - retval1.push_back (endP); + retval1.push_back(endP); } - if ((localAddressMatchesExact || (localAddressMatchesAllRouters)) - && remotePeerMatchesWildCard - && remoteAddressMatchesWildCard) + if ((localAddressMatchesExact || (localAddressMatchesAllRouters)) && + remotePeerMatchesWildCard && remoteAddressMatchesWildCard) { /* Only local port and local address matches exactly */ - retval2.push_back (endP); + retval2.push_back(endP); } - if (localAddressMatchesWildCard - && remotePeerMatchesExact - && remoteAddressMatchesExact) + if (localAddressMatchesWildCard && remotePeerMatchesExact && remoteAddressMatchesExact) { /* All but local address */ - retval3.push_back (endP); + retval3.push_back(endP); } - if (localAddressMatchesExact - && remotePeerMatchesExact - && remoteAddressMatchesExact) + if (localAddressMatchesExact && remotePeerMatchesExact && remoteAddressMatchesExact) { /* All 4 match */ - retval4.push_back (endP); + retval4.push_back(endP); } } - // Here we find the most exact match - EndPoints retval; - if (!retval4.empty ()) + // Here we find the most exact match + EndPoints retval; + if (!retval4.empty()) { - retval = retval4; + retval = retval4; } - else if (!retval3.empty ()) + else if (!retval3.empty()) { - retval = retval3; + retval = retval3; } - else if (!retval2.empty ()) + else if (!retval2.empty()) { - retval = retval2; + retval = retval2; } - else + else { - retval = retval1; + retval = retval1; } - NS_ABORT_MSG_IF (retval.size () > 1, "Too many endpoints - perhaps you created too many sockets without binding them to different NetDevices."); - return retval; // might be empty if no matches + NS_ABORT_MSG_IF(retval.size() > 1, + "Too many endpoints - perhaps you created too many sockets without binding " + "them to different NetDevices."); + return retval; // might be empty if no matches } -Ipv6EndPoint* Ipv6EndPointDemux::SimpleLookup (Ipv6Address dst, uint16_t dport, Ipv6Address src, uint16_t sport) +Ipv6EndPoint* +Ipv6EndPointDemux::SimpleLookup(Ipv6Address dst, uint16_t dport, Ipv6Address src, uint16_t sport) { - uint32_t genericity = 3; - Ipv6EndPoint *generic = nullptr; + uint32_t genericity = 3; + Ipv6EndPoint* generic = nullptr; - for (EndPointsI i = m_endPoints.begin (); i != m_endPoints.end (); i++) + for (EndPointsI i = m_endPoints.begin(); i != m_endPoints.end(); i++) { - uint32_t tmp = 0; + uint32_t tmp = 0; - if ((*i)->GetLocalPort () != dport) + if ((*i)->GetLocalPort() != dport) { - continue; + continue; } - if ((*i)->GetLocalAddress () == dst && (*i)->GetPeerPort () == sport - && (*i)->GetPeerAddress () == src) + if ((*i)->GetLocalAddress() == dst && (*i)->GetPeerPort() == sport && + (*i)->GetPeerAddress() == src) { - /* this is an exact match. */ - return *i; + /* this is an exact match. */ + return *i; } - if ((*i)->GetLocalAddress () == Ipv6Address::GetAny ()) + if ((*i)->GetLocalAddress() == Ipv6Address::GetAny()) { - tmp++; + tmp++; } - if ((*i)->GetPeerAddress () == Ipv6Address::GetAny ()) + if ((*i)->GetPeerAddress() == Ipv6Address::GetAny()) { - tmp++; + tmp++; } - if (tmp < genericity) + if (tmp < genericity) { - generic = (*i); - genericity = tmp; + generic = (*i); + genericity = tmp; } } - return generic; + return generic; } -uint16_t Ipv6EndPointDemux::AllocateEphemeralPort () +uint16_t +Ipv6EndPointDemux::AllocateEphemeralPort() { - NS_LOG_FUNCTION (this); - uint16_t port = m_ephemeral; - int count = m_portLast - m_portFirst; - do + NS_LOG_FUNCTION(this); + uint16_t port = m_ephemeral; + int count = m_portLast - m_portFirst; + do { - if (count-- < 0) + if (count-- < 0) { - return 0; + return 0; } - ++port; - if (port < m_portFirst || port > m_portLast) + ++port; + if (port < m_portFirst || port > m_portLast) { - port = m_portFirst; + port = m_portFirst; } - } - while (LookupPortLocal (port)); - m_ephemeral = port; - return port; + } while (LookupPortLocal(port)); + m_ephemeral = port; + return port; } -Ipv6EndPointDemux::EndPoints Ipv6EndPointDemux::GetEndPoints () const +Ipv6EndPointDemux::EndPoints +Ipv6EndPointDemux::GetEndPoints() const { - return m_endPoints; + return m_endPoints; } } /* namespace ns3 */ - diff --git a/src/internet/model/ipv6-packet-info-tag.cc b/src/internet/model/ipv6-packet-info-tag.cc index 642fa14f9..1371e4e11 100644 --- a/src/internet/model/ipv6-packet-info-tag.cc +++ b/src/internet/model/ipv6-packet-info-tag.cc @@ -18,124 +18,124 @@ * Authors: Hajime Tazaki */ - -#include -#include "ns3/ipv6-address.h" #include "ipv6-packet-info-tag.h" -namespace ns3 { +#include "ns3/ipv6-address.h" -NS_OBJECT_ENSURE_REGISTERED (Ipv6PacketInfoTag); +#include -Ipv6PacketInfoTag::Ipv6PacketInfoTag () - : m_addr (Ipv6Address ()), - m_ifindex (0), - m_hoplimit (0), - m_tclass (0) +namespace ns3 +{ + +NS_OBJECT_ENSURE_REGISTERED(Ipv6PacketInfoTag); + +Ipv6PacketInfoTag::Ipv6PacketInfoTag() + : m_addr(Ipv6Address()), + m_ifindex(0), + m_hoplimit(0), + m_tclass(0) { } void -Ipv6PacketInfoTag::SetAddress (Ipv6Address addr) +Ipv6PacketInfoTag::SetAddress(Ipv6Address addr) { - m_addr = addr; + m_addr = addr; } Ipv6Address -Ipv6PacketInfoTag::GetAddress () const +Ipv6PacketInfoTag::GetAddress() const { - return m_addr; + return m_addr; } void -Ipv6PacketInfoTag::SetRecvIf (uint32_t ifindex) +Ipv6PacketInfoTag::SetRecvIf(uint32_t ifindex) { - m_ifindex = ifindex; + m_ifindex = ifindex; } uint32_t -Ipv6PacketInfoTag::GetRecvIf () const +Ipv6PacketInfoTag::GetRecvIf() const { - return m_ifindex; + return m_ifindex; } void -Ipv6PacketInfoTag::SetHoplimit (uint8_t ttl) +Ipv6PacketInfoTag::SetHoplimit(uint8_t ttl) { - m_hoplimit = ttl; + m_hoplimit = ttl; } uint8_t -Ipv6PacketInfoTag::GetHoplimit () const +Ipv6PacketInfoTag::GetHoplimit() const { - return m_hoplimit; + return m_hoplimit; } void -Ipv6PacketInfoTag::SetTrafficClass (uint8_t tclass) +Ipv6PacketInfoTag::SetTrafficClass(uint8_t tclass) { - m_tclass = tclass; + m_tclass = tclass; } uint8_t -Ipv6PacketInfoTag::GetTrafficClass () const +Ipv6PacketInfoTag::GetTrafficClass() const { - return m_tclass; + return m_tclass; } +TypeId +Ipv6PacketInfoTag::GetTypeId() +{ + static TypeId tid = TypeId("ns3::Ipv6PacketInfoTag") + .SetParent() + .SetGroupName("Internet") + .AddConstructor(); + return tid; +} TypeId -Ipv6PacketInfoTag::GetTypeId () +Ipv6PacketInfoTag::GetInstanceTypeId() const { - static TypeId tid = TypeId ("ns3::Ipv6PacketInfoTag") - .SetParent () - .SetGroupName ("Internet") - .AddConstructor () - ; - return tid; -} -TypeId -Ipv6PacketInfoTag::GetInstanceTypeId () const -{ - return GetTypeId (); + return GetTypeId(); } uint32_t -Ipv6PacketInfoTag::GetSerializedSize () const +Ipv6PacketInfoTag::GetSerializedSize() const { - return 16 - + sizeof (uint8_t) - + sizeof (uint8_t) - + sizeof (uint8_t); + return 16 + sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t); } + void -Ipv6PacketInfoTag::Serialize (TagBuffer i) const +Ipv6PacketInfoTag::Serialize(TagBuffer i) const { - uint8_t buf[16]; - m_addr.Serialize (buf); - i.Write (buf, 16); - i.WriteU8 (m_ifindex); - i.WriteU8 (m_hoplimit); - i.WriteU8 (m_tclass); + uint8_t buf[16]; + m_addr.Serialize(buf); + i.Write(buf, 16); + i.WriteU8(m_ifindex); + i.WriteU8(m_hoplimit); + i.WriteU8(m_tclass); } + void -Ipv6PacketInfoTag::Deserialize (TagBuffer i) +Ipv6PacketInfoTag::Deserialize(TagBuffer i) { - uint8_t buf[16]; - i.Read (buf, 16); - m_addr = Ipv6Address::Deserialize (buf); - m_ifindex = i.ReadU8 (); - m_hoplimit = i.ReadU8 (); - m_tclass = i.ReadU8 (); + uint8_t buf[16]; + i.Read(buf, 16); + m_addr = Ipv6Address::Deserialize(buf); + m_ifindex = i.ReadU8(); + m_hoplimit = i.ReadU8(); + m_tclass = i.ReadU8(); } + void -Ipv6PacketInfoTag::Print (std::ostream &os) const +Ipv6PacketInfoTag::Print(std::ostream& os) const { - os << "Ipv6 PKTINFO [DestAddr: " << m_addr; - os << ", RecvIf:" << (uint32_t) m_ifindex; - os << ", TTL:" << (uint32_t) m_hoplimit; - os << ", TClass:" << (uint32_t) m_tclass; - os << "] "; + os << "Ipv6 PKTINFO [DestAddr: " << m_addr; + os << ", RecvIf:" << (uint32_t)m_ifindex; + os << ", TTL:" << (uint32_t)m_hoplimit; + os << ", TClass:" << (uint32_t)m_tclass; + os << "] "; } } // namespace ns3 - diff --git a/src/internet/model/tcp-option.cc b/src/internet/model/tcp-option.cc index 8b7b2cf3d..f3d5a95ab 100644 --- a/src/internet/model/tcp-option.cc +++ b/src/internet/model/tcp-option.cc @@ -19,86 +19,81 @@ */ #include "tcp-option.h" + #include "tcp-option-rfc793.h" -#include "tcp-option-winscale.h" -#include "tcp-option-ts.h" #include "tcp-option-sack-permitted.h" #include "tcp-option-sack.h" +#include "tcp-option-ts.h" +#include "tcp-option-winscale.h" -#include "ns3/type-id.h" #include "ns3/log.h" +#include "ns3/type-id.h" #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("TcpOption"); +NS_LOG_COMPONENT_DEFINE("TcpOption"); -NS_OBJECT_ENSURE_REGISTERED (TcpOption); +NS_OBJECT_ENSURE_REGISTERED(TcpOption); - -TcpOption::TcpOption () +TcpOption::TcpOption() { } -TcpOption::~TcpOption () +TcpOption::~TcpOption() { } TypeId -TcpOption::GetTypeId () +TcpOption::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpOption") - .SetParent () - .SetGroupName ("Internet") - ; - return tid; + static TypeId tid = TypeId("ns3::TcpOption").SetParent().SetGroupName("Internet"); + return tid; } TypeId -TcpOption::GetInstanceTypeId () const +TcpOption::GetInstanceTypeId() const { - return GetTypeId (); + return GetTypeId(); } Ptr -TcpOption::CreateOption (uint8_t kind) +TcpOption::CreateOption(uint8_t kind) { - struct kindToTid - { - TcpOption::Kind kind; - TypeId tid; - }; - - static kindToTid toTid[] = - { - { TcpOption::END, TcpOptionEnd::GetTypeId () }, - { TcpOption::MSS, TcpOptionMSS::GetTypeId () }, - { TcpOption::NOP, TcpOptionNOP::GetTypeId () }, - { TcpOption::TS, TcpOptionTS::GetTypeId () }, - { TcpOption::WINSCALE, TcpOptionWinScale::GetTypeId () }, - { TcpOption::SACKPERMITTED, TcpOptionSackPermitted::GetTypeId () }, - { TcpOption::SACK, TcpOptionSack::GetTypeId () }, - { TcpOption::UNKNOWN, TcpOptionUnknown::GetTypeId () } - }; - - for (unsigned int i = 0; i < sizeof (toTid) / sizeof (kindToTid); ++i) + struct kindToTid { - if (toTid[i].kind == kind) + TcpOption::Kind kind; + TypeId tid; + }; + + static kindToTid toTid[] = {{TcpOption::END, TcpOptionEnd::GetTypeId()}, + {TcpOption::MSS, TcpOptionMSS::GetTypeId()}, + {TcpOption::NOP, TcpOptionNOP::GetTypeId()}, + {TcpOption::TS, TcpOptionTS::GetTypeId()}, + {TcpOption::WINSCALE, TcpOptionWinScale::GetTypeId()}, + {TcpOption::SACKPERMITTED, TcpOptionSackPermitted::GetTypeId()}, + {TcpOption::SACK, TcpOptionSack::GetTypeId()}, + {TcpOption::UNKNOWN, TcpOptionUnknown::GetTypeId()}}; + + for (unsigned int i = 0; i < sizeof(toTid) / sizeof(kindToTid); ++i) + { + if (toTid[i].kind == kind) { - ObjectFactory objectFactory; - objectFactory.SetTypeId (toTid[i].tid); - return objectFactory.Create (); + ObjectFactory objectFactory; + objectFactory.SetTypeId(toTid[i].tid); + return objectFactory.Create(); } } - return CreateObject (); + return CreateObject(); } bool -TcpOption::IsKindKnown (uint8_t kind) +TcpOption::IsKindKnown(uint8_t kind) { - switch (kind) + switch (kind) { case END: case NOP: @@ -107,93 +102,93 @@ TcpOption::IsKindKnown (uint8_t kind) case SACKPERMITTED: case SACK: case TS: - // Do not add UNKNOWN here - return true; + // Do not add UNKNOWN here + return true; } - return false; + return false; } -NS_OBJECT_ENSURE_REGISTERED (TcpOptionUnknown); +NS_OBJECT_ENSURE_REGISTERED(TcpOptionUnknown); -TcpOptionUnknown::TcpOptionUnknown () - : TcpOption () +TcpOptionUnknown::TcpOptionUnknown() + : TcpOption() { - m_kind = 0xFF; - m_size = 0; + m_kind = 0xFF; + m_size = 0; } -TcpOptionUnknown::~TcpOptionUnknown () +TcpOptionUnknown::~TcpOptionUnknown() { } TypeId -TcpOptionUnknown::GetTypeId () +TcpOptionUnknown::GetTypeId() { - static TypeId tid = TypeId ("ns3::TcpOptionUnknown") - .SetParent () - .SetGroupName ("Internet") - .AddConstructor () - ; - return tid; + static TypeId tid = TypeId("ns3::TcpOptionUnknown") + .SetParent() + .SetGroupName("Internet") + .AddConstructor(); + return tid; } TypeId -TcpOptionUnknown::GetInstanceTypeId () const +TcpOptionUnknown::GetInstanceTypeId() const { - return GetTypeId (); + return GetTypeId(); } void -TcpOptionUnknown::Print (std::ostream &os) const +TcpOptionUnknown::Print(std::ostream& os) const { - os << "Unknown option"; + os << "Unknown option"; } uint32_t -TcpOptionUnknown::GetSerializedSize () const +TcpOptionUnknown::GetSerializedSize() const { - return m_size; + return m_size; } void -TcpOptionUnknown::Serialize (Buffer::Iterator i) const +TcpOptionUnknown::Serialize(Buffer::Iterator i) const { - if (m_size == 0) + if (m_size == 0) { - NS_LOG_WARN ("Can't Serialize an Unknown Tcp Option"); - return; + NS_LOG_WARN("Can't Serialize an Unknown Tcp Option"); + return; } - i.WriteU8 (GetKind ()); - i.WriteU8 (static_cast (GetSerializedSize ())); - i.Write (m_content, m_size - 2); + i.WriteU8(GetKind()); + i.WriteU8(static_cast(GetSerializedSize())); + i.Write(m_content, m_size - 2); } uint32_t -TcpOptionUnknown::Deserialize (Buffer::Iterator start) +TcpOptionUnknown::Deserialize(Buffer::Iterator start) { - Buffer::Iterator i = start; + Buffer::Iterator i = start; - m_kind = i.ReadU8 (); - NS_LOG_WARN ("Trying to Deserialize an Unknown Option of Kind " << int (m_kind)); + m_kind = i.ReadU8(); + NS_LOG_WARN("Trying to Deserialize an Unknown Option of Kind " << int(m_kind)); - m_size = i.ReadU8 (); - if (m_size < 2 || m_size > 40) + m_size = i.ReadU8(); + if (m_size < 2 || m_size > 40) { - NS_LOG_WARN ("Unable to parse an unknown option of kind " << int (m_kind) << " with apparent size " << int (m_size)); - return 0; + NS_LOG_WARN("Unable to parse an unknown option of kind " + << int(m_kind) << " with apparent size " << int(m_size)); + return 0; } - i.Read (m_content, m_size - 2); + i.Read(m_content, m_size - 2); - return m_size; + return m_size; } uint8_t -TcpOptionUnknown::GetKind () const +TcpOptionUnknown::GetKind() const { - return m_kind; + return m_kind; } } // namespace ns3 diff --git a/src/mpi/examples/simple-hybrid.cc b/src/mpi/examples/simple-hybrid.cc index 812ffac52..653f9161a 100644 --- a/src/mpi/examples/simple-hybrid.cc +++ b/src/mpi/examples/simple-hybrid.cc @@ -48,254 +48,254 @@ #include "mpi-test-fixtures.h" #include "ns3/core-module.h" -#include "ns3/network-module.h" -#include "ns3/mpi-interface.h" -#include "ns3/ipv4-global-routing-helper.h" -#include "ns3/point-to-point-helper.h" #include "ns3/internet-stack-helper.h" -#include "ns3/nix-vector-helper.h" #include "ns3/ipv4-address-helper.h" +#include "ns3/ipv4-global-routing-helper.h" +#include "ns3/mpi-interface.h" +#include "ns3/mtp-interface.h" +#include "ns3/network-module.h" +#include "ns3/nix-vector-helper.h" #include "ns3/on-off-helper.h" #include "ns3/packet-sink-helper.h" -#include "ns3/mtp-interface.h" -#include +#include "ns3/point-to-point-helper.h" #include +#include using namespace ns3; -NS_LOG_COMPONENT_DEFINE ("SimpleDistributed"); +NS_LOG_COMPONENT_DEFINE("SimpleDistributed"); int -main (int argc, char *argv[]) +main(int argc, char* argv[]) { - LogComponentEnable ("LogicalProcess", LOG_LEVEL_INFO); + LogComponentEnable("LogicalProcess", LOG_LEVEL_INFO); - bool nix = true; - bool nullmsg = false; - bool tracing = false; - bool testing = false; - bool verbose = false; + bool nix = true; + bool nullmsg = false; + bool tracing = false; + bool testing = false; + bool verbose = false; - // Parse command line - CommandLine cmd (__FILE__); - cmd.AddValue ("nix", "Enable the use of nix-vector or global routing", nix); - cmd.AddValue ("nullmsg", "Enable the use of null-message synchronization", nullmsg); - cmd.AddValue ("tracing", "Enable pcap tracing", tracing); - cmd.AddValue ("verbose", "verbose output", verbose); - cmd.AddValue ("test", "Enable regression test output", testing); - cmd.Parse (argc, argv); + // Parse command line + CommandLine cmd(__FILE__); + cmd.AddValue("nix", "Enable the use of nix-vector or global routing", nix); + cmd.AddValue("nullmsg", "Enable the use of null-message synchronization", nullmsg); + cmd.AddValue("tracing", "Enable pcap tracing", tracing); + cmd.AddValue("verbose", "verbose output", verbose); + cmd.AddValue("test", "Enable regression test output", testing); + cmd.Parse(argc, argv); - // Distributed simulation setup; by default use granted time window algorithm. - if(nullmsg) + // Distributed simulation setup; by default use granted time window algorithm. + if (nullmsg) { - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::NullMessageSimulatorImpl")); - } - else + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::NullMessageSimulatorImpl")); + } + else { - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::DistributedSimulatorImpl")); + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::DistributedSimulatorImpl")); } - // Enable parallel simulator with the command line arguments - MtpInterface::Enable (); - MpiInterface::Enable (&argc, &argv); + // Enable parallel simulator with the command line arguments + MtpInterface::Enable(); + MpiInterface::Enable(&argc, &argv); - SinkTracer::Init (); + SinkTracer::Init(); - if (verbose) + if (verbose) { - LogComponentEnable ("PacketSink", (LogLevel)(LOG_LEVEL_INFO | LOG_PREFIX_NODE | LOG_PREFIX_TIME)); + LogComponentEnable("PacketSink", + (LogLevel)(LOG_LEVEL_INFO | LOG_PREFIX_NODE | LOG_PREFIX_TIME)); } - uint32_t systemId = MpiInterface::GetSystemId (); - uint32_t systemCount = MpiInterface::GetSize (); + uint32_t systemId = MpiInterface::GetSystemId(); + uint32_t systemCount = MpiInterface::GetSize(); - // Check for valid distributed parameters. - // Must have 2 and only 2 Logical Processors (LPs) - if (systemCount != 2) + // Check for valid distributed parameters. + // Must have 2 and only 2 Logical Processors (LPs) + if (systemCount != 2) { - std::cout << "This simulation requires 2 and only 2 logical processors." << std::endl; - return 1; + std::cout << "This simulation requires 2 and only 2 logical processors." << std::endl; + return 1; } - // Some default values - Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (512)); - Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("1Mbps")); - Config::SetDefault ("ns3::OnOffApplication::MaxBytes", UintegerValue (512)); + // Some default values + Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(512)); + Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("1Mbps")); + Config::SetDefault("ns3::OnOffApplication::MaxBytes", UintegerValue(512)); - // Create leaf nodes on left with system id 0 - NodeContainer leftLeafNodes; - leftLeafNodes.Create (4, 0); + // Create leaf nodes on left with system id 0 + NodeContainer leftLeafNodes; + leftLeafNodes.Create(4, 0); - // Create router nodes. Left router - // with system id 0, right router with - // system id 1 - NodeContainer routerNodes; - Ptr routerNode1 = CreateObject (0); - Ptr routerNode2 = CreateObject (1); - routerNodes.Add (routerNode1); - routerNodes.Add (routerNode2); + // Create router nodes. Left router + // with system id 0, right router with + // system id 1 + NodeContainer routerNodes; + Ptr routerNode1 = CreateObject(0); + Ptr routerNode2 = CreateObject(1); + routerNodes.Add(routerNode1); + routerNodes.Add(routerNode2); - // Create leaf nodes on right with system id 1 - NodeContainer rightLeafNodes; - rightLeafNodes.Create (4, 1); + // Create leaf nodes on right with system id 1 + NodeContainer rightLeafNodes; + rightLeafNodes.Create(4, 1); - PointToPointHelper routerLink; - routerLink.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); - routerLink.SetChannelAttribute ("Delay", StringValue ("5ms")); + PointToPointHelper routerLink; + routerLink.SetDeviceAttribute("DataRate", StringValue("5Mbps")); + routerLink.SetChannelAttribute("Delay", StringValue("5ms")); - PointToPointHelper leafLink; - leafLink.SetDeviceAttribute ("DataRate", StringValue ("1Mbps")); - leafLink.SetChannelAttribute ("Delay", StringValue ("2ms")); + PointToPointHelper leafLink; + leafLink.SetDeviceAttribute("DataRate", StringValue("1Mbps")); + leafLink.SetChannelAttribute("Delay", StringValue("2ms")); - // Add link connecting routers - NetDeviceContainer routerDevices; - routerDevices = routerLink.Install (routerNodes); + // Add link connecting routers + NetDeviceContainer routerDevices; + routerDevices = routerLink.Install(routerNodes); - // Add links for left side leaf nodes to left router - NetDeviceContainer leftRouterDevices; - NetDeviceContainer leftLeafDevices; - for (uint32_t i = 0; i < 4; ++i) + // Add links for left side leaf nodes to left router + NetDeviceContainer leftRouterDevices; + NetDeviceContainer leftLeafDevices; + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer temp = leafLink.Install (leftLeafNodes.Get (i), routerNodes.Get (0)); - leftLeafDevices.Add (temp.Get (0)); - leftRouterDevices.Add (temp.Get (1)); + NetDeviceContainer temp = leafLink.Install(leftLeafNodes.Get(i), routerNodes.Get(0)); + leftLeafDevices.Add(temp.Get(0)); + leftRouterDevices.Add(temp.Get(1)); } - // Add links for right side leaf nodes to right router - NetDeviceContainer rightRouterDevices; - NetDeviceContainer rightLeafDevices; - for (uint32_t i = 0; i < 4; ++i) + // Add links for right side leaf nodes to right router + NetDeviceContainer rightRouterDevices; + NetDeviceContainer rightLeafDevices; + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer temp = leafLink.Install (rightLeafNodes.Get (i), routerNodes.Get (1)); - rightLeafDevices.Add (temp.Get (0)); - rightRouterDevices.Add (temp.Get (1)); + NetDeviceContainer temp = leafLink.Install(rightLeafNodes.Get(i), routerNodes.Get(1)); + rightLeafDevices.Add(temp.Get(0)); + rightRouterDevices.Add(temp.Get(1)); } - InternetStackHelper stack; - if (nix) + InternetStackHelper stack; + if (nix) { - Ipv4NixVectorHelper nixRouting; - stack.SetRoutingHelper (nixRouting); // has effect on the next Install () + Ipv4NixVectorHelper nixRouting; + stack.SetRoutingHelper(nixRouting); // has effect on the next Install () } - stack.InstallAll (); + stack.InstallAll(); - Ipv4InterfaceContainer routerInterfaces; - Ipv4InterfaceContainer leftLeafInterfaces; - Ipv4InterfaceContainer leftRouterInterfaces; - Ipv4InterfaceContainer rightLeafInterfaces; - Ipv4InterfaceContainer rightRouterInterfaces; + Ipv4InterfaceContainer routerInterfaces; + Ipv4InterfaceContainer leftLeafInterfaces; + Ipv4InterfaceContainer leftRouterInterfaces; + Ipv4InterfaceContainer rightLeafInterfaces; + Ipv4InterfaceContainer rightRouterInterfaces; - Ipv4AddressHelper leftAddress; - leftAddress.SetBase ("10.1.1.0", "255.255.255.0"); + Ipv4AddressHelper leftAddress; + leftAddress.SetBase("10.1.1.0", "255.255.255.0"); - Ipv4AddressHelper routerAddress; - routerAddress.SetBase ("10.2.1.0", "255.255.255.0"); + Ipv4AddressHelper routerAddress; + routerAddress.SetBase("10.2.1.0", "255.255.255.0"); - Ipv4AddressHelper rightAddress; - rightAddress.SetBase ("10.3.1.0", "255.255.255.0"); + Ipv4AddressHelper rightAddress; + rightAddress.SetBase("10.3.1.0", "255.255.255.0"); - // Router-to-Router interfaces - routerInterfaces = routerAddress.Assign (routerDevices); + // Router-to-Router interfaces + routerInterfaces = routerAddress.Assign(routerDevices); - // Left interfaces - for (uint32_t i = 0; i < 4; ++i) + // Left interfaces + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer ndc; - ndc.Add (leftLeafDevices.Get (i)); - ndc.Add (leftRouterDevices.Get (i)); - Ipv4InterfaceContainer ifc = leftAddress.Assign (ndc); - leftLeafInterfaces.Add (ifc.Get (0)); - leftRouterInterfaces.Add (ifc.Get (1)); - leftAddress.NewNetwork (); + NetDeviceContainer ndc; + ndc.Add(leftLeafDevices.Get(i)); + ndc.Add(leftRouterDevices.Get(i)); + Ipv4InterfaceContainer ifc = leftAddress.Assign(ndc); + leftLeafInterfaces.Add(ifc.Get(0)); + leftRouterInterfaces.Add(ifc.Get(1)); + leftAddress.NewNetwork(); } - // Right interfaces - for (uint32_t i = 0; i < 4; ++i) + // Right interfaces + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer ndc; - ndc.Add (rightLeafDevices.Get (i)); - ndc.Add (rightRouterDevices.Get (i)); - Ipv4InterfaceContainer ifc = rightAddress.Assign (ndc); - rightLeafInterfaces.Add (ifc.Get (0)); - rightRouterInterfaces.Add (ifc.Get (1)); - rightAddress.NewNetwork (); + NetDeviceContainer ndc; + ndc.Add(rightLeafDevices.Get(i)); + ndc.Add(rightRouterDevices.Get(i)); + Ipv4InterfaceContainer ifc = rightAddress.Assign(ndc); + rightLeafInterfaces.Add(ifc.Get(0)); + rightRouterInterfaces.Add(ifc.Get(1)); + rightAddress.NewNetwork(); } - if (!nix) + if (!nix) { - Ipv4GlobalRoutingHelper::PopulateRoutingTables (); + Ipv4GlobalRoutingHelper::PopulateRoutingTables(); } - if (tracing == true) + if (tracing == true) { - if (systemId == 0) + if (systemId == 0) { - routerLink.EnablePcap("router-left", routerDevices, true); - leafLink.EnablePcap("leaf-left", leftLeafDevices, true); + routerLink.EnablePcap("router-left", routerDevices, true); + leafLink.EnablePcap("leaf-left", leftLeafDevices, true); } - - if (systemId == 1) + + if (systemId == 1) { - routerLink.EnablePcap("router-right", routerDevices, true); - leafLink.EnablePcap("leaf-right", rightLeafDevices, true); + routerLink.EnablePcap("router-right", routerDevices, true); + leafLink.EnablePcap("leaf-right", rightLeafDevices, true); } } - // Create a packet sink on the right leafs to receive packets from left leafs + // Create a packet sink on the right leafs to receive packets from left leafs - uint16_t port = 50000; - if (systemId == 1) + uint16_t port = 50000; + if (systemId == 1) { - Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port)); - PacketSinkHelper sinkHelper ("ns3::UdpSocketFactory", sinkLocalAddress); - ApplicationContainer sinkApp; - for (uint32_t i = 0; i < 4; ++i) + Address sinkLocalAddress(InetSocketAddress(Ipv4Address::GetAny(), port)); + PacketSinkHelper sinkHelper("ns3::UdpSocketFactory", sinkLocalAddress); + ApplicationContainer sinkApp; + for (uint32_t i = 0; i < 4; ++i) { - sinkApp.Add (sinkHelper.Install (rightLeafNodes.Get (i))); - if (testing) + sinkApp.Add(sinkHelper.Install(rightLeafNodes.Get(i))); + if (testing) { - sinkApp.Get (i)->TraceConnectWithoutContext ("RxWithAddresses", MakeCallback (&SinkTracer::SinkTrace)); + sinkApp.Get(i)->TraceConnectWithoutContext("RxWithAddresses", + MakeCallback(&SinkTracer::SinkTrace)); } } - sinkApp.Start (Seconds (1.0)); - sinkApp.Stop (Seconds (5)); + sinkApp.Start(Seconds(1.0)); + sinkApp.Stop(Seconds(5)); } - // Create the OnOff applications to send - if (systemId == 0) + // Create the OnOff applications to send + if (systemId == 0) { - OnOffHelper clientHelper ("ns3::UdpSocketFactory", Address ()); - clientHelper.SetAttribute - ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); - clientHelper.SetAttribute - ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); + OnOffHelper clientHelper("ns3::UdpSocketFactory", Address()); + clientHelper.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]")); + clientHelper.SetAttribute("OffTime", + StringValue("ns3::ConstantRandomVariable[Constant=0]")); - ApplicationContainer clientApps; - for (uint32_t i = 0; i < 4; ++i) + ApplicationContainer clientApps; + for (uint32_t i = 0; i < 4; ++i) { - AddressValue remoteAddress - (InetSocketAddress (rightLeafInterfaces.GetAddress (i), port)); - clientHelper.SetAttribute ("Remote", remoteAddress); - clientApps.Add (clientHelper.Install (leftLeafNodes.Get (i))); + AddressValue remoteAddress(InetSocketAddress(rightLeafInterfaces.GetAddress(i), port)); + clientHelper.SetAttribute("Remote", remoteAddress); + clientApps.Add(clientHelper.Install(leftLeafNodes.Get(i))); } - clientApps.Start (Seconds (1.0)); - clientApps.Stop (Seconds (5)); + clientApps.Start(Seconds(1.0)); + clientApps.Stop(Seconds(5)); } - Simulator::Stop (Seconds (5)); - Simulator::Run (); - Simulator::Destroy (); + Simulator::Stop(Seconds(5)); + Simulator::Run(); + Simulator::Destroy(); - if (testing) + if (testing) { - SinkTracer::Verify (4); + SinkTracer::Verify(4); } - - // Exit the MPI execution environment - MpiInterface::Disable (); - return 0; + + // Exit the MPI execution environment + MpiInterface::Disable(); + return 0; } diff --git a/src/mpi/model/granted-time-window-mpi-interface.cc b/src/mpi/model/granted-time-window-mpi-interface.cc index c1e394494..fdba4444a 100644 --- a/src/mpi/model/granted-time-window-mpi-interface.cc +++ b/src/mpi/model/granted-time-window-mpi-interface.cc @@ -25,351 +25,372 @@ // This object contains static methods that provide an easy interface // to the necessary MPI information. -#include -#include -#include - #include "granted-time-window-mpi-interface.h" -#include "mpi-receiver.h" -#include "mpi-interface.h" -#include "ns3/node.h" -#include "ns3/node-list.h" -#include "ns3/net-device.h" -#include "ns3/simulator.h" -#include "ns3/simulator-impl.h" -#include "ns3/nstime.h" +#include "mpi-interface.h" +#include "mpi-receiver.h" + #include "ns3/log.h" +#include "ns3/net-device.h" +#include "ns3/node-list.h" +#include "ns3/node.h" +#include "ns3/nstime.h" +#include "ns3/simulator-impl.h" +#include "ns3/simulator.h" + +#include +#include +#include #ifdef NS3_MTP #include "ns3/mtp-interface.h" #endif #include -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("GrantedTimeWindowMpiInterface"); - -NS_OBJECT_ENSURE_REGISTERED (GrantedTimeWindowMpiInterface); - -SentBuffer::SentBuffer () +namespace ns3 { - m_buffer = 0; - m_request = 0; + +NS_LOG_COMPONENT_DEFINE("GrantedTimeWindowMpiInterface"); + +NS_OBJECT_ENSURE_REGISTERED(GrantedTimeWindowMpiInterface); + +SentBuffer::SentBuffer() +{ + m_buffer = 0; + m_request = 0; } -SentBuffer::~SentBuffer () +SentBuffer::~SentBuffer() { - delete [] m_buffer; + delete[] m_buffer; } uint8_t* -SentBuffer::GetBuffer () +SentBuffer::GetBuffer() { - return m_buffer; + return m_buffer; } void -SentBuffer::SetBuffer (uint8_t* buffer) +SentBuffer::SetBuffer(uint8_t* buffer) { - m_buffer = buffer; + m_buffer = buffer; } MPI_Request* -SentBuffer::GetRequest () +SentBuffer::GetRequest() { - return &m_request; + return &m_request; } -uint32_t GrantedTimeWindowMpiInterface::g_sid = 0; -uint32_t GrantedTimeWindowMpiInterface::g_size = 1; -bool GrantedTimeWindowMpiInterface::g_enabled = false; -bool GrantedTimeWindowMpiInterface::g_mpiInitCalled = false; -uint32_t GrantedTimeWindowMpiInterface::g_rxCount = 0; -uint32_t GrantedTimeWindowMpiInterface::g_txCount = 0; +uint32_t GrantedTimeWindowMpiInterface::g_sid = 0; +uint32_t GrantedTimeWindowMpiInterface::g_size = 1; +bool GrantedTimeWindowMpiInterface::g_enabled = false; +bool GrantedTimeWindowMpiInterface::g_mpiInitCalled = false; +uint32_t GrantedTimeWindowMpiInterface::g_rxCount = 0; +uint32_t GrantedTimeWindowMpiInterface::g_txCount = 0; std::list GrantedTimeWindowMpiInterface::g_pendingTx; MPI_Request* GrantedTimeWindowMpiInterface::g_requests; -char** GrantedTimeWindowMpiInterface::g_pRxBuffers; -MPI_Comm GrantedTimeWindowMpiInterface::g_communicator = MPI_COMM_WORLD; -bool GrantedTimeWindowMpiInterface::g_freeCommunicator = false;; +char** GrantedTimeWindowMpiInterface::g_pRxBuffers; +MPI_Comm GrantedTimeWindowMpiInterface::g_communicator = MPI_COMM_WORLD; +bool GrantedTimeWindowMpiInterface::g_freeCommunicator = false; +; #ifdef NS3_MTP -std::atomic GrantedTimeWindowMpiInterface::g_sending (false); +std::atomic GrantedTimeWindowMpiInterface::g_sending(false); #endif -TypeId -GrantedTimeWindowMpiInterface::GetTypeId (void) +TypeId +GrantedTimeWindowMpiInterface::GetTypeId(void) { - static TypeId tid = TypeId ("ns3::GrantedTimeWindowMpiInterface") - .SetParent () - .SetGroupName ("Mpi") - ; - return tid; + static TypeId tid = + TypeId("ns3::GrantedTimeWindowMpiInterface").SetParent().SetGroupName("Mpi"); + return tid; } void -GrantedTimeWindowMpiInterface::Destroy () +GrantedTimeWindowMpiInterface::Destroy() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - for (uint32_t i = 0; i < GetSize (); ++i) + for (uint32_t i = 0; i < GetSize(); ++i) { - delete [] g_pRxBuffers[i]; + delete[] g_pRxBuffers[i]; } - delete [] g_pRxBuffers; - delete [] g_requests; + delete[] g_pRxBuffers; + delete[] g_requests; - g_pendingTx.clear (); + g_pendingTx.clear(); } uint32_t -GrantedTimeWindowMpiInterface::GetRxCount () +GrantedTimeWindowMpiInterface::GetRxCount() { - NS_ASSERT (g_enabled); - return g_rxCount; + NS_ASSERT(g_enabled); + return g_rxCount; } uint32_t -GrantedTimeWindowMpiInterface::GetTxCount () +GrantedTimeWindowMpiInterface::GetTxCount() { - NS_ASSERT (g_enabled); - return g_txCount; + NS_ASSERT(g_enabled); + return g_txCount; } uint32_t -GrantedTimeWindowMpiInterface::GetSystemId () +GrantedTimeWindowMpiInterface::GetSystemId() { - NS_ASSERT (g_enabled); - return g_sid; + NS_ASSERT(g_enabled); + return g_sid; } uint32_t -GrantedTimeWindowMpiInterface::GetSize () +GrantedTimeWindowMpiInterface::GetSize() { - NS_ASSERT (g_enabled); - return g_size; + NS_ASSERT(g_enabled); + return g_size; } bool -GrantedTimeWindowMpiInterface::IsEnabled () +GrantedTimeWindowMpiInterface::IsEnabled() { - return g_enabled; + return g_enabled; } MPI_Comm GrantedTimeWindowMpiInterface::GetCommunicator() { - NS_ASSERT (g_enabled); - return g_communicator; + NS_ASSERT(g_enabled); + return g_communicator; } void -GrantedTimeWindowMpiInterface::Enable (int* pargc, char*** pargv) +GrantedTimeWindowMpiInterface::Enable(int* pargc, char*** pargv) { - NS_LOG_FUNCTION (this << pargc << pargv); + NS_LOG_FUNCTION(this << pargc << pargv); - NS_ASSERT (g_enabled == false); + NS_ASSERT(g_enabled == false); - // Initialize the MPI interface - MPI_Init (pargc, pargv); - Enable (MPI_COMM_WORLD); - g_mpiInitCalled = true; - g_enabled = true; + // Initialize the MPI interface + MPI_Init(pargc, pargv); + Enable(MPI_COMM_WORLD); + g_mpiInitCalled = true; + g_enabled = true; } void -GrantedTimeWindowMpiInterface::Enable (MPI_Comm communicator) +GrantedTimeWindowMpiInterface::Enable(MPI_Comm communicator) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - NS_ASSERT (g_enabled == false); + NS_ASSERT(g_enabled == false); - // Standard MPI practice is to duplicate the communicator for - // library to use. Library communicates in isolated communication - // context. - MPI_Comm_dup (communicator, &g_communicator); - g_freeCommunicator = true; + // Standard MPI practice is to duplicate the communicator for + // library to use. Library communicates in isolated communication + // context. + MPI_Comm_dup(communicator, &g_communicator); + g_freeCommunicator = true; - MPI_Barrier (g_communicator); + MPI_Barrier(g_communicator); - int mpiSystemId; - int mpiSize; - MPI_Comm_rank (g_communicator, &mpiSystemId); - MPI_Comm_size (g_communicator, &mpiSize); - g_sid = mpiSystemId; - g_size = mpiSize; + int mpiSystemId; + int mpiSize; + MPI_Comm_rank(g_communicator, &mpiSystemId); + MPI_Comm_size(g_communicator, &mpiSize); + g_sid = mpiSystemId; + g_size = mpiSize; - g_enabled = true; - // Post a non-blocking receive for all peers - g_pRxBuffers = new char*[g_size]; - g_requests = new MPI_Request[g_size]; - for (uint32_t i = 0; i < GetSize (); ++i) + g_enabled = true; + // Post a non-blocking receive for all peers + g_pRxBuffers = new char*[g_size]; + g_requests = new MPI_Request[g_size]; + for (uint32_t i = 0; i < GetSize(); ++i) { - g_pRxBuffers[i] = new char[MAX_MPI_MSG_SIZE]; - MPI_Irecv (g_pRxBuffers[i], MAX_MPI_MSG_SIZE, MPI_CHAR, MPI_ANY_SOURCE, 0, - g_communicator, &g_requests[i]); + g_pRxBuffers[i] = new char[MAX_MPI_MSG_SIZE]; + MPI_Irecv(g_pRxBuffers[i], + MAX_MPI_MSG_SIZE, + MPI_CHAR, + MPI_ANY_SOURCE, + 0, + g_communicator, + &g_requests[i]); } } void -GrantedTimeWindowMpiInterface::SendPacket (Ptr p, const Time& rxTime, uint32_t node, uint32_t dev) +GrantedTimeWindowMpiInterface::SendPacket(Ptr p, + const Time& rxTime, + uint32_t node, + uint32_t dev) { - NS_LOG_FUNCTION (this << p << rxTime.GetTimeStep () << node << dev); + NS_LOG_FUNCTION(this << p << rxTime.GetTimeStep() << node << dev); #ifdef NS3_MTP - while (g_sending.exchange (true, std::memory_order_acquire)) - ; + while (g_sending.exchange(true, std::memory_order_acquire)) + ; #endif - SentBuffer sendBuf; - g_pendingTx.push_back (sendBuf); - std::list::reverse_iterator i = g_pendingTx.rbegin (); // Points to the last element + SentBuffer sendBuf; + g_pendingTx.push_back(sendBuf); + std::list::reverse_iterator i = g_pendingTx.rbegin(); // Points to the last element - uint32_t serializedSize = p->GetSerializedSize (); - uint8_t* buffer = new uint8_t[serializedSize + 16]; - i->SetBuffer (buffer); - // Add the time, dest node and dest device - uint64_t t = rxTime.GetInteger (); - uint64_t* pTime = reinterpret_cast (buffer); - *pTime++ = t; - uint32_t* pData = reinterpret_cast (pTime); - *pData++ = node; - *pData++ = dev; - // Serialize the packet - p->Serialize (reinterpret_cast (pData), serializedSize); + uint32_t serializedSize = p->GetSerializedSize(); + uint8_t* buffer = new uint8_t[serializedSize + 16]; + i->SetBuffer(buffer); + // Add the time, dest node and dest device + uint64_t t = rxTime.GetInteger(); + uint64_t* pTime = reinterpret_cast(buffer); + *pTime++ = t; + uint32_t* pData = reinterpret_cast(pTime); + *pData++ = node; + *pData++ = dev; + // Serialize the packet + p->Serialize(reinterpret_cast(pData), serializedSize); - // Find the system id for the destination node - Ptr destNode = NodeList::GetNode (node); + // Find the system id for the destination node + Ptr destNode = NodeList::GetNode(node); #ifdef NS3_MTP - uint32_t nodeSysId = destNode->GetSystemId () & 0xFFFF; + uint32_t nodeSysId = destNode->GetSystemId() & 0xFFFF; #else - uint32_t nodeSysId = destNode->GetSystemId (); + uint32_t nodeSysId = destNode->GetSystemId(); #endif - MPI_Isend (reinterpret_cast (i->GetBuffer ()), serializedSize + 16, MPI_CHAR, nodeSysId, - 0, g_communicator, (i->GetRequest ())); - g_txCount++; + MPI_Isend(reinterpret_cast(i->GetBuffer()), + serializedSize + 16, + MPI_CHAR, + nodeSysId, + 0, + g_communicator, + (i->GetRequest())); + g_txCount++; #ifdef NS3_MTP - g_sending.store(false, std::memory_order_release); + g_sending.store(false, std::memory_order_release); #endif } void -GrantedTimeWindowMpiInterface::ReceiveMessages () +GrantedTimeWindowMpiInterface::ReceiveMessages() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - // Poll the non-block reads to see if data arrived - while (true) + // Poll the non-block reads to see if data arrived + while (true) { - int flag = 0; - int index = 0; - MPI_Status status; + int flag = 0; + int index = 0; + MPI_Status status; - MPI_Testany (MpiInterface::GetSize (), g_requests, &index, &flag, &status); - if (!flag) + MPI_Testany(MpiInterface::GetSize(), g_requests, &index, &flag, &status); + if (!flag) { - break; // No more messages + break; // No more messages } - int count; - MPI_Get_count (&status, MPI_CHAR, &count); - g_rxCount++; // Count this receive + int count; + MPI_Get_count(&status, MPI_CHAR, &count); + g_rxCount++; // Count this receive - // Get the meta data first - uint64_t* pTime = reinterpret_cast (g_pRxBuffers[index]); - uint64_t time = *pTime++; - uint32_t* pData = reinterpret_cast (pTime); - uint32_t node = *pData++; - uint32_t dev = *pData++; + // Get the meta data first + uint64_t* pTime = reinterpret_cast(g_pRxBuffers[index]); + uint64_t time = *pTime++; + uint32_t* pData = reinterpret_cast(pTime); + uint32_t node = *pData++; + uint32_t dev = *pData++; - Time rxTime (time); + Time rxTime(time); - count -= sizeof (time) + sizeof (node) + sizeof (dev); + count -= sizeof(time) + sizeof(node) + sizeof(dev); - Ptr p = Create (reinterpret_cast (pData), count, true); + Ptr p = Create(reinterpret_cast(pData), count, true); - // Find the correct node/device to schedule receive event - Ptr pNode = NodeList::GetNode (node); - Ptr pMpiRec = 0; - uint32_t nDevices = pNode->GetNDevices (); - for (uint32_t i = 0; i < nDevices; ++i) + // Find the correct node/device to schedule receive event + Ptr pNode = NodeList::GetNode(node); + Ptr pMpiRec = 0; + uint32_t nDevices = pNode->GetNDevices(); + for (uint32_t i = 0; i < nDevices; ++i) { - Ptr pThisDev = pNode->GetDevice (i); - if (pThisDev->GetIfIndex () == dev) + Ptr pThisDev = pNode->GetDevice(i); + if (pThisDev->GetIfIndex() == dev) { - pMpiRec = pThisDev->GetObject (); - break; + pMpiRec = pThisDev->GetObject(); + break; } } - NS_ASSERT (pNode && pMpiRec); + NS_ASSERT(pNode && pMpiRec); - // Schedule the rx event + // Schedule the rx event #ifdef NS3_MTP - MtpInterface::GetSystem (pNode->GetSystemId () >> 16) - ->ScheduleAt (pNode->GetId (), rxTime, MakeEvent (&MpiReceiver::Receive, pMpiRec, p)); + MtpInterface::GetSystem(pNode->GetSystemId() >> 16) + ->ScheduleAt(pNode->GetId(), rxTime, MakeEvent(&MpiReceiver::Receive, pMpiRec, p)); #else - Simulator::ScheduleWithContext (pNode->GetId (), rxTime - Simulator::Now (), - &MpiReceiver::Receive, pMpiRec, p); + Simulator::ScheduleWithContext(pNode->GetId(), + rxTime - Simulator::Now(), + &MpiReceiver::Receive, + pMpiRec, + p); #endif - // Re-queue the next read - MPI_Irecv (g_pRxBuffers[index], MAX_MPI_MSG_SIZE, MPI_CHAR, MPI_ANY_SOURCE, 0, - g_communicator, &g_requests[index]); + // Re-queue the next read + MPI_Irecv(g_pRxBuffers[index], + MAX_MPI_MSG_SIZE, + MPI_CHAR, + MPI_ANY_SOURCE, + 0, + g_communicator, + &g_requests[index]); } } void -GrantedTimeWindowMpiInterface::TestSendComplete () +GrantedTimeWindowMpiInterface::TestSendComplete() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - std::list::iterator i = g_pendingTx.begin (); - while (i != g_pendingTx.end ()) + std::list::iterator i = g_pendingTx.begin(); + while (i != g_pendingTx.end()) { - MPI_Status status; - int flag = 0; - MPI_Test (i->GetRequest (), &flag, &status); - std::list::iterator current = i; // Save current for erasing - i++; // Advance to next - if (flag) + MPI_Status status; + int flag = 0; + MPI_Test(i->GetRequest(), &flag, &status); + std::list::iterator current = i; // Save current for erasing + i++; // Advance to next + if (flag) { // This message is complete - g_pendingTx.erase (current); + g_pendingTx.erase(current); } } } void -GrantedTimeWindowMpiInterface::Disable () +GrantedTimeWindowMpiInterface::Disable() { - NS_LOG_FUNCTION_NOARGS (); + NS_LOG_FUNCTION_NOARGS(); - if (g_freeCommunicator) + if (g_freeCommunicator) { - MPI_Comm_free (&g_communicator); - g_freeCommunicator = false; + MPI_Comm_free(&g_communicator); + g_freeCommunicator = false; } - // ns-3 should MPI finalize only if ns-3 was used to initialize - if (g_mpiInitCalled) + // ns-3 should MPI finalize only if ns-3 was used to initialize + if (g_mpiInitCalled) { - int flag = 0; - MPI_Initialized (&flag); - if (flag) + int flag = 0; + MPI_Initialized(&flag); + if (flag) { - MPI_Finalize (); + MPI_Finalize(); } - else + else { - NS_FATAL_ERROR ("Cannot disable MPI environment without Initializing it first"); + NS_FATAL_ERROR("Cannot disable MPI environment without Initializing it first"); } - g_mpiInitCalled = false; + g_mpiInitCalled = false; } - g_enabled = false; + g_enabled = false; } - } // namespace ns3 diff --git a/src/mpi/model/granted-time-window-mpi-interface.h b/src/mpi/model/granted-time-window-mpi-interface.h index 10c9938c9..8b34fb32d 100644 --- a/src/mpi/model/granted-time-window-mpi-interface.h +++ b/src/mpi/model/granted-time-window-mpi-interface.h @@ -28,18 +28,18 @@ #ifndef NS3_GRANTED_TIME_WINDOW_MPI_INTERFACE_H #define NS3_GRANTED_TIME_WINDOW_MPI_INTERFACE_H -#include -#include -#include - -#include "ns3/nstime.h" -#include "ns3/buffer.h" - +#include "mpi.h" #include "parallel-communication-interface.h" -#include "mpi.h" +#include "ns3/buffer.h" +#include "ns3/nstime.h" -namespace ns3 { +#include +#include +#include + +namespace ns3 +{ /** * maximum MPI message size for easy @@ -57,26 +57,26 @@ const uint32_t MAX_MPI_MSG_SIZE = 2000; */ class SentBuffer { -public: - SentBuffer (); - ~SentBuffer (); + public: + SentBuffer(); + ~SentBuffer(); - /** - * \return pointer to sent buffer - */ - uint8_t* GetBuffer (); - /** - * \param buffer pointer to sent buffer - */ - void SetBuffer (uint8_t* buffer); - /** - * \return MPI request - */ - MPI_Request* GetRequest (); + /** + * \return pointer to sent buffer + */ + uint8_t* GetBuffer(); + /** + * \param buffer pointer to sent buffer + */ + void SetBuffer(uint8_t* buffer); + /** + * \return MPI request + */ + MPI_Request* GetRequest(); -private: - uint8_t* m_buffer; /**< The buffer. */ - MPI_Request m_request; /**< The MPI request handle. */ + private: + uint8_t* m_buffer; /**< The buffer. */ + MPI_Request m_request; /**< The MPI request handle. */ }; class Packet; @@ -94,87 +94,87 @@ class HybridSimulatorImpl; */ class GrantedTimeWindowMpiInterface : public ParallelCommunicationInterface, Object { -public: - /** - * Register this type. - * \return The object TypeId. - */ - static TypeId GetTypeId (void); + public: + /** + * Register this type. + * \return The object TypeId. + */ + static TypeId GetTypeId(void); - // Inherited - virtual void Destroy (); - virtual uint32_t GetSystemId (); - virtual uint32_t GetSize (); - virtual bool IsEnabled (); - virtual void Enable (int* pargc, char*** pargv); - virtual void Enable (MPI_Comm communicator); - virtual void Disable(); - virtual void SendPacket (Ptr p, const Time &rxTime, uint32_t node, uint32_t dev); - virtual MPI_Comm GetCommunicator(); + // Inherited + virtual void Destroy(); + virtual uint32_t GetSystemId(); + virtual uint32_t GetSize(); + virtual bool IsEnabled(); + virtual void Enable(int* pargc, char*** pargv); + virtual void Enable(MPI_Comm communicator); + virtual void Disable(); + virtual void SendPacket(Ptr p, const Time& rxTime, uint32_t node, uint32_t dev); + virtual MPI_Comm GetCommunicator(); - /* - * The granted time window implementation is a collaboration of several - * classes. Methods that should be invoked only by the - * collaborators are private to restrict use. - * It is not intended for state to be shared. - */ - friend ns3::DistributedSimulatorImpl; - friend ns3::HybridSimulatorImpl; + /* + * The granted time window implementation is a collaboration of several + * classes. Methods that should be invoked only by the + * collaborators are private to restrict use. + * It is not intended for state to be shared. + */ + friend ns3::DistributedSimulatorImpl; + friend ns3::HybridSimulatorImpl; - /** - * Check for received messages complete - */ - static void ReceiveMessages (); - /** - * Check for completed sends - */ - static void TestSendComplete (); - /** - * \return received count in packets - */ - static uint32_t GetRxCount (); - /** - * \return transmitted count in packets - */ - static uint32_t GetTxCount (); + /** + * Check for received messages complete + */ + static void ReceiveMessages(); + /** + * Check for completed sends + */ + static void TestSendComplete(); + /** + * \return received count in packets + */ + static uint32_t GetRxCount(); + /** + * \return transmitted count in packets + */ + static uint32_t GetTxCount(); - /** System ID (rank) for this task. */ - static uint32_t g_sid; - /** Size of the MPI COM_WORLD group. */ - static uint32_t g_size; + /** System ID (rank) for this task. */ + static uint32_t g_sid; + /** Size of the MPI COM_WORLD group. */ + static uint32_t g_size; - /** Total packets received. */ - static uint32_t g_rxCount; + /** Total packets received. */ + static uint32_t g_rxCount; - /** Total packets sent. */ - static uint32_t g_txCount; + /** Total packets sent. */ + static uint32_t g_txCount; - /** Has this interface been enabled. */ - static bool g_enabled; + /** Has this interface been enabled. */ + static bool g_enabled; - /** - * Has MPI Init been called by this interface. - * Alternatively user supplies a communicator. - */ - static bool g_mpiInitCalled; + /** + * Has MPI Init been called by this interface. + * Alternatively user supplies a communicator. + */ + static bool g_mpiInitCalled; - /** Pending non-blocking receives. */ - static MPI_Request* g_requests; + /** Pending non-blocking receives. */ + static MPI_Request* g_requests; - /** Data buffers for non-blocking reads. */ - static char** g_pRxBuffers; + /** Data buffers for non-blocking reads. */ + static char** g_pRxBuffers; - /** List of pending non-blocking sends. */ - static std::list g_pendingTx; + /** List of pending non-blocking sends. */ + static std::list g_pendingTx; - /** MPI communicator being used for ns-3 tasks. */ - static MPI_Comm g_communicator; + /** MPI communicator being used for ns-3 tasks. */ + static MPI_Comm g_communicator; - /** Did ns-3 create the communicator? Have to free it. */ - static bool g_freeCommunicator; + /** Did ns-3 create the communicator? Have to free it. */ + static bool g_freeCommunicator; #ifdef NS3_MTP - static std::atomic g_sending; + static std::atomic g_sending; #endif }; diff --git a/src/mpi/model/hybrid-simulator-impl.cc b/src/mpi/model/hybrid-simulator-impl.cc index 2488d2ffb..96a7fa1c5 100644 --- a/src/mpi/model/hybrid-simulator-impl.cc +++ b/src/mpi/model/hybrid-simulator-impl.cc @@ -1,437 +1,451 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "hybrid-simulator-impl.h" + #include "granted-time-window-mpi-interface.h" #include "mpi-interface.h" #include "ns3/channel.h" -#include "ns3/simulator.h" -#include "ns3/node.h" +#include "ns3/mtp-interface.h" #include "ns3/node-container.h" #include "ns3/node-list.h" +#include "ns3/node.h" +#include "ns3/simulator.h" #include "ns3/uinteger.h" -#include "ns3/mtp-interface.h" -#include #include +#include #include #include -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("HybridSimulatorImpl"); - -NS_OBJECT_ENSURE_REGISTERED (HybridSimulatorImpl); - -HybridSimulatorImpl::HybridSimulatorImpl () +namespace ns3 { - NS_LOG_FUNCTION (this); - MtpInterface::Enable (1, 0); - m_myId = MpiInterface::GetSystemId (); - m_systemCount = MpiInterface::GetSize (); +NS_LOG_COMPONENT_DEFINE("HybridSimulatorImpl"); - // Allocate the LBTS message buffer - m_pLBTS = new LbtsMessage[m_systemCount]; - m_smallestTime = Seconds (0); - m_globalFinished = false; +NS_OBJECT_ENSURE_REGISTERED(HybridSimulatorImpl); + +HybridSimulatorImpl::HybridSimulatorImpl() +{ + NS_LOG_FUNCTION(this); + + MtpInterface::Enable(1, 0); + m_myId = MpiInterface::GetSystemId(); + m_systemCount = MpiInterface::GetSize(); + + // Allocate the LBTS message buffer + m_pLBTS = new LbtsMessage[m_systemCount]; + m_smallestTime = Seconds(0); + m_globalFinished = false; } -HybridSimulatorImpl::~HybridSimulatorImpl () +HybridSimulatorImpl::~HybridSimulatorImpl() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } TypeId -HybridSimulatorImpl::GetTypeId (void) +HybridSimulatorImpl::GetTypeId(void) { - static TypeId tid = - TypeId ("ns3::HybridSimulatorImpl") - .SetParent () - .SetGroupName ("Mtp") - .AddConstructor () - .AddAttribute ("MaxThreads", "The maximum threads used in simulation", - UintegerValue (std::thread::hardware_concurrency ()), - MakeUintegerAccessor (&HybridSimulatorImpl::m_maxThreads), - MakeUintegerChecker (1)) - .AddAttribute ("MinLookahead", "The minimum lookahead in a partition", - TimeValue (TimeStep (1)), - MakeTimeAccessor (&HybridSimulatorImpl::m_minLookahead), - MakeTimeChecker (TimeStep (0))); - return tid; + static TypeId tid = TypeId("ns3::HybridSimulatorImpl") + .SetParent() + .SetGroupName("Mtp") + .AddConstructor() + .AddAttribute("MaxThreads", + "The maximum threads used in simulation", + UintegerValue(std::thread::hardware_concurrency()), + MakeUintegerAccessor(&HybridSimulatorImpl::m_maxThreads), + MakeUintegerChecker(1)) + .AddAttribute("MinLookahead", + "The minimum lookahead in a partition", + TimeValue(TimeStep(1)), + MakeTimeAccessor(&HybridSimulatorImpl::m_minLookahead), + MakeTimeChecker(TimeStep(0))); + return tid; } void -HybridSimulatorImpl::Destroy () +HybridSimulatorImpl::Destroy() { - while (!m_destroyEvents.empty ()) + while (!m_destroyEvents.empty()) { - Ptr ev = m_destroyEvents.front ().PeekEventImpl (); - m_destroyEvents.pop_front (); - NS_LOG_LOGIC ("handle destroy " << ev); - if (!ev->IsCancelled ()) + Ptr ev = m_destroyEvents.front().PeekEventImpl(); + m_destroyEvents.pop_front(); + NS_LOG_LOGIC("handle destroy " << ev); + if (!ev->IsCancelled()) { - ev->Invoke (); + ev->Invoke(); } } - MtpInterface::Disable (); - MpiInterface::Destroy (); + MtpInterface::Disable(); + MpiInterface::Destroy(); } bool -HybridSimulatorImpl::IsFinished (void) const +HybridSimulatorImpl::IsFinished(void) const { - return m_globalFinished; + return m_globalFinished; } bool -HybridSimulatorImpl::IsLocalFinished (void) const +HybridSimulatorImpl::IsLocalFinished(void) const { - return MtpInterface::isFinished (); + return MtpInterface::isFinished(); } void -HybridSimulatorImpl::Stop (void) +HybridSimulatorImpl::Stop(void) { - NS_LOG_FUNCTION (this); - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + NS_LOG_FUNCTION(this); + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - MtpInterface::GetSystem (i)->Stop (); + MtpInterface::GetSystem(i)->Stop(); } } void -HybridSimulatorImpl::Stop (Time const &delay) +HybridSimulatorImpl::Stop(const Time& delay) { - NS_LOG_FUNCTION (this << delay.GetTimeStep ()); - Simulator::Schedule (delay, &Simulator::Stop); + NS_LOG_FUNCTION(this << delay.GetTimeStep()); + Simulator::Schedule(delay, &Simulator::Stop); } EventId -HybridSimulatorImpl::Schedule (Time const &delay, EventImpl *event) +HybridSimulatorImpl::Schedule(const Time& delay, EventImpl* event) { - NS_LOG_FUNCTION (this << delay.GetTimeStep () << event); - return MtpInterface::GetSystem ()->Schedule (delay, event); + NS_LOG_FUNCTION(this << delay.GetTimeStep() << event); + return MtpInterface::GetSystem()->Schedule(delay, event); } void -HybridSimulatorImpl::ScheduleWithContext (uint32_t context, Time const &delay, EventImpl *event) +HybridSimulatorImpl::ScheduleWithContext(uint32_t context, const Time& delay, EventImpl* event) { - NS_LOG_FUNCTION (this << context << delay.GetTimeStep () << event); + NS_LOG_FUNCTION(this << context << delay.GetTimeStep() << event); - if (MtpInterface::GetSize () == 1) + if (MtpInterface::GetSize() == 1) { - // initialization stage, do not schedule remote - LogicalProcess *local = MtpInterface::GetSystem (); - local->ScheduleWithContext (local, context, delay, event); + // initialization stage, do not schedule remote + LogicalProcess* local = MtpInterface::GetSystem(); + local->ScheduleWithContext(local, context, delay, event); } - else + else { - LogicalProcess *remote = - MtpInterface::GetSystem (NodeList::GetNode (context)->GetSystemId () >> 16); - MtpInterface::GetSystem ()->ScheduleWithContext (remote, context, delay, event); + LogicalProcess* remote = + MtpInterface::GetSystem(NodeList::GetNode(context)->GetSystemId() >> 16); + MtpInterface::GetSystem()->ScheduleWithContext(remote, context, delay, event); } } EventId -HybridSimulatorImpl::ScheduleNow (EventImpl *event) +HybridSimulatorImpl::ScheduleNow(EventImpl* event) { - return Schedule (TimeStep (0), event); + return Schedule(TimeStep(0), event); } EventId -HybridSimulatorImpl::ScheduleDestroy (EventImpl *event) +HybridSimulatorImpl::ScheduleDestroy(EventImpl* event) { - EventId id (Ptr (event, false), GetMaximumSimulationTime ().GetTimeStep (), 0xffffffff, - EventId::DESTROY); - MtpInterface::CriticalSection cs; - m_destroyEvents.push_back (id); - return id; + EventId id(Ptr(event, false), + GetMaximumSimulationTime().GetTimeStep(), + 0xffffffff, + EventId::DESTROY); + MtpInterface::CriticalSection cs; + m_destroyEvents.push_back(id); + return id; } void -HybridSimulatorImpl::Remove (const EventId &id) +HybridSimulatorImpl::Remove(const EventId& id) { - if (id.GetUid () == EventId::DESTROY) + if (id.GetUid() == EventId::DESTROY) { - // destroy events. - for (std::list::iterator i = m_destroyEvents.begin (); i != m_destroyEvents.end (); - i++) + // destroy events. + for (std::list::iterator i = m_destroyEvents.begin(); i != m_destroyEvents.end(); + i++) { - if (*i == id) + if (*i == id) { - m_destroyEvents.erase (i); - break; + m_destroyEvents.erase(i); + break; } } } - else + else { - MtpInterface::GetSystem ()->Remove (id); + MtpInterface::GetSystem()->Remove(id); } } void -HybridSimulatorImpl::Cancel (const EventId &id) +HybridSimulatorImpl::Cancel(const EventId& id) { - if (!IsExpired (id)) + if (!IsExpired(id)) { - id.PeekEventImpl ()->Cancel (); + id.PeekEventImpl()->Cancel(); } } bool -HybridSimulatorImpl::IsExpired (const EventId &id) const +HybridSimulatorImpl::IsExpired(const EventId& id) const { - if (id.GetUid () == EventId::DESTROY) + if (id.GetUid() == EventId::DESTROY) { - // destroy events. - if (id.PeekEventImpl () == 0 || id.PeekEventImpl ()->IsCancelled ()) + // destroy events. + if (id.PeekEventImpl() == 0 || id.PeekEventImpl()->IsCancelled()) { - return true; + return true; } - for (std::list::const_iterator i = m_destroyEvents.begin (); - i != m_destroyEvents.end (); i++) + for (std::list::const_iterator i = m_destroyEvents.begin(); + i != m_destroyEvents.end(); + i++) { - if (*i == id) + if (*i == id) { - return false; + return false; } } - return true; + return true; } - else + else { - return MtpInterface::GetSystem ()->IsExpired (id); + return MtpInterface::GetSystem()->IsExpired(id); } } void -HybridSimulatorImpl::Run (void) +HybridSimulatorImpl::Run(void) { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - Partition (); - MtpInterface::RunBefore (); + Partition(); + MtpInterface::RunBefore(); - m_globalFinished = false; - while (!m_globalFinished) + m_globalFinished = false; + while (!m_globalFinished) { - GrantedTimeWindowMpiInterface::ReceiveMessages (); - GrantedTimeWindowMpiInterface::TestSendComplete (); - MtpInterface::CalculateSmallestTime (); - LbtsMessage lMsg (GrantedTimeWindowMpiInterface::GetRxCount (), - GrantedTimeWindowMpiInterface::GetTxCount (), m_myId, IsLocalFinished (), - MtpInterface::GetSmallestTime ()); - m_pLBTS[m_myId] = lMsg; - MPI_Allgather (&lMsg, sizeof (LbtsMessage), MPI_BYTE, m_pLBTS, sizeof (LbtsMessage), MPI_BYTE, - MpiInterface::GetCommunicator ()); - m_smallestTime = m_pLBTS[0].GetSmallestTime (); + GrantedTimeWindowMpiInterface::ReceiveMessages(); + GrantedTimeWindowMpiInterface::TestSendComplete(); + MtpInterface::CalculateSmallestTime(); + LbtsMessage lMsg(GrantedTimeWindowMpiInterface::GetRxCount(), + GrantedTimeWindowMpiInterface::GetTxCount(), + m_myId, + IsLocalFinished(), + MtpInterface::GetSmallestTime()); + m_pLBTS[m_myId] = lMsg; + MPI_Allgather(&lMsg, + sizeof(LbtsMessage), + MPI_BYTE, + m_pLBTS, + sizeof(LbtsMessage), + MPI_BYTE, + MpiInterface::GetCommunicator()); + m_smallestTime = m_pLBTS[0].GetSmallestTime(); - // The totRx and totTx counts insure there are no transient - // messages; If totRx != totTx, there are transients, - // so we don't update the granted time. - uint32_t totRx = m_pLBTS[0].GetRxCount (); - uint32_t totTx = m_pLBTS[0].GetTxCount (); - m_globalFinished = m_pLBTS[0].IsFinished (); + // The totRx and totTx counts insure there are no transient + // messages; If totRx != totTx, there are transients, + // so we don't update the granted time. + uint32_t totRx = m_pLBTS[0].GetRxCount(); + uint32_t totTx = m_pLBTS[0].GetTxCount(); + m_globalFinished = m_pLBTS[0].IsFinished(); - // calculate smallest time of all hosts - for (uint32_t i = 1; i < m_systemCount; ++i) + // calculate smallest time of all hosts + for (uint32_t i = 1; i < m_systemCount; ++i) { - if (m_pLBTS[i].GetSmallestTime () < m_smallestTime) + if (m_pLBTS[i].GetSmallestTime() < m_smallestTime) { - m_smallestTime = m_pLBTS[i].GetSmallestTime (); + m_smallestTime = m_pLBTS[i].GetSmallestTime(); } - totRx += m_pLBTS[i].GetRxCount (); - totTx += m_pLBTS[i].GetTxCount (); - m_globalFinished &= m_pLBTS[i].IsFinished (); + totRx += m_pLBTS[i].GetRxCount(); + totTx += m_pLBTS[i].GetTxCount(); + m_globalFinished &= m_pLBTS[i].IsFinished(); } - MtpInterface::SetSmallestTime (m_smallestTime); + MtpInterface::SetSmallestTime(m_smallestTime); - // Global halting condition is all nodes have empty queue's and - // no messages are in-flight. - m_globalFinished &= totRx == totTx; + // Global halting condition is all nodes have empty queue's and + // no messages are in-flight. + m_globalFinished &= totRx == totTx; - // Execute next event if it is within the current time window. - // Local task may be completed. - if (totRx == totTx && !IsLocalFinished ()) + // Execute next event if it is within the current time window. + // Local task may be completed. + if (totRx == totTx && !IsLocalFinished()) { // Safe to process - MtpInterface::ProcessOneRound (); + MtpInterface::ProcessOneRound(); } } - MtpInterface::RunAfter (); + MtpInterface::RunAfter(); } Time -HybridSimulatorImpl::Now (void) const +HybridSimulatorImpl::Now(void) const { - // Do not add function logging here, to avoid stack overflow - return MtpInterface::GetSystem ()->Now (); + // Do not add function logging here, to avoid stack overflow + return MtpInterface::GetSystem()->Now(); } Time -HybridSimulatorImpl::GetDelayLeft (const EventId &id) const +HybridSimulatorImpl::GetDelayLeft(const EventId& id) const { - if (IsExpired (id)) + if (IsExpired(id)) { - return TimeStep (0); + return TimeStep(0); } - else + else { - return MtpInterface::GetSystem ()->GetDelayLeft (id); + return MtpInterface::GetSystem()->GetDelayLeft(id); } } Time -HybridSimulatorImpl::GetMaximumSimulationTime (void) const +HybridSimulatorImpl::GetMaximumSimulationTime(void) const { - return Time::Max () / 2; + return Time::Max() / 2; } void -HybridSimulatorImpl::SetScheduler (ObjectFactory schedulerFactory) +HybridSimulatorImpl::SetScheduler(ObjectFactory schedulerFactory) { - NS_LOG_FUNCTION (this << schedulerFactory); - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + NS_LOG_FUNCTION(this << schedulerFactory); + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - MtpInterface::GetSystem (i)->SetScheduler (schedulerFactory); + MtpInterface::GetSystem(i)->SetScheduler(schedulerFactory); } - m_schedulerTypeId = schedulerFactory.GetTypeId (); + m_schedulerTypeId = schedulerFactory.GetTypeId(); } uint32_t -HybridSimulatorImpl::GetSystemId () const +HybridSimulatorImpl::GetSystemId() const { - return m_myId; + return m_myId; } uint32_t -HybridSimulatorImpl::GetContext (void) const +HybridSimulatorImpl::GetContext(void) const { - return MtpInterface::GetSystem ()->GetContext (); + return MtpInterface::GetSystem()->GetContext(); } uint64_t -HybridSimulatorImpl::GetEventCount (void) const +HybridSimulatorImpl::GetEventCount(void) const { - uint64_t eventCount = 0; - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + uint64_t eventCount = 0; + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - eventCount += MtpInterface::GetSystem (i)->GetEventCount (); + eventCount += MtpInterface::GetSystem(i)->GetEventCount(); } - return eventCount; + return eventCount; } void -HybridSimulatorImpl::DoDispose (void) +HybridSimulatorImpl::DoDispose(void) { - delete[] m_pLBTS; - SimulatorImpl::DoDispose (); + delete[] m_pLBTS; + SimulatorImpl::DoDispose(); } void -HybridSimulatorImpl::Partition () +HybridSimulatorImpl::Partition() { - NS_LOG_FUNCTION (this); - uint32_t localSystemId = 0; - NodeContainer nodes = NodeContainer::GetGlobal (); - bool *visited = new bool[nodes.GetN ()]{false}; - std::queue> q; + NS_LOG_FUNCTION(this); + uint32_t localSystemId = 0; + NodeContainer nodes = NodeContainer::GetGlobal(); + bool* visited = new bool[nodes.GetN()]{false}; + std::queue> q; - // perform a BFS on the whole network topo to assign each node a localSystemId - for (NodeContainer::Iterator it = nodes.Begin (); it != nodes.End (); it++) + // perform a BFS on the whole network topo to assign each node a localSystemId + for (NodeContainer::Iterator it = nodes.Begin(); it != nodes.End(); it++) { - Ptr node = *it; - if (!visited[node->GetId ()] && node->GetSystemId () == m_myId) + Ptr node = *it; + if (!visited[node->GetId()] && node->GetSystemId() == m_myId) { - q.push (node); - localSystemId++; - while (!q.empty ()) + q.push(node); + localSystemId++; + while (!q.empty()) { - // pop from BFS queue - node = q.front (); - q.pop (); - visited[node->GetId ()] = true; - // assign this node the current localSystemId - node->SetSystemId (localSystemId << 16 | m_myId); - NS_LOG_INFO ("node " << node->GetId () << " is set to local system " - << localSystemId); + // pop from BFS queue + node = q.front(); + q.pop(); + visited[node->GetId()] = true; + // assign this node the current localSystemId + node->SetSystemId(localSystemId << 16 | m_myId); + NS_LOG_INFO("node " << node->GetId() << " is set to local system " + << localSystemId); - for (uint32_t i = 0; i < node->GetNDevices (); i++) + for (uint32_t i = 0; i < node->GetNDevices(); i++) { - Ptr localNetDevice = node->GetDevice (i); - Ptr channel = localNetDevice->GetChannel (); - if (channel == 0) + Ptr localNetDevice = node->GetDevice(i); + Ptr channel = localNetDevice->GetChannel(); + if (channel == 0) { - continue; + continue; } - // cut-off p2p links for partition - if (localNetDevice->IsPointToPoint ()) + // cut-off p2p links for partition + if (localNetDevice->IsPointToPoint()) { - TimeValue delay; - channel->GetAttribute ("Delay", delay); - // if delay is below threshold, do not cut-off - if (delay.Get () >= m_minLookahead) + TimeValue delay; + channel->GetAttribute("Delay", delay); + // if delay is below threshold, do not cut-off + if (delay.Get() >= m_minLookahead) { - continue; + continue; } } - // grab the adjacent nodes - for (uint32_t j = 0; j < channel->GetNDevices (); j++) + // grab the adjacent nodes + for (uint32_t j = 0; j < channel->GetNDevices(); j++) { - Ptr remote = channel->GetDevice (j)->GetNode (); - // if it's not visited, and not remote, add it to the current partition - if (!visited[remote->GetId ()] && node->GetSystemId () == m_myId) + Ptr remote = channel->GetDevice(j)->GetNode(); + // if it's not visited, and not remote, add it to the current partition + if (!visited[remote->GetId()] && node->GetSystemId() == m_myId) { - q.push (remote); + q.push(remote); } } } } } } - delete[] visited; + delete[] visited; - // after the partition, we finally know the system count - uint32_t systemCount = localSystemId; - uint32_t threadCount = std::min (m_maxThreads, systemCount); - NS_LOG_INFO ("Partition done! " << systemCount << " systems share " << threadCount << " threads"); + // after the partition, we finally know the system count + uint32_t systemCount = localSystemId; + uint32_t threadCount = std::min(m_maxThreads, systemCount); + NS_LOG_INFO("Partition done! " << systemCount << " systems share " << threadCount + << " threads"); - // create new systems - Ptr events = MtpInterface::GetSystem ()->GetPendingEvents (); - MtpInterface::Disable (); - MtpInterface::Enable (threadCount, systemCount); + // create new systems + Ptr events = MtpInterface::GetSystem()->GetPendingEvents(); + MtpInterface::Disable(); + MtpInterface::Enable(threadCount, systemCount); - // set scheduler - ObjectFactory schedulerFactory; - schedulerFactory.SetTypeId (m_schedulerTypeId); - for (uint32_t i = 0; i <= systemCount; i++) + // set scheduler + ObjectFactory schedulerFactory; + schedulerFactory.SetTypeId(m_schedulerTypeId); + for (uint32_t i = 0; i <= systemCount; i++) { - MtpInterface::GetSystem (i)->SetScheduler (schedulerFactory); + MtpInterface::GetSystem(i)->SetScheduler(schedulerFactory); } - // transfer events to new system - while (!events->IsEmpty ()) + // transfer events to new system + while (!events->IsEmpty()) { - Scheduler::Event ev = events->RemoveNext (); - // invoke initialization events (at time 0) by their insertion order - // since they may not be in the same system, causing error - if (ev.key.m_ts == 0) + Scheduler::Event ev = events->RemoveNext(); + // invoke initialization events (at time 0) by their insertion order + // since they may not be in the same system, causing error + if (ev.key.m_ts == 0) { - MtpInterface::GetSystem (ev.key.m_context == Simulator::NO_CONTEXT - ? 0 - : NodeList::GetNode (ev.key.m_context)->GetSystemId () >> 16) - ->InvokeNow (ev); + MtpInterface::GetSystem(ev.key.m_context == Simulator::NO_CONTEXT + ? 0 + : NodeList::GetNode(ev.key.m_context)->GetSystemId() >> 16) + ->InvokeNow(ev); } - else if (ev.key.m_context == Simulator::NO_CONTEXT) + else if (ev.key.m_context == Simulator::NO_CONTEXT) { - Schedule (TimeStep (ev.key.m_ts), ev.impl); + Schedule(TimeStep(ev.key.m_ts), ev.impl); } - else + else { - ScheduleWithContext (ev.key.m_context, TimeStep (ev.key.m_ts), ev.impl); + ScheduleWithContext(ev.key.m_context, TimeStep(ev.key.m_ts), ev.impl); } } } diff --git a/src/mpi/model/hybrid-simulator-impl.h b/src/mpi/model/hybrid-simulator-impl.h index 61e4e21a9..66e1dd12c 100644 --- a/src/mpi/model/hybrid-simulator-impl.h +++ b/src/mpi/model/hybrid-simulator-impl.h @@ -12,59 +12,60 @@ #include -namespace ns3 { +namespace ns3 +{ class HybridSimulatorImpl : public SimulatorImpl { -public: - static TypeId GetTypeId (void); + public: + static TypeId GetTypeId(void); - /** Default constructor. */ - HybridSimulatorImpl (); - /** Destructor. */ - ~HybridSimulatorImpl (); + /** Default constructor. */ + HybridSimulatorImpl(); + /** Destructor. */ + ~HybridSimulatorImpl(); - // virtual from SimulatorImpl - virtual void Destroy (); - virtual bool IsFinished (void) const; - virtual void Stop (void); - virtual void Stop (Time const &delay); - virtual EventId Schedule (Time const &delay, EventImpl *event); - virtual void ScheduleWithContext (uint32_t context, Time const &delay, EventImpl *event); - virtual EventId ScheduleNow (EventImpl *event); - virtual EventId ScheduleDestroy (EventImpl *event); - virtual void Remove (const EventId &id); - virtual void Cancel (const EventId &id); - virtual bool IsExpired (const EventId &id) const; - virtual void Run (void); - virtual Time Now (void) const; - virtual Time GetDelayLeft (const EventId &id) const; - virtual Time GetMaximumSimulationTime (void) const; - virtual void SetScheduler (ObjectFactory schedulerFactory); - virtual uint32_t GetSystemId (void) const; - virtual uint32_t GetContext (void) const; - virtual uint64_t GetEventCount (void) const; + // virtual from SimulatorImpl + virtual void Destroy(); + virtual bool IsFinished(void) const; + virtual void Stop(void); + virtual void Stop(const Time& delay); + virtual EventId Schedule(const Time& delay, EventImpl* event); + virtual void ScheduleWithContext(uint32_t context, const Time& delay, EventImpl* event); + virtual EventId ScheduleNow(EventImpl* event); + virtual EventId ScheduleDestroy(EventImpl* event); + virtual void Remove(const EventId& id); + virtual void Cancel(const EventId& id); + virtual bool IsExpired(const EventId& id) const; + virtual void Run(void); + virtual Time Now(void) const; + virtual Time GetDelayLeft(const EventId& id) const; + virtual Time GetMaximumSimulationTime(void) const; + virtual void SetScheduler(ObjectFactory schedulerFactory); + virtual uint32_t GetSystemId(void) const; + virtual uint32_t GetContext(void) const; + virtual uint64_t GetEventCount(void) const; -private: - // Inherited from Object - virtual void DoDispose (void); + private: + // Inherited from Object + virtual void DoDispose(void); - bool IsLocalFinished (void) const; + bool IsLocalFinished(void) const; - /** Are all parallel instances completed. */ - bool m_globalFinished; + /** Are all parallel instances completed. */ + bool m_globalFinished; - LbtsMessage *m_pLBTS; - uint32_t m_myId; /**< MPI rank. */ - uint32_t m_systemCount; /**< MPI communicator size. */ - Time m_smallestTime; /**< End of current window. */ + LbtsMessage* m_pLBTS; + uint32_t m_myId; /**< MPI rank. */ + uint32_t m_systemCount; /**< MPI communicator size. */ + Time m_smallestTime; /**< End of current window. */ - void Partition (); + void Partition(); - uint32_t m_maxThreads; - Time m_minLookahead; - TypeId m_schedulerTypeId; - std::list m_destroyEvents; + uint32_t m_maxThreads; + Time m_minLookahead; + TypeId m_schedulerTypeId; + std::list m_destroyEvents; }; } // namespace ns3 diff --git a/src/mpi/model/mpi-interface.cc b/src/mpi/model/mpi-interface.cc index 440db62fa..c539c298c 100644 --- a/src/mpi/model/mpi-interface.cc +++ b/src/mpi/model/mpi-interface.cc @@ -26,130 +26,130 @@ #include "mpi-interface.h" -#include -#include -#include - -#include "null-message-mpi-interface.h" #include "granted-time-window-mpi-interface.h" +#include "null-message-mpi-interface.h" -namespace ns3 { +#include +#include +#include -NS_LOG_COMPONENT_DEFINE ("MpiInterface"); +namespace ns3 +{ + +NS_LOG_COMPONENT_DEFINE("MpiInterface"); ParallelCommunicationInterface* MpiInterface::g_parallelCommunicationInterface = 0; void -MpiInterface::Destroy () +MpiInterface::Destroy() { - NS_ASSERT (g_parallelCommunicationInterface); - g_parallelCommunicationInterface->Destroy (); + NS_ASSERT(g_parallelCommunicationInterface); + g_parallelCommunicationInterface->Destroy(); } uint32_t -MpiInterface::GetSystemId () +MpiInterface::GetSystemId() { - if ( g_parallelCommunicationInterface ) - return g_parallelCommunicationInterface->GetSystemId (); - else - return 0; + if (g_parallelCommunicationInterface) + return g_parallelCommunicationInterface->GetSystemId(); + else + return 0; } uint32_t -MpiInterface::GetSize () +MpiInterface::GetSize() { - if ( g_parallelCommunicationInterface ) - return g_parallelCommunicationInterface->GetSize (); - else - return 1; + if (g_parallelCommunicationInterface) + return g_parallelCommunicationInterface->GetSize(); + else + return 1; } bool -MpiInterface::IsEnabled () +MpiInterface::IsEnabled() { - if (g_parallelCommunicationInterface) + if (g_parallelCommunicationInterface) { - return g_parallelCommunicationInterface->IsEnabled (); + return g_parallelCommunicationInterface->IsEnabled(); } - else + else { - return false; + return false; } } void -MpiInterface::SetParallelSimulatorImpl (void) +MpiInterface::SetParallelSimulatorImpl(void) { - StringValue simulationTypeValue; - bool useDefault = true; + StringValue simulationTypeValue; + bool useDefault = true; - if (GlobalValue::GetValueByNameFailSafe ("SimulatorImplementationType", simulationTypeValue)) + if (GlobalValue::GetValueByNameFailSafe("SimulatorImplementationType", simulationTypeValue)) { - std::string simulationType = simulationTypeValue.Get (); + std::string simulationType = simulationTypeValue.Get(); - // Set communication interface based on the simulation type being used. - // Defaults to synchronous. - if (simulationType.compare ("ns3::NullMessageSimulatorImpl") == 0) + // Set communication interface based on the simulation type being used. + // Defaults to synchronous. + if (simulationType.compare("ns3::NullMessageSimulatorImpl") == 0) { - g_parallelCommunicationInterface = new NullMessageMpiInterface (); - useDefault = false; + g_parallelCommunicationInterface = new NullMessageMpiInterface(); + useDefault = false; } - else if (simulationType.compare ("ns3::DistributedSimulatorImpl") == 0 || simulationType.compare("ns3::HybridSimulatorImpl") == 0) + else if (simulationType.compare("ns3::DistributedSimulatorImpl") == 0 || + simulationType.compare("ns3::HybridSimulatorImpl") == 0) { - g_parallelCommunicationInterface = new GrantedTimeWindowMpiInterface (); - useDefault = false; + g_parallelCommunicationInterface = new GrantedTimeWindowMpiInterface(); + useDefault = false; } } - // User did not specify a valid parallel simulator; use the default. - if (useDefault) + // User did not specify a valid parallel simulator; use the default. + if (useDefault) { - g_parallelCommunicationInterface = new GrantedTimeWindowMpiInterface (); - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::DistributedSimulatorImpl")); - NS_LOG_WARN ("SimulatorImplementationType was set to non-parallel simulator; setting type to ns3::DistributedSimulatorImp"); + g_parallelCommunicationInterface = new GrantedTimeWindowMpiInterface(); + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::DistributedSimulatorImpl")); + NS_LOG_WARN("SimulatorImplementationType was set to non-parallel simulator; setting type " + "to ns3::DistributedSimulatorImp"); } } void -MpiInterface::Enable (int* pargc, char*** pargv) +MpiInterface::Enable(int* pargc, char*** pargv) { + SetParallelSimulatorImpl(); - SetParallelSimulatorImpl (); - - g_parallelCommunicationInterface->Enable (pargc, pargv); + g_parallelCommunicationInterface->Enable(pargc, pargv); } void -MpiInterface::Enable (MPI_Comm communicator) +MpiInterface::Enable(MPI_Comm communicator) { - SetParallelSimulatorImpl (); - g_parallelCommunicationInterface->Enable (communicator); + SetParallelSimulatorImpl(); + g_parallelCommunicationInterface->Enable(communicator); } void -MpiInterface::SendPacket (Ptr p, const Time& rxTime, uint32_t node, uint32_t dev) +MpiInterface::SendPacket(Ptr p, const Time& rxTime, uint32_t node, uint32_t dev) { - NS_ASSERT (g_parallelCommunicationInterface); - g_parallelCommunicationInterface->SendPacket (p, rxTime, node, dev); + NS_ASSERT(g_parallelCommunicationInterface); + g_parallelCommunicationInterface->SendPacket(p, rxTime, node, dev); } MPI_Comm MpiInterface::GetCommunicator() { - NS_ASSERT (g_parallelCommunicationInterface); - return g_parallelCommunicationInterface->GetCommunicator (); + NS_ASSERT(g_parallelCommunicationInterface); + return g_parallelCommunicationInterface->GetCommunicator(); } - void -MpiInterface::Disable () +MpiInterface::Disable() { - NS_ASSERT (g_parallelCommunicationInterface); - g_parallelCommunicationInterface->Disable (); - delete g_parallelCommunicationInterface; - g_parallelCommunicationInterface = 0; + NS_ASSERT(g_parallelCommunicationInterface); + g_parallelCommunicationInterface->Disable(); + delete g_parallelCommunicationInterface; + g_parallelCommunicationInterface = 0; } - } // namespace ns3 diff --git a/src/mtp/examples/simple-mtp.cc b/src/mtp/examples/simple-mtp.cc index 75f80becd..c069199fd 100644 --- a/src/mtp/examples/simple-mtp.cc +++ b/src/mtp/examples/simple-mtp.cc @@ -46,199 +46,199 @@ */ #include "ns3/core-module.h" -#include "ns3/network-module.h" -#include "ns3/multithreaded-simulator-impl.h" -#include "ns3/ipv4-global-routing-helper.h" -#include "ns3/point-to-point-helper.h" #include "ns3/internet-stack-helper.h" -#include "ns3/nix-vector-helper.h" #include "ns3/ipv4-address-helper.h" +#include "ns3/ipv4-global-routing-helper.h" +#include "ns3/mtp-interface.h" +#include "ns3/multithreaded-simulator-impl.h" +#include "ns3/network-module.h" +#include "ns3/nix-vector-helper.h" #include "ns3/on-off-helper.h" #include "ns3/packet-sink-helper.h" -#include "ns3/mtp-interface.h" +#include "ns3/point-to-point-helper.h" #include using namespace ns3; -NS_LOG_COMPONENT_DEFINE ("SimpleMtp"); +NS_LOG_COMPONENT_DEFINE("SimpleMtp"); int -main (int argc, char *argv[]) +main(int argc, char* argv[]) { - bool nix = true; - bool tracing = false; - bool verbose = false; + bool nix = true; + bool tracing = false; + bool verbose = false; - // Parse command line - CommandLine cmd (__FILE__); - cmd.AddValue ("nix", "Enable the use of nix-vector or global routing", nix); - cmd.AddValue ("tracing", "Enable pcap tracing", tracing); - cmd.AddValue ("verbose", "verbose output", verbose); - cmd.Parse (argc, argv); + // Parse command line + CommandLine cmd(__FILE__); + cmd.AddValue("nix", "Enable the use of nix-vector or global routing", nix); + cmd.AddValue("tracing", "Enable pcap tracing", tracing); + cmd.AddValue("verbose", "verbose output", verbose); + cmd.Parse(argc, argv); - MtpInterface::Enable (2, 2); - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::MultithreadedSimulatorImpl")); + MtpInterface::Enable(2, 2); + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::MultithreadedSimulatorImpl")); - if (verbose) + if (verbose) { - LogComponentEnable ("PacketSink", - (LogLevel) (LOG_LEVEL_INFO | LOG_PREFIX_NODE | LOG_PREFIX_TIME)); + LogComponentEnable("PacketSink", + (LogLevel)(LOG_LEVEL_INFO | LOG_PREFIX_NODE | LOG_PREFIX_TIME)); } - // Some default values - Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (512)); - Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("1Mbps")); - Config::SetDefault ("ns3::OnOffApplication::MaxBytes", UintegerValue (512)); + // Some default values + Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(512)); + Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("1Mbps")); + Config::SetDefault("ns3::OnOffApplication::MaxBytes", UintegerValue(512)); - // Create leaf nodes on left with system id 1 - NodeContainer leftLeafNodes; - leftLeafNodes.Create (4, 1); + // Create leaf nodes on left with system id 1 + NodeContainer leftLeafNodes; + leftLeafNodes.Create(4, 1); - // Create router nodes. Left router - // with system id 0, right router with - // system id 1 - NodeContainer routerNodes; - Ptr routerNode1 = CreateObject (1); - Ptr routerNode2 = CreateObject (2); - routerNodes.Add (routerNode1); - routerNodes.Add (routerNode2); + // Create router nodes. Left router + // with system id 0, right router with + // system id 1 + NodeContainer routerNodes; + Ptr routerNode1 = CreateObject(1); + Ptr routerNode2 = CreateObject(2); + routerNodes.Add(routerNode1); + routerNodes.Add(routerNode2); - // Create leaf nodes on right with system id 2 - NodeContainer rightLeafNodes; - rightLeafNodes.Create (4, 2); + // Create leaf nodes on right with system id 2 + NodeContainer rightLeafNodes; + rightLeafNodes.Create(4, 2); - PointToPointHelper routerLink; - routerLink.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); - routerLink.SetChannelAttribute ("Delay", StringValue ("5ms")); + PointToPointHelper routerLink; + routerLink.SetDeviceAttribute("DataRate", StringValue("5Mbps")); + routerLink.SetChannelAttribute("Delay", StringValue("5ms")); - PointToPointHelper leafLink; - leafLink.SetDeviceAttribute ("DataRate", StringValue ("1Mbps")); - leafLink.SetChannelAttribute ("Delay", StringValue ("2ms")); + PointToPointHelper leafLink; + leafLink.SetDeviceAttribute("DataRate", StringValue("1Mbps")); + leafLink.SetChannelAttribute("Delay", StringValue("2ms")); - // Add link connecting routers - NetDeviceContainer routerDevices; - routerDevices = routerLink.Install (routerNodes); + // Add link connecting routers + NetDeviceContainer routerDevices; + routerDevices = routerLink.Install(routerNodes); - // Add links for left side leaf nodes to left router - NetDeviceContainer leftRouterDevices; - NetDeviceContainer leftLeafDevices; - for (uint32_t i = 0; i < 4; ++i) + // Add links for left side leaf nodes to left router + NetDeviceContainer leftRouterDevices; + NetDeviceContainer leftLeafDevices; + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer temp = leafLink.Install (leftLeafNodes.Get (i), routerNodes.Get (0)); - leftLeafDevices.Add (temp.Get (0)); - leftRouterDevices.Add (temp.Get (1)); + NetDeviceContainer temp = leafLink.Install(leftLeafNodes.Get(i), routerNodes.Get(0)); + leftLeafDevices.Add(temp.Get(0)); + leftRouterDevices.Add(temp.Get(1)); } - // Add links for right side leaf nodes to right router - NetDeviceContainer rightRouterDevices; - NetDeviceContainer rightLeafDevices; - for (uint32_t i = 0; i < 4; ++i) + // Add links for right side leaf nodes to right router + NetDeviceContainer rightRouterDevices; + NetDeviceContainer rightLeafDevices; + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer temp = leafLink.Install (rightLeafNodes.Get (i), routerNodes.Get (1)); - rightLeafDevices.Add (temp.Get (0)); - rightRouterDevices.Add (temp.Get (1)); + NetDeviceContainer temp = leafLink.Install(rightLeafNodes.Get(i), routerNodes.Get(1)); + rightLeafDevices.Add(temp.Get(0)); + rightRouterDevices.Add(temp.Get(1)); } - InternetStackHelper stack; - if (nix) + InternetStackHelper stack; + if (nix) { - Ipv4NixVectorHelper nixRouting; - stack.SetRoutingHelper (nixRouting); // has effect on the next Install () + Ipv4NixVectorHelper nixRouting; + stack.SetRoutingHelper(nixRouting); // has effect on the next Install () } - stack.InstallAll (); + stack.InstallAll(); - Ipv4InterfaceContainer routerInterfaces; - Ipv4InterfaceContainer leftLeafInterfaces; - Ipv4InterfaceContainer leftRouterInterfaces; - Ipv4InterfaceContainer rightLeafInterfaces; - Ipv4InterfaceContainer rightRouterInterfaces; + Ipv4InterfaceContainer routerInterfaces; + Ipv4InterfaceContainer leftLeafInterfaces; + Ipv4InterfaceContainer leftRouterInterfaces; + Ipv4InterfaceContainer rightLeafInterfaces; + Ipv4InterfaceContainer rightRouterInterfaces; - Ipv4AddressHelper leftAddress; - leftAddress.SetBase ("10.1.1.0", "255.255.255.0"); + Ipv4AddressHelper leftAddress; + leftAddress.SetBase("10.1.1.0", "255.255.255.0"); - Ipv4AddressHelper routerAddress; - routerAddress.SetBase ("10.2.1.0", "255.255.255.0"); + Ipv4AddressHelper routerAddress; + routerAddress.SetBase("10.2.1.0", "255.255.255.0"); - Ipv4AddressHelper rightAddress; - rightAddress.SetBase ("10.3.1.0", "255.255.255.0"); + Ipv4AddressHelper rightAddress; + rightAddress.SetBase("10.3.1.0", "255.255.255.0"); - // Router-to-Router interfaces - routerInterfaces = routerAddress.Assign (routerDevices); + // Router-to-Router interfaces + routerInterfaces = routerAddress.Assign(routerDevices); - // Left interfaces - for (uint32_t i = 0; i < 4; ++i) + // Left interfaces + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer ndc; - ndc.Add (leftLeafDevices.Get (i)); - ndc.Add (leftRouterDevices.Get (i)); - Ipv4InterfaceContainer ifc = leftAddress.Assign (ndc); - leftLeafInterfaces.Add (ifc.Get (0)); - leftRouterInterfaces.Add (ifc.Get (1)); - leftAddress.NewNetwork (); + NetDeviceContainer ndc; + ndc.Add(leftLeafDevices.Get(i)); + ndc.Add(leftRouterDevices.Get(i)); + Ipv4InterfaceContainer ifc = leftAddress.Assign(ndc); + leftLeafInterfaces.Add(ifc.Get(0)); + leftRouterInterfaces.Add(ifc.Get(1)); + leftAddress.NewNetwork(); } - // Right interfaces - for (uint32_t i = 0; i < 4; ++i) + // Right interfaces + for (uint32_t i = 0; i < 4; ++i) { - NetDeviceContainer ndc; - ndc.Add (rightLeafDevices.Get (i)); - ndc.Add (rightRouterDevices.Get (i)); - Ipv4InterfaceContainer ifc = rightAddress.Assign (ndc); - rightLeafInterfaces.Add (ifc.Get (0)); - rightRouterInterfaces.Add (ifc.Get (1)); - rightAddress.NewNetwork (); + NetDeviceContainer ndc; + ndc.Add(rightLeafDevices.Get(i)); + ndc.Add(rightRouterDevices.Get(i)); + Ipv4InterfaceContainer ifc = rightAddress.Assign(ndc); + rightLeafInterfaces.Add(ifc.Get(0)); + rightRouterInterfaces.Add(ifc.Get(1)); + rightAddress.NewNetwork(); } - if (!nix) + if (!nix) { - Ipv4GlobalRoutingHelper::PopulateRoutingTables (); + Ipv4GlobalRoutingHelper::PopulateRoutingTables(); } - if (tracing == true) + if (tracing == true) { - routerLink.EnablePcap ("router-left", routerDevices, true); - leafLink.EnablePcap ("leaf-left", leftLeafDevices, true); - routerLink.EnablePcap ("router-right", routerDevices, true); - leafLink.EnablePcap ("leaf-right", rightLeafDevices, true); + routerLink.EnablePcap("router-left", routerDevices, true); + leafLink.EnablePcap("leaf-left", leftLeafDevices, true); + routerLink.EnablePcap("router-right", routerDevices, true); + leafLink.EnablePcap("leaf-right", rightLeafDevices, true); } - // Create a packet sink on the right leafs to receive packets from left leafs + // Create a packet sink on the right leafs to receive packets from left leafs - uint16_t port = 50000; + uint16_t port = 50000; - Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port)); - PacketSinkHelper sinkHelper ("ns3::UdpSocketFactory", sinkLocalAddress); - ApplicationContainer sinkApp; - for (uint32_t i = 0; i < 4; ++i) + Address sinkLocalAddress(InetSocketAddress(Ipv4Address::GetAny(), port)); + PacketSinkHelper sinkHelper("ns3::UdpSocketFactory", sinkLocalAddress); + ApplicationContainer sinkApp; + for (uint32_t i = 0; i < 4; ++i) { - sinkApp.Add (sinkHelper.Install (rightLeafNodes.Get (i))); + sinkApp.Add(sinkHelper.Install(rightLeafNodes.Get(i))); } - sinkApp.Start (Seconds (1.0)); - sinkApp.Stop (Seconds (5)); + sinkApp.Start(Seconds(1.0)); + sinkApp.Stop(Seconds(5)); - // Create the OnOff applications to send + // Create the OnOff applications to send - OnOffHelper clientHelper ("ns3::UdpSocketFactory", Address ()); - clientHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); - clientHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); + OnOffHelper clientHelper("ns3::UdpSocketFactory", Address()); + clientHelper.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]")); + clientHelper.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]")); - ApplicationContainer clientApps; - for (uint32_t i = 0; i < 4; ++i) + ApplicationContainer clientApps; + for (uint32_t i = 0; i < 4; ++i) { - AddressValue remoteAddress (InetSocketAddress (rightLeafInterfaces.GetAddress (i), port)); - clientHelper.SetAttribute ("Remote", remoteAddress); - clientApps.Add (clientHelper.Install (leftLeafNodes.Get (i))); + AddressValue remoteAddress(InetSocketAddress(rightLeafInterfaces.GetAddress(i), port)); + clientHelper.SetAttribute("Remote", remoteAddress); + clientApps.Add(clientHelper.Install(leftLeafNodes.Get(i))); } - clientApps.Start (Seconds (1.0)); - clientApps.Stop (Seconds (5)); + clientApps.Start(Seconds(1.0)); + clientApps.Stop(Seconds(5)); - Simulator::Stop (Seconds (5)); - Simulator::Run (); - Simulator::Destroy (); + Simulator::Stop(Seconds(5)); + Simulator::Run(); + Simulator::Destroy(); - // Exit the MPI execution environment - return 0; + // Exit the MPI execution environment + return 0; } diff --git a/src/mtp/model/logical-process.cc b/src/mtp/model/logical-process.cc index 5ae82b8c1..8b19193c4 100644 --- a/src/mtp/model/logical-process.cc +++ b/src/mtp/model/logical-process.cc @@ -1,6 +1,7 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "logical-process.h" + #include "mtp-interface.h" #include "ns3/channel.h" @@ -9,302 +10,305 @@ #include -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("LogicalProcess"); - -LogicalProcess::LogicalProcess () +namespace ns3 { - m_systemId = 0; - m_systemCount = 0; - m_uid = EventId::UID::VALID; - m_stop = false; - m_currentContext = Simulator::NO_CONTEXT; - m_currentUid = 0; - m_currentTs = 0; - m_eventCount = 0; - m_pendingEventCount = 0; - m_events = 0; - m_lookAhead = TimeStep (0); + +NS_LOG_COMPONENT_DEFINE("LogicalProcess"); + +LogicalProcess::LogicalProcess() +{ + m_systemId = 0; + m_systemCount = 0; + m_uid = EventId::UID::VALID; + m_stop = false; + m_currentContext = Simulator::NO_CONTEXT; + m_currentUid = 0; + m_currentTs = 0; + m_eventCount = 0; + m_pendingEventCount = 0; + m_events = 0; + m_lookAhead = TimeStep(0); } -LogicalProcess::~LogicalProcess () +LogicalProcess::~LogicalProcess() { - NS_LOG_INFO ("system " << m_systemId << " finished with event count " << m_eventCount); + NS_LOG_INFO("system " << m_systemId << " finished with event count " << m_eventCount); - // if others hold references to event list, do not unref events - if (m_events->GetReferenceCount () == 1) + // if others hold references to event list, do not unref events + if (m_events->GetReferenceCount() == 1) { - while (!m_events->IsEmpty ()) + while (!m_events->IsEmpty()) { - Scheduler::Event next = m_events->RemoveNext (); - next.impl->Unref (); + Scheduler::Event next = m_events->RemoveNext(); + next.impl->Unref(); } } } void -LogicalProcess::Enable (const uint32_t systemId, const uint32_t systemCount) +LogicalProcess::Enable(const uint32_t systemId, const uint32_t systemCount) { - m_systemId = systemId; - m_systemCount = systemCount; + m_systemId = systemId; + m_systemCount = systemCount; } void -LogicalProcess::CalculateLookAhead () +LogicalProcess::CalculateLookAhead() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - if (m_systemId == 0) + if (m_systemId == 0) { - m_lookAhead = TimeStep (0); // No lookahead for public LP + m_lookAhead = TimeStep(0); // No lookahead for public LP } - else + else { - m_lookAhead = Time::Max () / 2 - TimeStep (1); - NodeContainer c = NodeContainer::GetGlobal (); - for (NodeContainer::Iterator iter = c.Begin (); iter != c.End (); ++iter) + m_lookAhead = Time::Max() / 2 - TimeStep(1); + NodeContainer c = NodeContainer::GetGlobal(); + for (NodeContainer::Iterator iter = c.Begin(); iter != c.End(); ++iter) { #ifdef NS3_MPI - if (((*iter)->GetSystemId () >> 16) != m_systemId) + if (((*iter)->GetSystemId() >> 16) != m_systemId) { - continue; + continue; } #else - if ((*iter)->GetSystemId () != m_systemId) + if ((*iter)->GetSystemId() != m_systemId) { - continue; + continue; } #endif - for (uint32_t i = 0; i < (*iter)->GetNDevices (); ++i) + for (uint32_t i = 0; i < (*iter)->GetNDevices(); ++i) { - Ptr localNetDevice = (*iter)->GetDevice (i); - // only works for p2p links currently - if (!localNetDevice->IsPointToPoint ()) + Ptr localNetDevice = (*iter)->GetDevice(i); + // only works for p2p links currently + if (!localNetDevice->IsPointToPoint()) { - continue; + continue; } - Ptr channel = localNetDevice->GetChannel (); - if (channel == 0) + Ptr channel = localNetDevice->GetChannel(); + if (channel == 0) { - continue; + continue; } - // grab the adjacent node - Ptr remoteNode; - if (channel->GetDevice (0) == localNetDevice) + // grab the adjacent node + Ptr remoteNode; + if (channel->GetDevice(0) == localNetDevice) { - remoteNode = (channel->GetDevice (1))->GetNode (); + remoteNode = (channel->GetDevice(1))->GetNode(); } - else + else { - remoteNode = (channel->GetDevice (0))->GetNode (); + remoteNode = (channel->GetDevice(0))->GetNode(); } - // if it's not remote, don't consider it - if (remoteNode->GetSystemId () == m_systemId) + // if it's not remote, don't consider it + if (remoteNode->GetSystemId() == m_systemId) { - continue; + continue; } - // compare delay on the channel with current value of m_lookAhead. - // if delay on channel is smaller, make it the new lookAhead. - TimeValue delay; - channel->GetAttribute ("Delay", delay); - if (delay.Get () < m_lookAhead) + // compare delay on the channel with current value of m_lookAhead. + // if delay on channel is smaller, make it the new lookAhead. + TimeValue delay; + channel->GetAttribute("Delay", delay); + if (delay.Get() < m_lookAhead) { - m_lookAhead = delay.Get (); + m_lookAhead = delay.Get(); } - // add the neighbour to the mailbox - m_mailbox[remoteNode->GetSystemId ()]; + // add the neighbour to the mailbox + m_mailbox[remoteNode->GetSystemId()]; } } } - NS_LOG_INFO ("lookahead of system " << m_systemId << " is set to " << m_lookAhead.GetTimeStep ()); + NS_LOG_INFO("lookahead of system " << m_systemId << " is set to " << m_lookAhead.GetTimeStep()); } void -LogicalProcess::ReceiveMessages () +LogicalProcess::ReceiveMessages() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - m_pendingEventCount = 0; - for (auto &item : m_mailbox) + m_pendingEventCount = 0; + for (auto& item : m_mailbox) { - auto &queue = item.second; - std::sort (queue.begin (), queue.end (), std::greater<> ()); - while (!queue.empty ()) + auto& queue = item.second; + std::sort(queue.begin(), queue.end(), std::greater<>()); + while (!queue.empty()) { - auto &evWithTs = queue.back (); - Scheduler::Event &ev = std::get<3> (evWithTs); - ev.key.m_uid = m_uid++; - m_events->Insert (ev); - queue.pop_back (); - m_pendingEventCount++; + auto& evWithTs = queue.back(); + Scheduler::Event& ev = std::get<3>(evWithTs); + ev.key.m_uid = m_uid++; + m_events->Insert(ev); + queue.pop_back(); + m_pendingEventCount++; } } } void -LogicalProcess::ProcessOneRound () +LogicalProcess::ProcessOneRound() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); - // set thread context - MtpInterface::SetSystem (m_systemId); + // set thread context + MtpInterface::SetSystem(m_systemId); - // calculate time window - Time grantedTime = - Min (MtpInterface::GetSmallestTime () + m_lookAhead, MtpInterface::GetNextPublicTime ()); + // calculate time window + Time grantedTime = + Min(MtpInterface::GetSmallestTime() + m_lookAhead, MtpInterface::GetNextPublicTime()); - auto start = std::chrono::system_clock::now (); + auto start = std::chrono::system_clock::now(); - // process events - while (Next () <= grantedTime) + // process events + while (Next() <= grantedTime) { - Scheduler::Event next = m_events->RemoveNext (); - m_eventCount++; - NS_LOG_LOGIC ("handle " << next.key.m_ts); + Scheduler::Event next = m_events->RemoveNext(); + m_eventCount++; + NS_LOG_LOGIC("handle " << next.key.m_ts); - m_currentTs = next.key.m_ts; - m_currentContext = next.key.m_context; - m_currentUid = next.key.m_uid; + m_currentTs = next.key.m_ts; + m_currentContext = next.key.m_context; + m_currentUid = next.key.m_uid; - next.impl->Invoke (); - next.impl->Unref (); + next.impl->Invoke(); + next.impl->Unref(); } - auto end = std::chrono::system_clock::now (); - m_executionTime = std::chrono::duration_cast (end - start).count (); + auto end = std::chrono::system_clock::now(); + m_executionTime = std::chrono::duration_cast(end - start).count(); } EventId -LogicalProcess::Schedule (Time const &delay, EventImpl *event) +LogicalProcess::Schedule(const Time& delay, EventImpl* event) { - Scheduler::Event ev; + Scheduler::Event ev; - ev.impl = event; - ev.key.m_ts = m_currentTs + delay.GetTimeStep (); - ev.key.m_context = GetContext (); - ev.key.m_uid = m_uid++; - m_events->Insert (ev); + ev.impl = event; + ev.key.m_ts = m_currentTs + delay.GetTimeStep(); + ev.key.m_context = GetContext(); + ev.key.m_uid = m_uid++; + m_events->Insert(ev); - return EventId (event, ev.key.m_ts, ev.key.m_context, ev.key.m_uid); + return EventId(event, ev.key.m_ts, ev.key.m_context, ev.key.m_uid); } void -LogicalProcess::ScheduleAt (const uint32_t context, Time const &time, EventImpl *event) +LogicalProcess::ScheduleAt(const uint32_t context, const Time& time, EventImpl* event) { - Scheduler::Event ev; + Scheduler::Event ev; - ev.impl = event; - ev.key.m_ts = time.GetTimeStep (); - ev.key.m_context = context; - ev.key.m_uid = m_uid++; - m_events->Insert (ev); + ev.impl = event; + ev.key.m_ts = time.GetTimeStep(); + ev.key.m_context = context; + ev.key.m_uid = m_uid++; + m_events->Insert(ev); } void -LogicalProcess::ScheduleWithContext (LogicalProcess *remote, const uint32_t context, - Time const &delay, EventImpl *event) +LogicalProcess::ScheduleWithContext(LogicalProcess* remote, + const uint32_t context, + const Time& delay, + EventImpl* event) { - Scheduler::Event ev; + Scheduler::Event ev; - ev.impl = event; - ev.key.m_ts = delay.GetTimeStep () + m_currentTs; - ev.key.m_context = context; + ev.impl = event; + ev.key.m_ts = delay.GetTimeStep() + m_currentTs; + ev.key.m_context = context; - if (remote == this) + if (remote == this) { - ev.key.m_uid = m_uid++; - m_events->Insert (ev); + ev.key.m_uid = m_uid++; + m_events->Insert(ev); } - else + else { - ev.key.m_uid = EventId::UID::INVALID; - remote->m_mailbox[m_systemId].push_back ( - std::make_tuple (m_currentTs, m_systemId, m_uid, ev)); + ev.key.m_uid = EventId::UID::INVALID; + remote->m_mailbox[m_systemId].push_back( + std::make_tuple(m_currentTs, m_systemId, m_uid, ev)); } } void -LogicalProcess::InvokeNow (Scheduler::Event const &ev) +LogicalProcess::InvokeNow(const Scheduler::Event& ev) { - uint32_t oldSystemId = MtpInterface::GetSystem ()->GetSystemId (); - MtpInterface::SetSystem (m_systemId); + uint32_t oldSystemId = MtpInterface::GetSystem()->GetSystemId(); + MtpInterface::SetSystem(m_systemId); - m_eventCount++; - NS_LOG_LOGIC ("handle " << ev.key.m_ts); + m_eventCount++; + NS_LOG_LOGIC("handle " << ev.key.m_ts); - m_currentTs = ev.key.m_ts; - m_currentContext = ev.key.m_context; - m_currentUid = ev.key.m_uid; + m_currentTs = ev.key.m_ts; + m_currentContext = ev.key.m_context; + m_currentUid = ev.key.m_uid; - ev.impl->Invoke (); - ev.impl->Unref (); + ev.impl->Invoke(); + ev.impl->Unref(); - // restore previous thread context - MtpInterface::SetSystem (oldSystemId); + // restore previous thread context + MtpInterface::SetSystem(oldSystemId); } void -LogicalProcess::Remove (const EventId &id) +LogicalProcess::Remove(const EventId& id) { - if (IsExpired (id)) + if (IsExpired(id)) { - return; + return; } - Scheduler::Event event; + Scheduler::Event event; - event.impl = id.PeekEventImpl (); - event.key.m_ts = id.GetTs (); - event.key.m_context = id.GetContext (); - event.key.m_uid = id.GetUid (); - m_events->Remove (event); - event.impl->Cancel (); - // whenever we remove an event from the event list, we have to unref it. - event.impl->Unref (); + event.impl = id.PeekEventImpl(); + event.key.m_ts = id.GetTs(); + event.key.m_context = id.GetContext(); + event.key.m_uid = id.GetUid(); + m_events->Remove(event); + event.impl->Cancel(); + // whenever we remove an event from the event list, we have to unref it. + event.impl->Unref(); } bool -LogicalProcess::IsExpired (const EventId &id) const +LogicalProcess::IsExpired(const EventId& id) const { - if (id.PeekEventImpl () == 0 || id.GetTs () < m_currentTs || - (id.GetTs () == m_currentTs && id.GetUid () <= m_currentUid) || - id.PeekEventImpl ()->IsCancelled ()) + if (id.PeekEventImpl() == 0 || id.GetTs() < m_currentTs || + (id.GetTs() == m_currentTs && id.GetUid() <= m_currentUid) || + id.PeekEventImpl()->IsCancelled()) { - return true; + return true; } - else + else { - return false; + return false; } } void -LogicalProcess::SetScheduler (ObjectFactory schedulerFactory) +LogicalProcess::SetScheduler(ObjectFactory schedulerFactory) { - Ptr scheduler = schedulerFactory.Create (); - if (m_events != 0) + Ptr scheduler = schedulerFactory.Create(); + if (m_events != 0) { - while (!m_events->IsEmpty ()) + while (!m_events->IsEmpty()) { - Scheduler::Event next = m_events->RemoveNext (); - scheduler->Insert (next); + Scheduler::Event next = m_events->RemoveNext(); + scheduler->Insert(next); } } - m_events = scheduler; + m_events = scheduler; } Time -LogicalProcess::Next () const +LogicalProcess::Next() const { - if (m_stop || m_events->IsEmpty ()) + if (m_stop || m_events->IsEmpty()) { - return Time::Max (); + return Time::Max(); } - else + else { - Scheduler::Event ev = m_events->PeekNext (); - return TimeStep (ev.key.m_ts); + Scheduler::Event ev = m_events->PeekNext(); + return TimeStep(ev.key.m_ts); } } diff --git a/src/mtp/model/logical-process.h b/src/mtp/model/logical-process.h index fa0ba3e2d..179ea3a09 100644 --- a/src/mtp/model/logical-process.h +++ b/src/mtp/model/logical-process.h @@ -15,107 +15,100 @@ #include #include -namespace ns3 { +namespace ns3 +{ class LogicalProcess { -public: - LogicalProcess (); - ~LogicalProcess (); + public: + LogicalProcess(); + ~LogicalProcess(); - void Enable (const uint32_t systemId, const uint32_t systemCount); - void CalculateLookAhead (); - void ReceiveMessages (); - void ProcessOneRound (); + void Enable(const uint32_t systemId, const uint32_t systemCount); + void CalculateLookAhead(); + void ReceiveMessages(); + void ProcessOneRound(); - inline uint64_t - GetExecutionTime () const - { - return m_executionTime; - } + inline uint64_t GetExecutionTime() const + { + return m_executionTime; + } - inline uint64_t - GetPendingEventCount () const - { - return m_pendingEventCount; - } + inline uint64_t GetPendingEventCount() const + { + return m_pendingEventCount; + } - inline Ptr - GetPendingEvents () const - { - return m_events; - } + inline Ptr GetPendingEvents() const + { + return m_events; + } - // mapped from MultithreadedSimulatorImpl - EventId Schedule (Time const &delay, EventImpl *event); - void ScheduleAt (const uint32_t context, Time const &time, EventImpl *event); - void ScheduleWithContext (LogicalProcess *remote, const uint32_t context, Time const &delay, - EventImpl *event); - void InvokeNow (Scheduler::Event const &ev); // cross context immediate invocation - void Remove (const EventId &id); - void Cancel (const EventId &id); - bool IsExpired (const EventId &id) const; - void SetScheduler (ObjectFactory schedulerFactory); - Time Next () const; + // mapped from MultithreadedSimulatorImpl + EventId Schedule(const Time& delay, EventImpl* event); + void ScheduleAt(const uint32_t context, const Time& time, EventImpl* event); + void ScheduleWithContext(LogicalProcess* remote, + const uint32_t context, + const Time& delay, + EventImpl* event); + void InvokeNow(const Scheduler::Event& ev); // cross context immediate invocation + void Remove(const EventId& id); + void Cancel(const EventId& id); + bool IsExpired(const EventId& id) const; + void SetScheduler(ObjectFactory schedulerFactory); + Time Next() const; - inline bool - isLocalFinished () const - { - return m_stop || m_events->IsEmpty (); - } + inline bool isLocalFinished() const + { + return m_stop || m_events->IsEmpty(); + } - inline void - Stop () - { - m_stop = true; - } + inline void Stop() + { + m_stop = true; + } - inline Time - Now () const - { - return TimeStep (m_currentTs); - } + inline Time Now() const + { + return TimeStep(m_currentTs); + } - inline Time - GetDelayLeft (const EventId &id) const - { - return TimeStep (id.GetTs () - m_currentTs); - } + inline Time GetDelayLeft(const EventId& id) const + { + return TimeStep(id.GetTs() - m_currentTs); + } - inline uint32_t - GetSystemId (void) const - { - return m_systemId; - } + inline uint32_t GetSystemId(void) const + { + return m_systemId; + } - inline uint32_t - GetContext () const - { - return m_currentContext; - } + inline uint32_t GetContext() const + { + return m_currentContext; + } - inline uint64_t - GetEventCount () const - { - return m_eventCount; - } + inline uint64_t GetEventCount() const + { + return m_eventCount; + } -private: - uint32_t m_systemId; - uint32_t m_systemCount; - bool m_stop; - uint32_t m_uid; - uint32_t m_currentContext; - uint32_t m_currentUid; - uint64_t m_currentTs; - uint64_t m_eventCount; - uint64_t m_pendingEventCount; - Ptr m_events; - Time m_lookAhead; + private: + uint32_t m_systemId; + uint32_t m_systemCount; + bool m_stop; + uint32_t m_uid; + uint32_t m_currentContext; + uint32_t m_currentUid; + uint64_t m_currentTs; + uint64_t m_eventCount; + uint64_t m_pendingEventCount; + Ptr m_events; + Time m_lookAhead; - std::map>> - m_mailbox; // event message mail box - std::chrono::nanoseconds::rep m_executionTime; + std::map>> + m_mailbox; // event message mail box + std::chrono::nanoseconds::rep m_executionTime; }; } // namespace ns3 diff --git a/src/mtp/model/mtp-interface.cc b/src/mtp/model/mtp-interface.cc index 9c352686e..1c37b5eba 100644 --- a/src/mtp/model/mtp-interface.cc +++ b/src/mtp/model/mtp-interface.cc @@ -3,347 +3,351 @@ #include "mtp-interface.h" #include "ns3/assert.h" +#include "ns3/config.h" #include "ns3/log.h" #include "ns3/string.h" #include "ns3/uinteger.h" -#include "ns3/config.h" #include #include -namespace ns3 { +namespace ns3 +{ -NS_LOG_COMPONENT_DEFINE ("MtpInterface"); +NS_LOG_COMPONENT_DEFINE("MtpInterface"); void -MtpInterface::Enable () +MtpInterface::Enable() { #ifdef NS3_MPI - GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::HybridSimulatorImpl")); + GlobalValue::Bind("SimulatorImplementationType", StringValue("ns3::HybridSimulatorImpl")); #else - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::MultithreadedSimulatorImpl")); + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::MultithreadedSimulatorImpl")); #endif - g_enabled = true; + g_enabled = true; } void -MtpInterface::Enable (const uint32_t threadCount) +MtpInterface::Enable(const uint32_t threadCount) { #ifdef NS3_MPI - Config::SetDefault ("ns3::HybridSimulatorImpl::MaxThreads", UintegerValue (threadCount)); + Config::SetDefault("ns3::HybridSimulatorImpl::MaxThreads", UintegerValue(threadCount)); #else - Config::SetDefault ("ns3::MultithreadedSimulatorImpl::MaxThreads", UintegerValue (threadCount)); + Config::SetDefault("ns3::MultithreadedSimulatorImpl::MaxThreads", UintegerValue(threadCount)); #endif - MtpInterface::Enable (); + MtpInterface::Enable(); } void -MtpInterface::Enable (const uint32_t threadCount, const uint32_t systemCount) +MtpInterface::Enable(const uint32_t threadCount, const uint32_t systemCount) { - NS_ASSERT_MSG (threadCount > 0, "There must be at least one thread"); + NS_ASSERT_MSG(threadCount > 0, "There must be at least one thread"); - // called by manual partition - if (!g_enabled) + // called by manual partition + if (!g_enabled) { - GlobalValue::Bind ("SimulatorImplementationType", - StringValue ("ns3::MultithreadedSimulatorImpl")); + GlobalValue::Bind("SimulatorImplementationType", + StringValue("ns3::MultithreadedSimulatorImpl")); } - // set size - g_threadCount = threadCount; - g_systemCount = systemCount; + // set size + g_threadCount = threadCount; + g_systemCount = systemCount; - // allocate systems - g_systems = new LogicalProcess[g_systemCount + 1]; // include the public LP - for (uint32_t i = 0; i <= g_systemCount; i++) + // allocate systems + g_systems = new LogicalProcess[g_systemCount + 1]; // include the public LP + for (uint32_t i = 0; i <= g_systemCount; i++) { - g_systems[i].Enable (i, g_systemCount + 1); + g_systems[i].Enable(i, g_systemCount + 1); } - StringValue s; - g_sortMethod.GetValue (s); - if (s.Get () == "ByExecutionTime") + StringValue s; + g_sortMethod.GetValue(s); + if (s.Get() == "ByExecutionTime") { - g_sortFunc = SortByExecutionTime; + g_sortFunc = SortByExecutionTime; } - else if (s.Get () == "ByPendingEventCount") + else if (s.Get() == "ByPendingEventCount") { - g_sortFunc = SortByPendingEventCount; + g_sortFunc = SortByPendingEventCount; } - else if (s.Get () == "ByEventCount") + else if (s.Get() == "ByEventCount") { - g_sortFunc = SortByEventCount; + g_sortFunc = SortByEventCount; } - else if (s.Get () == "BySimulationTime") + else if (s.Get() == "BySimulationTime") { - g_sortFunc = SortBySimulationTime; + g_sortFunc = SortBySimulationTime; } - UintegerValue ui; - g_sortPeriod.GetValue (ui); - if (ui.Get () == 0) + UintegerValue ui; + g_sortPeriod.GetValue(ui); + if (ui.Get() == 0) { - g_period = std::ceil (std::log2 (g_systemCount) / 4 + 1); - NS_LOG_INFO ("Secheduling period is automatically set to " << g_period); + g_period = std::ceil(std::log2(g_systemCount) / 4 + 1); + NS_LOG_INFO("Secheduling period is automatically set to " << g_period); } - else + else { - g_period = ui.Get (); + g_period = ui.Get(); } - // create a thread local storage key - // so that we can access the currently assigned LP of each thread - pthread_key_create (&g_key, nullptr); - pthread_setspecific (g_key, &g_systems[0]); + // create a thread local storage key + // so that we can access the currently assigned LP of each thread + pthread_key_create(&g_key, nullptr); + pthread_setspecific(g_key, &g_systems[0]); } void -MtpInterface::EnableNew (const uint32_t newSystemCount) +MtpInterface::EnableNew(const uint32_t newSystemCount) { - const LogicalProcess *oldSystems = g_systems; - g_systems = new LogicalProcess[g_systemCount + newSystemCount + 1]; - for (uint32_t i = 0; i <= g_systemCount; i++) + const LogicalProcess* oldSystems = g_systems; + g_systems = new LogicalProcess[g_systemCount + newSystemCount + 1]; + for (uint32_t i = 0; i <= g_systemCount; i++) { - g_systems[i] = oldSystems[i]; + g_systems[i] = oldSystems[i]; } - delete[] oldSystems; + delete[] oldSystems; - g_systemCount += newSystemCount; - for (uint32_t i = 0; i <= g_systemCount; i++) + g_systemCount += newSystemCount; + for (uint32_t i = 0; i <= g_systemCount; i++) { - g_systems[i].Enable (i, g_systemCount + 1); + g_systems[i].Enable(i, g_systemCount + 1); } } void -MtpInterface::Disable () +MtpInterface::Disable() { - g_threadCount = 0; - g_systemCount = 0; - g_sortFunc = nullptr; - g_globalFinished = false; - delete[] g_systems; - delete[] g_threads; - delete[] g_sortedSystemIndices; + g_threadCount = 0; + g_systemCount = 0; + g_sortFunc = nullptr; + g_globalFinished = false; + delete[] g_systems; + delete[] g_threads; + delete[] g_sortedSystemIndices; } void -MtpInterface::Run () +MtpInterface::Run() { - RunBefore (); - while (!g_globalFinished) + RunBefore(); + while (!g_globalFinished) { - ProcessOneRound (); - CalculateSmallestTime (); + ProcessOneRound(); + CalculateSmallestTime(); } - RunAfter (); + RunAfter(); } void -MtpInterface::RunBefore () +MtpInterface::RunBefore() { - CalculateLookAhead (); + CalculateLookAhead(); - // LP index for sorting & holding worker threads - g_sortedSystemIndices = new uint32_t[g_systemCount]; - for (uint32_t i = 0; i < g_systemCount; i++) + // LP index for sorting & holding worker threads + g_sortedSystemIndices = new uint32_t[g_systemCount]; + for (uint32_t i = 0; i < g_systemCount; i++) { - g_sortedSystemIndices[i] = i + 1; + g_sortedSystemIndices[i] = i + 1; } - g_systemIndex.store (g_systemCount, std::memory_order_release); + g_systemIndex.store(g_systemCount, std::memory_order_release); - // start threads - g_threads = new pthread_t[g_threadCount - 1]; // exclude the main thread - for (uint32_t i = 0; i < g_threadCount - 1; i++) + // start threads + g_threads = new pthread_t[g_threadCount - 1]; // exclude the main thread + for (uint32_t i = 0; i < g_threadCount - 1; i++) { - pthread_create (&g_threads[i], nullptr, ThreadFunc, nullptr); + pthread_create(&g_threads[i], nullptr, ThreadFunc, nullptr); } } void -MtpInterface::ProcessOneRound () +MtpInterface::ProcessOneRound() { - // assign logical process to threads + // assign logical process to threads - // determine the priority of logical processes - if (g_sortFunc != nullptr && g_round++ % g_period == 0) + // determine the priority of logical processes + if (g_sortFunc != nullptr && g_round++ % g_period == 0) { - std::sort (g_sortedSystemIndices, g_sortedSystemIndices + g_systemCount, g_sortFunc); + std::sort(g_sortedSystemIndices, g_sortedSystemIndices + g_systemCount, g_sortFunc); } - // stage 1: process events - g_recvMsgStage = false; - g_finishedSystemCount.store (0, std::memory_order_relaxed); - g_systemIndex.store (0, std::memory_order_release); - // main thread also needs to process an LP to reduce an extra thread overhead - while (true) + // stage 1: process events + g_recvMsgStage = false; + g_finishedSystemCount.store(0, std::memory_order_relaxed); + g_systemIndex.store(0, std::memory_order_release); + // main thread also needs to process an LP to reduce an extra thread overhead + while (true) { - uint32_t index = g_systemIndex.fetch_add (1, std::memory_order_acquire); - if (index >= g_systemCount) + uint32_t index = g_systemIndex.fetch_add(1, std::memory_order_acquire); + if (index >= g_systemCount) { - break; + break; } - LogicalProcess *system = &g_systems[g_sortedSystemIndices[index]]; - system->ProcessOneRound (); - g_finishedSystemCount.fetch_add (1, std::memory_order_release); + LogicalProcess* system = &g_systems[g_sortedSystemIndices[index]]; + system->ProcessOneRound(); + g_finishedSystemCount.fetch_add(1, std::memory_order_release); } - // logical process barriar synchronization - while (g_finishedSystemCount.load (std::memory_order_acquire) != g_systemCount) - ; + // logical process barriar synchronization + while (g_finishedSystemCount.load(std::memory_order_acquire) != g_systemCount) + ; - // stage 2: process the public LP - g_systems[0].ProcessOneRound (); + // stage 2: process the public LP + g_systems[0].ProcessOneRound(); - // stage 3: receive messages - g_recvMsgStage = true; - g_finishedSystemCount.store (0, std::memory_order_relaxed); - g_systemIndex.store (0, std::memory_order_release); - while (true) + // stage 3: receive messages + g_recvMsgStage = true; + g_finishedSystemCount.store(0, std::memory_order_relaxed); + g_systemIndex.store(0, std::memory_order_release); + while (true) { - uint32_t index = g_systemIndex.fetch_add (1, std::memory_order_acquire); - if (index >= g_systemCount) + uint32_t index = g_systemIndex.fetch_add(1, std::memory_order_acquire); + if (index >= g_systemCount) { - break; + break; } - LogicalProcess *system = &g_systems[g_sortedSystemIndices[index]]; - system->ReceiveMessages (); - g_finishedSystemCount.fetch_add (1, std::memory_order_release); + LogicalProcess* system = &g_systems[g_sortedSystemIndices[index]]; + system->ReceiveMessages(); + g_finishedSystemCount.fetch_add(1, std::memory_order_release); } - // logical process barriar synchronization - while (g_finishedSystemCount.load (std::memory_order_acquire) != g_systemCount) - ; + // logical process barriar synchronization + while (g_finishedSystemCount.load(std::memory_order_acquire) != g_systemCount) + ; } void -MtpInterface::CalculateSmallestTime () +MtpInterface::CalculateSmallestTime() { - // update smallest time - g_smallestTime = Time::Max () / 2; - for (uint32_t i = 0; i <= g_systemCount; i++) + // update smallest time + g_smallestTime = Time::Max() / 2; + for (uint32_t i = 0; i <= g_systemCount; i++) { - Time nextTime = g_systems[i].Next (); - if (nextTime < g_smallestTime) + Time nextTime = g_systems[i].Next(); + if (nextTime < g_smallestTime) { - g_smallestTime = nextTime; + g_smallestTime = nextTime; } } - g_nextPublicTime = g_systems[0].Next (); + g_nextPublicTime = g_systems[0].Next(); - // test if global finished - bool globalFinished = true; - for (uint32_t i = 0; i <= g_systemCount; i++) + // test if global finished + bool globalFinished = true; + for (uint32_t i = 0; i <= g_systemCount; i++) { - globalFinished &= g_systems[i].isLocalFinished (); + globalFinished &= g_systems[i].isLocalFinished(); } - g_globalFinished = globalFinished; + g_globalFinished = globalFinished; } void -MtpInterface::RunAfter () +MtpInterface::RunAfter() { - // global finished, terminate threads - g_systemIndex.store (0, std::memory_order_release); - for (uint32_t i = 0; i < g_threadCount - 1; i++) + // global finished, terminate threads + g_systemIndex.store(0, std::memory_order_release); + for (uint32_t i = 0; i < g_threadCount - 1; i++) { - pthread_join (g_threads[i], nullptr); + pthread_join(g_threads[i], nullptr); } } bool -MtpInterface::isEnabled () +MtpInterface::isEnabled() { - return g_enabled; + return g_enabled; } bool -MtpInterface::isPartitioned () +MtpInterface::isPartitioned() { - return g_threadCount != 0; + return g_threadCount != 0; } void -MtpInterface::CalculateLookAhead () +MtpInterface::CalculateLookAhead() { - for (uint32_t i = 1; i <= g_systemCount; i++) + for (uint32_t i = 1; i <= g_systemCount; i++) { - g_systems[i].CalculateLookAhead (); + g_systems[i].CalculateLookAhead(); } } -void * -MtpInterface::ThreadFunc (void *arg) +void* +MtpInterface::ThreadFunc(void* arg) { - while (!g_globalFinished) + while (!g_globalFinished) { - uint32_t index = g_systemIndex.fetch_add (1, std::memory_order_acquire); - if (index >= g_systemCount) + uint32_t index = g_systemIndex.fetch_add(1, std::memory_order_acquire); + if (index >= g_systemCount) { - while (g_systemIndex.load (std::memory_order_acquire) >= g_systemCount) - ; - continue; + while (g_systemIndex.load(std::memory_order_acquire) >= g_systemCount) + ; + continue; } - LogicalProcess *system = &g_systems[g_sortedSystemIndices[index]]; - if (g_recvMsgStage) + LogicalProcess* system = &g_systems[g_sortedSystemIndices[index]]; + if (g_recvMsgStage) { - system->ReceiveMessages (); + system->ReceiveMessages(); } - else + else { - system->ProcessOneRound (); + system->ProcessOneRound(); } - g_finishedSystemCount.fetch_add (1, std::memory_order_release); + g_finishedSystemCount.fetch_add(1, std::memory_order_release); } - return nullptr; + return nullptr; } bool -MtpInterface::SortByExecutionTime (const uint32_t &i, const uint32_t &j) +MtpInterface::SortByExecutionTime(const uint32_t& i, const uint32_t& j) { - return g_systems[i].GetExecutionTime () > g_systems[j].GetExecutionTime (); + return g_systems[i].GetExecutionTime() > g_systems[j].GetExecutionTime(); } bool -MtpInterface::SortByEventCount (const uint32_t &i, const uint32_t &j) +MtpInterface::SortByEventCount(const uint32_t& i, const uint32_t& j) { - return g_systems[i].GetEventCount () > g_systems[j].GetEventCount (); + return g_systems[i].GetEventCount() > g_systems[j].GetEventCount(); } bool -MtpInterface::SortByPendingEventCount (const uint32_t &i, const uint32_t &j) +MtpInterface::SortByPendingEventCount(const uint32_t& i, const uint32_t& j) { - return g_systems[i].GetPendingEventCount () > g_systems[j].GetPendingEventCount (); + return g_systems[i].GetPendingEventCount() > g_systems[j].GetPendingEventCount(); } bool -MtpInterface::SortBySimulationTime (const uint32_t &i, const uint32_t &j) +MtpInterface::SortBySimulationTime(const uint32_t& i, const uint32_t& j) { - return g_systems[i].Now () > g_systems[j].Now (); + return g_systems[i].Now() > g_systems[j].Now(); } -bool (*MtpInterface::g_sortFunc) (const uint32_t &, const uint32_t &) = nullptr; +bool (*MtpInterface::g_sortFunc)(const uint32_t&, const uint32_t&) = nullptr; -GlobalValue MtpInterface::g_sortMethod = GlobalValue ( - "PartitionSchedulingMethod", "The scheduling method to determine which partition runs first", - StringValue ("ByExecutionTime"), MakeStringChecker ()); +GlobalValue MtpInterface::g_sortMethod = + GlobalValue("PartitionSchedulingMethod", + "The scheduling method to determine which partition runs first", + StringValue("ByExecutionTime"), + MakeStringChecker()); -GlobalValue MtpInterface::g_sortPeriod = - GlobalValue ("PartitionSchedulingPeriod", "The scheduling period of partitions", - UintegerValue (0), MakeUintegerChecker (0)); +GlobalValue MtpInterface::g_sortPeriod = GlobalValue("PartitionSchedulingPeriod", + "The scheduling period of partitions", + UintegerValue(0), + MakeUintegerChecker(0)); uint32_t MtpInterface::g_period = 0; -pthread_t *MtpInterface::g_threads = nullptr; +pthread_t* MtpInterface::g_threads = nullptr; -LogicalProcess *MtpInterface::g_systems = nullptr; +LogicalProcess* MtpInterface::g_systems = nullptr; uint32_t MtpInterface::g_threadCount = 0; uint32_t MtpInterface::g_systemCount = 0; -uint32_t *MtpInterface::g_sortedSystemIndices = nullptr; +uint32_t* MtpInterface::g_sortedSystemIndices = nullptr; std::atomic MtpInterface::g_systemIndex; @@ -351,9 +355,9 @@ std::atomic MtpInterface::g_finishedSystemCount; uint32_t MtpInterface::g_round = 0; -Time MtpInterface::g_smallestTime = TimeStep (0); +Time MtpInterface::g_smallestTime = TimeStep(0); -Time MtpInterface::g_nextPublicTime = TimeStep (0); +Time MtpInterface::g_nextPublicTime = TimeStep(0); bool MtpInterface::g_recvMsgStage = false; @@ -363,6 +367,6 @@ bool MtpInterface::g_enabled = false; pthread_key_t MtpInterface::g_key; -std::atomic MtpInterface::g_inCriticalSection (false); +std::atomic MtpInterface::g_inCriticalSection(false); } // namespace ns3 diff --git a/src/mtp/model/mtp-interface.h b/src/mtp/model/mtp-interface.h index 1367eca56..a557295fa 100644 --- a/src/mtp/model/mtp-interface.h +++ b/src/mtp/model/mtp-interface.h @@ -3,6 +3,7 @@ #define MTP_INTERFACE_H #include "logical-process.h" + #include "ns3/atomic-counter.h" #include "ns3/global-value.h" #include "ns3/nstime.h" @@ -10,149 +11,142 @@ #include -namespace ns3 { +namespace ns3 +{ class MtpInterface { -public: - class CriticalSection - { public: - inline CriticalSection () + class CriticalSection { - while (g_inCriticalSection.exchange (true, std::memory_order_acquire)) - ; + public: + inline CriticalSection() + { + while (g_inCriticalSection.exchange(true, std::memory_order_acquire)) + ; + } + + inline ~CriticalSection() + { + g_inCriticalSection.store(false, std::memory_order_release); + } + }; + + static void Enable(); // auto topology partition + static void Enable(const uint32_t threadCount); // auto partition, specify thread count + static void Enable(const uint32_t threadCount, const uint32_t systemCount); // manual partition + static void EnableNew(const uint32_t newSystemCount); // add LPs for dynamic added node + static void Disable(); + static void Run(); + static void RunBefore(); + static void ProcessOneRound(); + static void CalculateSmallestTime(); + static void RunAfter(); + static bool isEnabled(); + static bool isPartitioned(); + static void CalculateLookAhead(); + + // get current thread's executing logical process + inline static LogicalProcess* GetSystem() + { + return static_cast(pthread_getspecific(g_key)); } - inline ~CriticalSection () + inline static LogicalProcess* GetSystem(const uint32_t systemId) { - g_inCriticalSection.store (false, std::memory_order_release); + return &g_systems[systemId]; } - }; - static void Enable (); // auto topology partition - static void Enable (const uint32_t threadCount); // auto partition, specify thread count - static void Enable (const uint32_t threadCount, const uint32_t systemCount); // manual partition - static void EnableNew (const uint32_t newSystemCount); // add LPs for dynamic added node - static void Disable (); - static void Run (); - static void RunBefore (); - static void ProcessOneRound (); - static void CalculateSmallestTime (); - static void RunAfter (); - static bool isEnabled (); - static bool isPartitioned (); - static void CalculateLookAhead (); + // set current thread's executing logical process + inline static void SetSystem(const uint32_t systemId) + { + pthread_setspecific(g_key, &g_systems[systemId]); + } - // get current thread's executing logical process - inline static LogicalProcess * - GetSystem () - { - return static_cast (pthread_getspecific (g_key)); - } + inline static uint32_t GetSize() + { + return g_systemCount + 1; + } - inline static LogicalProcess * - GetSystem (const uint32_t systemId) - { - return &g_systems[systemId]; - } + inline static uint32_t GetRound() + { + return g_round; + } - // set current thread's executing logical process - inline static void - SetSystem (const uint32_t systemId) - { - pthread_setspecific (g_key, &g_systems[systemId]); - } + inline static Time GetSmallestTime() + { + return g_smallestTime; + } - inline static uint32_t - GetSize () - { - return g_systemCount + 1; - } + inline static void SetSmallestTime(const Time smallestTime) + { + g_smallestTime = smallestTime; + } - inline static uint32_t - GetRound () - { - return g_round; - } + inline static Time GetNextPublicTime() + { + return g_nextPublicTime; + } - inline static Time - GetSmallestTime () - { - return g_smallestTime; - } + inline static bool isFinished() + { + return g_globalFinished; + } - inline static void - SetSmallestTime (const Time smallestTime) - { - g_smallestTime = smallestTime; - } + template < + typename FUNC, + typename std::enable_if>::value, int>::type, + typename std::enable_if::type>::value, + int>::type, + typename... Ts> + inline static void ScheduleGlobal(FUNC f, Ts&&... args) + { + CriticalSection cs; + g_systems[0].ScheduleAt(Simulator::NO_CONTEXT, + Min(g_smallestTime, g_nextPublicTime), + MakeEvent(f, std::forward(args)...)); + } - inline static Time - GetNextPublicTime () - { - return g_nextPublicTime; - } + template + inline static void ScheduleGlobal(void (*f)(Us...), Ts&&... args) + { + CriticalSection cs; + g_systems[0].ScheduleAt(Simulator::NO_CONTEXT, + Min(g_smallestTime, g_nextPublicTime), + MakeEvent(f, std::forward(args)...)); + } - inline static bool - isFinished () - { - return g_globalFinished; - } + private: + static void* ThreadFunc(void* arg); - template >::value, int>::type, - typename std::enable_if< - !std::is_function::type>::value, int>::type, - typename... Ts> - inline static void - ScheduleGlobal (FUNC f, Ts &&...args) - { - CriticalSection cs; - g_systems[0].ScheduleAt (Simulator::NO_CONTEXT, Min (g_smallestTime, g_nextPublicTime), - MakeEvent (f, std::forward (args)...)); - } + // determine logical process priority + static bool SortByExecutionTime(const uint32_t& i, const uint32_t& j); + static bool SortByEventCount(const uint32_t& i, const uint32_t& j); + static bool SortByPendingEventCount(const uint32_t& i, const uint32_t& j); + static bool SortBySimulationTime(const uint32_t& i, const uint32_t& j); + static bool (*g_sortFunc)(const uint32_t&, const uint32_t&); + static GlobalValue g_sortMethod; + static GlobalValue g_sortPeriod; + static uint32_t g_period; - template - inline static void - ScheduleGlobal (void (*f) (Us...), Ts &&...args) - { - CriticalSection cs; - g_systems[0].ScheduleAt (Simulator::NO_CONTEXT, Min (g_smallestTime, g_nextPublicTime), - MakeEvent (f, std::forward (args)...)); - } + static pthread_t* g_threads; + static LogicalProcess* g_systems; + static uint32_t g_threadCount; + static uint32_t g_systemCount; -private: - static void *ThreadFunc (void *arg); + static uint32_t* g_sortedSystemIndices; + static std::atomic g_systemIndex; + static std::atomic g_finishedSystemCount; - // determine logical process priority - static bool SortByExecutionTime (const uint32_t &i, const uint32_t &j); - static bool SortByEventCount (const uint32_t &i, const uint32_t &j); - static bool SortByPendingEventCount (const uint32_t &i, const uint32_t &j); - static bool SortBySimulationTime (const uint32_t &i, const uint32_t &j); - static bool (*g_sortFunc) (const uint32_t &, const uint32_t &); - static GlobalValue g_sortMethod; - static GlobalValue g_sortPeriod; - static uint32_t g_period; + static uint32_t g_round; + static Time g_smallestTime; + static Time g_nextPublicTime; + static bool g_recvMsgStage; + static bool g_globalFinished; + static bool g_enabled; - static pthread_t *g_threads; - static LogicalProcess *g_systems; - static uint32_t g_threadCount; - static uint32_t g_systemCount; - - static uint32_t *g_sortedSystemIndices; - static std::atomic g_systemIndex; - static std::atomic g_finishedSystemCount; - - static uint32_t g_round; - static Time g_smallestTime; - static Time g_nextPublicTime; - static bool g_recvMsgStage; - static bool g_globalFinished; - static bool g_enabled; - - static pthread_key_t g_key; - static std::atomic g_inCriticalSection; + static pthread_key_t g_key; + static std::atomic g_inCriticalSection; }; } // namespace ns3 diff --git a/src/mtp/model/multithreaded-simulator-impl.cc b/src/mtp/model/multithreaded-simulator-impl.cc index 64658d455..c7164fac1 100644 --- a/src/mtp/model/multithreaded-simulator-impl.cc +++ b/src/mtp/model/multithreaded-simulator-impl.cc @@ -1,411 +1,420 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "multithreaded-simulator-impl.h" + #include "mtp-interface.h" -#include "ns3/type-id.h" #include "ns3/channel.h" -#include "ns3/simulator.h" -#include "ns3/node.h" #include "ns3/node-container.h" #include "ns3/node-list.h" +#include "ns3/node.h" +#include "ns3/simulator.h" +#include "ns3/type-id.h" #include "ns3/uinteger.h" #include #include #include -namespace ns3 { - -NS_LOG_COMPONENT_DEFINE ("MultithreadedSimulatorImpl"); - -NS_OBJECT_ENSURE_REGISTERED (MultithreadedSimulatorImpl); - -MultithreadedSimulatorImpl::MultithreadedSimulatorImpl () +namespace ns3 { - NS_LOG_FUNCTION (this); - if (!MtpInterface::isPartitioned ()) + +NS_LOG_COMPONENT_DEFINE("MultithreadedSimulatorImpl"); + +NS_OBJECT_ENSURE_REGISTERED(MultithreadedSimulatorImpl); + +MultithreadedSimulatorImpl::MultithreadedSimulatorImpl() +{ + NS_LOG_FUNCTION(this); + if (!MtpInterface::isPartitioned()) { - MtpInterface::Enable (1, 0); - m_partition = true; + MtpInterface::Enable(1, 0); + m_partition = true; } - else + else { - m_partition = false; + m_partition = false; } } -MultithreadedSimulatorImpl::~MultithreadedSimulatorImpl () +MultithreadedSimulatorImpl::~MultithreadedSimulatorImpl() { - NS_LOG_FUNCTION (this); + NS_LOG_FUNCTION(this); } TypeId -MultithreadedSimulatorImpl::GetTypeId () +MultithreadedSimulatorImpl::GetTypeId() { - static TypeId tid = - TypeId ("ns3::MultithreadedSimulatorImpl") - .SetParent () - .SetGroupName ("Mtp") - .AddConstructor () - .AddAttribute ("MaxThreads", "The maximum threads used in simulation", - UintegerValue (std::thread::hardware_concurrency ()), - MakeUintegerAccessor (&MultithreadedSimulatorImpl::m_maxThreads), - MakeUintegerChecker (1)) - .AddAttribute ("MinLookahead", "The minimum lookahead in a partition", - TimeValue (TimeStep (0)), - MakeTimeAccessor (&MultithreadedSimulatorImpl::m_minLookahead), - MakeTimeChecker (TimeStep (0))); - return tid; + static TypeId tid = + TypeId("ns3::MultithreadedSimulatorImpl") + .SetParent() + .SetGroupName("Mtp") + .AddConstructor() + .AddAttribute("MaxThreads", + "The maximum threads used in simulation", + UintegerValue(std::thread::hardware_concurrency()), + MakeUintegerAccessor(&MultithreadedSimulatorImpl::m_maxThreads), + MakeUintegerChecker(1)) + .AddAttribute("MinLookahead", + "The minimum lookahead in a partition", + TimeValue(TimeStep(0)), + MakeTimeAccessor(&MultithreadedSimulatorImpl::m_minLookahead), + MakeTimeChecker(TimeStep(0))); + return tid; } void -MultithreadedSimulatorImpl::Destroy () +MultithreadedSimulatorImpl::Destroy() { - while (!m_destroyEvents.empty ()) + while (!m_destroyEvents.empty()) { - Ptr ev = m_destroyEvents.front ().PeekEventImpl (); - m_destroyEvents.pop_front (); - NS_LOG_LOGIC ("handle destroy " << ev); - if (!ev->IsCancelled ()) + Ptr ev = m_destroyEvents.front().PeekEventImpl(); + m_destroyEvents.pop_front(); + NS_LOG_LOGIC("handle destroy " << ev); + if (!ev->IsCancelled()) { - ev->Invoke (); + ev->Invoke(); } } - MtpInterface::Disable (); + MtpInterface::Disable(); } bool -MultithreadedSimulatorImpl::IsFinished () const +MultithreadedSimulatorImpl::IsFinished() const { - return MtpInterface::isFinished (); + return MtpInterface::isFinished(); } void -MultithreadedSimulatorImpl::Stop () +MultithreadedSimulatorImpl::Stop() { - NS_LOG_FUNCTION (this); - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + NS_LOG_FUNCTION(this); + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - MtpInterface::GetSystem (i)->Stop (); + MtpInterface::GetSystem(i)->Stop(); } } void -MultithreadedSimulatorImpl::Stop (Time const &delay) +MultithreadedSimulatorImpl::Stop(const Time& delay) { - NS_LOG_FUNCTION (this << delay.GetTimeStep ()); - Simulator::Schedule (delay, &Simulator::Stop); + NS_LOG_FUNCTION(this << delay.GetTimeStep()); + Simulator::Schedule(delay, &Simulator::Stop); } EventId -MultithreadedSimulatorImpl::Schedule (Time const &delay, EventImpl *event) +MultithreadedSimulatorImpl::Schedule(const Time& delay, EventImpl* event) { - NS_LOG_FUNCTION (this << delay.GetTimeStep () << event); - return MtpInterface::GetSystem ()->Schedule (delay, event); + NS_LOG_FUNCTION(this << delay.GetTimeStep() << event); + return MtpInterface::GetSystem()->Schedule(delay, event); } void -MultithreadedSimulatorImpl::ScheduleWithContext (uint32_t context, Time const &delay, - EventImpl *event) +MultithreadedSimulatorImpl::ScheduleWithContext(uint32_t context, + const Time& delay, + EventImpl* event) { - NS_LOG_FUNCTION (this << context << delay.GetTimeStep () << event); - LogicalProcess *remote = MtpInterface::GetSystem (NodeList::GetNode (context)->GetSystemId ()); - MtpInterface::GetSystem ()->ScheduleWithContext (remote, context, delay, event); + NS_LOG_FUNCTION(this << context << delay.GetTimeStep() << event); + LogicalProcess* remote = MtpInterface::GetSystem(NodeList::GetNode(context)->GetSystemId()); + MtpInterface::GetSystem()->ScheduleWithContext(remote, context, delay, event); } EventId -MultithreadedSimulatorImpl::ScheduleNow (EventImpl *event) +MultithreadedSimulatorImpl::ScheduleNow(EventImpl* event) { - return Schedule (TimeStep (0), event); + return Schedule(TimeStep(0), event); } EventId -MultithreadedSimulatorImpl::ScheduleDestroy (EventImpl *event) +MultithreadedSimulatorImpl::ScheduleDestroy(EventImpl* event) { - EventId id (Ptr (event, false), GetMaximumSimulationTime ().GetTimeStep (), 0xffffffff, - EventId::DESTROY); - MtpInterface::CriticalSection cs; - m_destroyEvents.push_back (id); - return id; + EventId id(Ptr(event, false), + GetMaximumSimulationTime().GetTimeStep(), + 0xffffffff, + EventId::DESTROY); + MtpInterface::CriticalSection cs; + m_destroyEvents.push_back(id); + return id; } void -MultithreadedSimulatorImpl::Remove (const EventId &id) +MultithreadedSimulatorImpl::Remove(const EventId& id) { - if (id.GetUid () == EventId::DESTROY) + if (id.GetUid() == EventId::DESTROY) { - // destroy events. - for (std::list::iterator i = m_destroyEvents.begin (); i != m_destroyEvents.end (); - i++) + // destroy events. + for (std::list::iterator i = m_destroyEvents.begin(); i != m_destroyEvents.end(); + i++) { - if (*i == id) + if (*i == id) { - m_destroyEvents.erase (i); - break; + m_destroyEvents.erase(i); + break; } } } - else + else { - MtpInterface::GetSystem ()->Remove (id); + MtpInterface::GetSystem()->Remove(id); } } void -MultithreadedSimulatorImpl::Cancel (const EventId &id) +MultithreadedSimulatorImpl::Cancel(const EventId& id) { - if (!IsExpired (id)) + if (!IsExpired(id)) { - id.PeekEventImpl ()->Cancel (); + id.PeekEventImpl()->Cancel(); } } bool -MultithreadedSimulatorImpl::IsExpired (const EventId &id) const +MultithreadedSimulatorImpl::IsExpired(const EventId& id) const { - if (id.GetUid () == EventId::DESTROY) + if (id.GetUid() == EventId::DESTROY) { - // destroy events. - if (id.PeekEventImpl () == nullptr || id.PeekEventImpl ()->IsCancelled ()) + // destroy events. + if (id.PeekEventImpl() == nullptr || id.PeekEventImpl()->IsCancelled()) { - return true; + return true; } - for (std::list::const_iterator i = m_destroyEvents.begin (); - i != m_destroyEvents.end (); i++) + for (std::list::const_iterator i = m_destroyEvents.begin(); + i != m_destroyEvents.end(); + i++) { - if (*i == id) + if (*i == id) { - return false; + return false; } } - return true; + return true; } - else + else { - return MtpInterface::GetSystem ()->IsExpired (id); + return MtpInterface::GetSystem()->IsExpired(id); } } void -MultithreadedSimulatorImpl::Run () +MultithreadedSimulatorImpl::Run() { - NS_LOG_FUNCTION (this); - // auto partition - if (m_partition) + NS_LOG_FUNCTION(this); + // auto partition + if (m_partition) { - Partition (); + Partition(); } - MtpInterface::Run (); + MtpInterface::Run(); } Time -MultithreadedSimulatorImpl::Now (void) const +MultithreadedSimulatorImpl::Now(void) const { - // Do not add function logging here, to avoid stack overflow - return MtpInterface::GetSystem ()->Now (); + // Do not add function logging here, to avoid stack overflow + return MtpInterface::GetSystem()->Now(); } Time -MultithreadedSimulatorImpl::GetDelayLeft (const EventId &id) const +MultithreadedSimulatorImpl::GetDelayLeft(const EventId& id) const { - if (IsExpired (id)) + if (IsExpired(id)) { - return TimeStep (0); + return TimeStep(0); } - else + else { - return MtpInterface::GetSystem ()->GetDelayLeft (id); + return MtpInterface::GetSystem()->GetDelayLeft(id); } } Time -MultithreadedSimulatorImpl::GetMaximumSimulationTime (void) const +MultithreadedSimulatorImpl::GetMaximumSimulationTime(void) const { - return Time::Max () / 2; + return Time::Max() / 2; } void -MultithreadedSimulatorImpl::SetScheduler (ObjectFactory schedulerFactory) +MultithreadedSimulatorImpl::SetScheduler(ObjectFactory schedulerFactory) { - NS_LOG_FUNCTION (this << schedulerFactory); - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + NS_LOG_FUNCTION(this << schedulerFactory); + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - MtpInterface::GetSystem (i)->SetScheduler (schedulerFactory); + MtpInterface::GetSystem(i)->SetScheduler(schedulerFactory); } - m_schedulerTypeId = schedulerFactory.GetTypeId (); + m_schedulerTypeId = schedulerFactory.GetTypeId(); } uint32_t -MultithreadedSimulatorImpl::GetSystemId (void) const +MultithreadedSimulatorImpl::GetSystemId(void) const { - return MtpInterface::GetSystem ()->GetSystemId (); + return MtpInterface::GetSystem()->GetSystemId(); } uint32_t -MultithreadedSimulatorImpl::GetContext () const +MultithreadedSimulatorImpl::GetContext() const { - return MtpInterface::GetSystem ()->GetContext (); + return MtpInterface::GetSystem()->GetContext(); } uint64_t -MultithreadedSimulatorImpl::GetEventCount (void) const +MultithreadedSimulatorImpl::GetEventCount(void) const { - uint64_t eventCount = 0; - for (uint32_t i = 0; i < MtpInterface::GetSize (); i++) + uint64_t eventCount = 0; + for (uint32_t i = 0; i < MtpInterface::GetSize(); i++) { - eventCount += MtpInterface::GetSystem (i)->GetEventCount (); + eventCount += MtpInterface::GetSystem(i)->GetEventCount(); } - return eventCount; + return eventCount; } void -MultithreadedSimulatorImpl::DoDispose () +MultithreadedSimulatorImpl::DoDispose() { - SimulatorImpl::DoDispose (); + SimulatorImpl::DoDispose(); } void -MultithreadedSimulatorImpl::Partition () +MultithreadedSimulatorImpl::Partition() { - NS_LOG_FUNCTION (this); - uint32_t systemId = 0; - const NodeContainer nodes = NodeContainer::GetGlobal (); - bool *visited = new bool[nodes.GetN ()]{false}; - std::queue> q; + NS_LOG_FUNCTION(this); + uint32_t systemId = 0; + const NodeContainer nodes = NodeContainer::GetGlobal(); + bool* visited = new bool[nodes.GetN()]{false}; + std::queue> q; - // if m_minLookahead is not set, calculate the median of delay for every link - if (m_minLookahead == TimeStep (0)) + // if m_minLookahead is not set, calculate the median of delay for every link + if (m_minLookahead == TimeStep(0)) { - std::vector