NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
lp-reliability.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2022, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
26 #include "lp-reliability.hpp"
27 #include "generic-link-service.hpp"
28 #include "transport.hpp"
29 #include "common/global.hpp"
30 
31 namespace nfd {
32 namespace face {
33 
35 
37  : m_options(options)
38  , m_linkService(linkService)
39  , m_firstUnackedFrag(m_unackedFrags.begin())
40  , m_lastTxSeqNo(-1) // set to "-1" to start TxSequence numbers at 0
41 {
42  BOOST_ASSERT(m_linkService != nullptr);
43  BOOST_ASSERT(m_options.idleAckTimerPeriod > 0_ns);
44 }
45 
46 void
48 {
49  BOOST_ASSERT(options.idleAckTimerPeriod > 0_ns);
50 
51  if (m_options.isEnabled && !options.isEnabled) {
53  }
54 
55  m_options = options;
56 }
57 
58 const GenericLinkService*
60 {
61  return m_linkService;
62 }
63 
64 void
65 LpReliability::handleOutgoing(std::vector<lp::Packet>& frags, lp::Packet&& pkt, bool isInterest)
66 {
67  BOOST_ASSERT(m_options.isEnabled);
68 
69  auto unackedFragsIt = m_unackedFrags.begin();
71 
72  auto netPkt = make_shared<NetPkt>(std::move(pkt), isInterest);
73  netPkt->unackedFrags.reserve(frags.size());
74 
75  for (lp::Packet& frag : frags) {
76  // Non-IDLE packets are required to have assigned Sequence numbers with LpReliability enabled
77  BOOST_ASSERT(frag.has<lp::SequenceField>());
78 
79  // Assign TxSequence number
80  lp::Sequence txSeq = assignTxSequence(frag);
81 
82  // Store LpPacket for future retransmissions
83  unackedFragsIt = m_unackedFrags.emplace_hint(unackedFragsIt,
84  std::piecewise_construct,
85  std::forward_as_tuple(txSeq),
86  std::forward_as_tuple(frag));
87  unackedFragsIt->second.sendTime = sendTime;
88  auto rto = m_rttEst.getEstimatedRto();
89  lp::Sequence seq = frag.get<lp::SequenceField>();
90  NFD_LOG_FACE_TRACE("transmitting seq=" << seq << ", txseq=" << txSeq << ", rto=" <<
91  time::duration_cast<time::milliseconds>(rto).count() << "ms");
92  unackedFragsIt->second.rtoTimer = getScheduler().schedule(rto, [=] {
93  onLpPacketLost(txSeq, true);
94  });
95  unackedFragsIt->second.netPkt = netPkt;
96 
97  if (m_unackedFrags.size() == 1) {
99  }
100 
101  // Add to associated NetPkt
102  netPkt->unackedFrags.push_back(unackedFragsIt);
103  }
104 }
105 
106 bool
108 {
109  BOOST_ASSERT(m_options.isEnabled);
110 
111  bool isDuplicate = false;
112  auto now = time::steady_clock::now();
113 
114  // Extract and parse Acks
115  for (lp::Sequence ackTxSeq : pkt.list<lp::AckField>()) {
116  auto fragIt = m_unackedFrags.find(ackTxSeq);
117  if (fragIt == m_unackedFrags.end()) {
118  // Ignore an Ack for an unknown TxSequence number
119  NFD_LOG_FACE_DEBUG("received ack for unknown txseq=" << ackTxSeq);
120  continue;
121  }
122  auto& frag = fragIt->second;
123 
124  // Cancel the RTO timer for the acknowledged fragment
125  frag.rtoTimer.cancel();
126 
127  if (frag.retxCount == 0) {
128  NFD_LOG_FACE_TRACE("received ack for seq=" << frag.pkt.get<lp::SequenceField>() << ", txseq=" <<
129  ackTxSeq << ", retx=0, rtt=" <<
130  time::duration_cast<time::milliseconds>(now - frag.sendTime).count() << "ms");
131  // This sequence had no retransmissions, so use it to estimate the RTO
132  m_rttEst.addMeasurement(now - frag.sendTime);
133  }
134  else {
135  NFD_LOG_FACE_TRACE("received ack for seq=" << frag.pkt.get<lp::SequenceField>() << ", txseq=" <<
136  ackTxSeq << ", retx=" << frag.retxCount);
137  }
138 
139  // Look for frags with TxSequence numbers < ackTxSeq (allowing for wraparound) and consider
140  // them lost if a configurable number of Acks containing greater TxSequence numbers have been
141  // received.
142  auto lostLpPackets = findLostLpPackets(fragIt);
143 
144  // Remove the fragment from the map of unacknowledged fragments and from its associated network
145  // packet. Potentially increment the start of the window.
146  onLpPacketAcknowledged(fragIt);
147 
148  // This set contains TxSequences that have been removed by onLpPacketLost below because they
149  // were part of a network packet that was removed due to a fragment exceeding retx, as well as
150  // any other TxSequences removed by onLpPacketLost. This prevents onLpPacketLost from being
151  // called later for an invalid iterator.
152  std::set<lp::Sequence> removedLpPackets;
153 
154  // Resend or fail fragments considered lost. Potentially increment the start of the window.
155  for (lp::Sequence txSeq : lostLpPackets) {
156  if (removedLpPackets.find(txSeq) == removedLpPackets.end()) {
157  auto removedTxSeqs = onLpPacketLost(txSeq, false);
158  for (auto removedTxSeq : removedTxSeqs) {
159  removedLpPackets.insert(removedTxSeq);
160  }
161  }
162  }
163  }
164 
165  // If packet has Fragment and TxSequence fields, extract TxSequence and add to AckQueue
166  if (pkt.has<lp::FragmentField>() && pkt.has<lp::TxSequenceField>()) {
167  NFD_LOG_FACE_TRACE("queueing ack for remote txseq=" << pkt.get<lp::TxSequenceField>());
168  m_ackQueue.push(pkt.get<lp::TxSequenceField>());
169 
170  // Check for received frames with duplicate Sequences
171  if (pkt.has<lp::SequenceField>()) {
172  lp::Sequence pktSequence = pkt.get<lp::SequenceField>();
173  isDuplicate = m_recentRecvSeqs.count(pktSequence) > 0;
174  // Check for recent received Sequences to remove
175  auto now = time::steady_clock::now();
176  auto rto = m_rttEst.getEstimatedRto();
177  while (!m_recentRecvSeqsQueue.empty() &&
178  now > m_recentRecvSeqs[m_recentRecvSeqsQueue.front()] + rto) {
180  m_recentRecvSeqsQueue.pop();
181  }
182  m_recentRecvSeqs.emplace(pktSequence, now);
183  m_recentRecvSeqsQueue.push(pktSequence);
184  }
185 
187  }
188 
189  return !isDuplicate;
190 }
191 
192 void
194 {
195  BOOST_ASSERT(m_options.isEnabled);
196  BOOST_ASSERT(pkt.wireEncode().type() == lp::tlv::LpPacket);
197 
198  // up to 2 extra octets reserved for potential TLV-LENGTH size increases
199  ssize_t pktSize = pkt.wireEncode().size();
200  ssize_t reservedSpace = tlv::sizeOfVarNumber(ndn::MAX_NDN_PACKET_SIZE) -
201  tlv::sizeOfVarNumber(pktSize);
202  ssize_t remainingSpace = (mtu == MTU_UNLIMITED ? ndn::MAX_NDN_PACKET_SIZE : mtu) - reservedSpace;
203  remainingSpace -= pktSize;
204 
205  while (!m_ackQueue.empty()) {
206  lp::Sequence ackTxSeq = m_ackQueue.front();
207  // Ack size = Ack TLV-TYPE (3 octets) + TLV-LENGTH (1 octet) + lp::Sequence (8 octets)
208  const ssize_t ackSize = tlv::sizeOfVarNumber(lp::tlv::Ack) +
210  sizeof(lp::Sequence);
211 
212  if (ackSize > remainingSpace) {
213  break;
214  }
215 
216  NFD_LOG_FACE_TRACE("piggybacking ack for remote txseq=" << ackTxSeq);
217 
218  pkt.add<lp::AckField>(ackTxSeq);
219  m_ackQueue.pop();
220  remainingSpace -= ackSize;
221  }
222 }
223 
225 LpReliability::assignTxSequence(lp::Packet& frag)
226 {
227  lp::Sequence txSeq = ++m_lastTxSeqNo;
228  frag.set<lp::TxSequenceField>(txSeq);
229  if (!m_unackedFrags.empty() && m_lastTxSeqNo == m_firstUnackedFrag->first) {
230  NDN_THROW(std::length_error("TxSequence range exceeded"));
231  }
232  return m_lastTxSeqNo;
233 }
234 
235 void
237 {
238  if (m_idleAckTimer) {
239  // timer is already running, do nothing
240  return;
241  }
242 
243  m_idleAckTimer = getScheduler().schedule(m_options.idleAckTimerPeriod, [this] {
244  while (!m_ackQueue.empty()) {
245  m_linkService->requestIdlePacket();
246  }
247  });
248 }
249 
250 std::vector<lp::Sequence>
251 LpReliability::findLostLpPackets(LpReliability::UnackedFrags::iterator ackIt)
252 {
253  std::vector<lp::Sequence> lostLpPackets;
254 
255  for (auto it = m_firstUnackedFrag; ; ++it) {
256  if (it == m_unackedFrags.end()) {
257  it = m_unackedFrags.begin();
258  }
259 
260  if (it->first == ackIt->first) {
261  break;
262  }
263 
264  auto& unackedFrag = it->second;
265  unackedFrag.nGreaterSeqAcks++;
266  NFD_LOG_FACE_TRACE("received ack=" << ackIt->first << " before=" << it->first <<
267  ", before count=" << unackedFrag.nGreaterSeqAcks);
268 
269  if (unackedFrag.nGreaterSeqAcks >= m_options.seqNumLossThreshold) {
270  lostLpPackets.push_back(it->first);
271  }
272  }
273 
274  return lostLpPackets;
275 }
276 
277 std::vector<lp::Sequence>
279 {
280  BOOST_ASSERT(m_unackedFrags.count(txSeq) > 0);
281  auto txSeqIt = m_unackedFrags.find(txSeq);
282 
283  auto& txFrag = txSeqIt->second;
284  txFrag.rtoTimer.cancel();
285  auto netPkt = txFrag.netPkt;
286  std::vector<lp::Sequence> removedThisTxSeq;
287  lp::Sequence seq = txFrag.pkt.get<lp::SequenceField>();
288 
289  if (isTimeout) {
290  NFD_LOG_FACE_TRACE("rto timer expired for seq=" << seq << ", txseq=" << txSeq);
291  }
292  else { // lost due to out-of-order TxSeqs
293  NFD_LOG_FACE_TRACE("seq=" << seq << ", txseq=" << txSeq <<
294  " considered lost from acks for more recent txseqs");
295  }
296 
297  // Check if maximum number of retransmissions exceeded
298  if (txFrag.retxCount >= m_options.maxRetx) {
299  NFD_LOG_FACE_DEBUG("seq=" << seq << " exceeded allowed retransmissions: DROP");
300  // Delete all LpPackets of NetPkt from m_unackedFrags (except this one)
301  for (size_t i = 0; i < netPkt->unackedFrags.size(); i++) {
302  if (netPkt->unackedFrags[i] != txSeqIt) {
303  removedThisTxSeq.push_back(netPkt->unackedFrags[i]->first);
304  deleteUnackedFrag(netPkt->unackedFrags[i]);
305  }
306  }
307 
308  ++m_linkService->nRetxExhausted;
309 
310  // Notify strategy of dropped Interest (if any)
311  if (netPkt->isInterest) {
312  BOOST_ASSERT(netPkt->pkt.has<lp::FragmentField>());
313  auto frag = netPkt->pkt.get<lp::FragmentField>();
314  onDroppedInterest(Interest(Block({frag.first, frag.second})));
315  }
316 
317  // Delete this LpPacket from m_unackedFrags
318  removedThisTxSeq.push_back(txSeqIt->first);
319  deleteUnackedFrag(txSeqIt);
320  }
321  else {
322  // Assign new TxSequence
323  lp::Sequence newTxSeq = assignTxSequence(txFrag.pkt);
324  netPkt->didRetx = true;
325 
326  // Move fragment to new TxSequence mapping
327  auto newTxFragIt = m_unackedFrags.emplace_hint(
328  m_firstUnackedFrag != m_unackedFrags.end() && m_firstUnackedFrag->first > newTxSeq
330  : m_unackedFrags.end(),
331  std::piecewise_construct,
332  std::forward_as_tuple(newTxSeq),
333  std::forward_as_tuple(txFrag.pkt));
334  auto& newTxFrag = newTxFragIt->second;
335  newTxFrag.retxCount = txFrag.retxCount + 1;
336  newTxFrag.netPkt = netPkt;
337 
338  // Update associated NetPkt
339  auto fragInNetPkt = std::find(netPkt->unackedFrags.begin(), netPkt->unackedFrags.end(), txSeqIt);
340  BOOST_ASSERT(fragInNetPkt != netPkt->unackedFrags.end());
341  *fragInNetPkt = newTxFragIt;
342 
343  removedThisTxSeq.push_back(txSeqIt->first);
344  deleteUnackedFrag(txSeqIt);
345 
346  // Retransmit fragment
347  m_linkService->sendLpPacket(lp::Packet(newTxFrag.pkt));
348 
349  auto rto = m_rttEst.getEstimatedRto();
350  NFD_LOG_FACE_TRACE("retransmitting seq=" << seq << ", txseq=" << newTxSeq << ", retx=" <<
351  txFrag.retxCount << ", rto=" <<
352  time::duration_cast<time::milliseconds>(rto).count() << "ms");
353 
354  // Start RTO timer for this sequence
355  newTxFrag.rtoTimer = getScheduler().schedule(rto, [=] {
356  onLpPacketLost(newTxSeq, true);
357  });
358  }
359 
360  return removedThisTxSeq;
361 }
362 
363 void
364 LpReliability::onLpPacketAcknowledged(UnackedFrags::iterator fragIt)
365 {
366  auto netPkt = fragIt->second.netPkt;
367 
368  // Remove from NetPkt unacked fragment list
369  auto fragInNetPkt = std::find(netPkt->unackedFrags.begin(), netPkt->unackedFrags.end(), fragIt);
370  BOOST_ASSERT(fragInNetPkt != netPkt->unackedFrags.end());
371  *fragInNetPkt = netPkt->unackedFrags.back();
372  netPkt->unackedFrags.pop_back();
373 
374  // Check if network-layer packet completely received. If so, increment counters
375  if (netPkt->unackedFrags.empty()) {
376  if (netPkt->didRetx) {
377  ++m_linkService->nRetransmitted;
378  }
379  else {
380  ++m_linkService->nAcknowledged;
381  }
382  }
383 
384  deleteUnackedFrag(fragIt);
385 }
386 
387 void
388 LpReliability::deleteUnackedFrag(UnackedFrags::iterator fragIt)
389 {
390  lp::Sequence firstUnackedTxSeq = m_firstUnackedFrag->first;
391  lp::Sequence currentTxSeq = fragIt->first;
392  auto nextFragIt = m_unackedFrags.erase(fragIt);
393 
394  if (!m_unackedFrags.empty() && firstUnackedTxSeq == currentTxSeq) {
395  // If "first" fragment in send window (allowing for wraparound), increment window begin
396  if (nextFragIt == m_unackedFrags.end()) {
398  }
399  else {
400  m_firstUnackedFrag = nextFragIt;
401  }
402  }
403  else if (m_unackedFrags.empty()) {
405  }
406 }
407 
408 LpReliability::UnackedFrag::UnackedFrag(lp::Packet pkt)
409  : pkt(std::move(pkt))
411  , retxCount(0)
412  , nGreaterSeqAcks(0)
413 {
414 }
415 
417  : pkt(std::move(pkt))
418  , isInterest(isInterest)
419  , didRetx(false)
420 {
421 }
422 
423 std::ostream&
424 operator<<(std::ostream& os, const FaceLogHelper<LpReliability>& flh)
425 {
426  if (flh.obj.getLinkService() == nullptr) {
427  os << "[id=0,local=unknown,remote=unknown] ";
428  }
429  else {
430  os << FaceLogHelper<LinkService>(*flh.obj.getLinkService());
431  }
432  return os;
433 }
434 
435 } // namespace face
436 } // namespace nfd
NDN_CXX_NODISCARD bool has() const
Definition: packet.hpp:74
ndn::util::RttEstimator m_rttEst
void setOptions(const Options &options)
set options for reliability
time::nanoseconds getEstimatedRto() const
Returns the estimated RTO value.
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
Packet & set(const typename FIELD::ValueType &value)
remove all occurrences of FIELD, and add a FIELD with value
Definition: packet.hpp:136
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:91
static time_point now() noexcept
Definition: time.cpp:80
void piggyback(lp::Packet &pkt, ssize_t mtu)
called by GenericLinkService to attach Acks onto an outgoing LpPacket
Packet & add(const typename FIELD::ValueType &value)
add a FIELD with value
Definition: packet.hpp:148
void handleOutgoing(std::vector< lp::Packet > &frags, lp::Packet &&pkt, bool isInterest)
observe outgoing fragment(s) of a network packet and store for potential retransmission ...
void addMeasurement(time::nanoseconds rtt, size_t nExpectedSamples=1)
Records a new RTT measurement.
std::vector< lp::Sequence > onLpPacketLost(lp::Sequence txSeq, bool isTimeout)
resend (or give up on) a lost fragment
STL namespace.
void startIdleAckTimer()
start the idle Ack timer
Represents a TLV element of the NDN packet format.
Definition: block.hpp:44
std::vector< lp::Sequence > findLostLpPackets(UnackedFrags::iterator ackIt)
find and mark as lost fragments where a configurable number of Acks (m_options.seqNumLossThreshold) h...
UnackedFrags::iterator m_firstUnackedFrag
An iterator that points to the first unacknowledged fragment in the current window.
bool isEnabled
enables link-layer reliability
uint64_t Sequence
represents a sequence number
Definition: sequence.hpp:35
std::queue< lp::Sequence > m_ackQueue
#define NDN_THROW(e)
Definition: exception.hpp:61
Scheduler & getScheduler()
Returns the global Scheduler instance for the calling thread.
Definition: global.cpp:70
Declare a field.
Definition: field-decl.hpp:176
std::map< lp::Sequence, time::steady_clock::TimePoint > m_recentRecvSeqs
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
scheduler::ScopedEventId m_idleAckTimer
size_t size() const
Return the size of the encoded wire, i.e., of the whole TLV.
Definition: block.cpp:294
FIELD::ValueType get(size_t index=0) const
Definition: packet.hpp:96
constexpr size_t sizeOfVarNumber(uint64_t number) noexcept
Get the number of bytes necessary to hold the value of number encoded as VAR-NUMBER.
Definition: tlv.hpp:454
Copyright (c) 2011-2015 Regents of the University of California.
Definition: ndn-common.hpp:39
const GenericLinkService * getLinkService() const
shared_ptr< NetPkt > netPkt
LpReliability(const Options &options, GenericLinkService *linkService)
void deleteUnackedFrag(UnackedFrags::iterator fragIt)
delete a fragment from UnackedFrags and advance acknowledge window if necessary
time::steady_clock::TimePoint sendTime
uint32_t type() const noexcept
Return the TLV-TYPE of the Block.
Definition: block.hpp:277
NetPkt(lp::Packet &&pkt, bool isInterest)
bool processIncomingPacket(const lp::Packet &pkt)
extract and parse all Acks and add Ack for contained Fragment (if any) to AckQueue ...
void cancel()
Cancel the operation.
Block wireEncode() const
encode packet into wire format
Definition: packet.cpp:119
signal::Signal< LpReliability, Interest > onDroppedInterest
signals on Interest dropped by reliability system for exceeding allowed number of retx ...
GenericLinkService * m_linkService
std::queue< lp::Sequence > m_recentRecvSeqsQueue
NDN_CXX_NODISCARD std::vector< typename FIELD::ValueType > list() const
Definition: packet.hpp:116
time::nanoseconds idleAckTimerPeriod
period between sending pending Acks in an IDLE packet
void onLpPacketAcknowledged(UnackedFrags::iterator fragIt)
remove the fragment with the given sequence number from the map of unacknowledged fragments...
provides for reliable sending and receiving of link-layer packets
const size_t MAX_NDN_PACKET_SIZE
Practical size limit of a network-layer packet.
Definition: tlv.hpp:41
size_t nGreaterSeqAcks
number of Acks received for sequences greater than this fragment