16#include "ns3/eht-frame-exchange-manager.h"
18#include "ns3/simulator.h"
23#undef NS_LOG_APPEND_CONTEXT
24#define NS_LOG_APPEND_CONTEXT std::clog << "[link=" << +m_linkId << "] "
82 m_cam->NotifyRxStartNow(duration);
90 m_cam->NotifyRxEndOkNow();
98 m_cam->NotifyRxEndErrorNow(txVector);
106 m_cam->NotifyTxStartNow(duration);
112 const std::vector<Time>& per20MhzDurations)
override
116 m_cam->NotifyCcaBusyStartNow(duration, channelType, per20MhzDurations);
122 m_cam->NotifySwitchingStartNow(
this, duration);
129 m_cam->NotifySleepNow();
137 m_cam->NotifyOffNow();
145 m_cam->NotifyWakeupNow();
153 m_cam->NotifyOnNow();
170 TypeId(
"ns3::ChannelAccessManager")
172 .SetGroupName(
"Wifi")
174 .AddAttribute(
"GenerateBackoffIfTxopWithoutTx",
175 "Specify whether the backoff should be invoked when the AC gains the "
176 "right to start a TXOP but it does not transmit any frame "
177 "(e.g., due to constraints associated with EMLSR operations), "
178 "provided that the queue is not actually empty.",
183 .AddAttribute(
"ProactiveBackoff",
184 "Specify whether a new backoff value is generated when a CCA busy "
185 "period starts, the backoff counter is zero and the station is not a "
186 "TXOP holder. This is useful to generate a new backoff value when, "
187 "e.g., the backoff counter reaches zero, the station does not transmit "
188 "and subsequently the medium becomes busy.",
192 .AddAttribute(
"ResetBackoffThreshold",
193 "If no PHY operates on this link, or the PHY operating on this link "
194 "stays in sleep mode or off mode, for a period greater than this "
195 "threshold, all the backoffs are reset.",
199 .AddAttribute(
"NSlotsLeft",
200 "The NSlotsLeftAlert trace source is fired when the number of remaining "
201 "backoff slots for any AC is equal to or less than the value of this "
202 "attribute. Note that the trace source is fired only if the AC for which "
203 "the previous condition is met has requested channel access. Also, if "
204 "the value of this attribute is zero, the trace source is never fired.",
208 .AddAttribute(
"NSlotsLeftMinDelay",
209 "The minimum gap between the end of a medium busy event and the time "
210 "the NSlotsLeftAlert trace source can be fired.",
214 .AddTraceSource(
"NSlotsLeftAlert",
215 "The number of remaining backoff slots for the AC with the given index "
216 "reached the threshold set through the NSlotsLeft attribute.",
218 "ns3::ChannelAccessManager::NSlotsLeftCallback");
227 m_lastRxReceivedOk(
true),
229 m_lastSwitchingEnd(0),
233 InitLastBusyStructs();
258std::shared_ptr<PhyListener>
263 return listenerIt->second;
280 "There is already an active listener registered for given PHY");
282 phyListener->SetActive(
true);
286 phy->UnregisterListener(phyListener);
295 phyListener = std::make_shared<PhyListener>(
this);
315 phy->RegisterListener(phyListener);
324 phy->UnregisterListener(phyListener);
343 listener->SetActive(
false);
354 "The given PHY is already expected to switch channel");
421 if (!
m_phy || !
m_phy->GetOperatingChannel().IsOfdm())
426 if (width >=
MHz_u{40})
437 if (width >=
MHz_u{80})
448 if (width >=
MHz_u{160})
459 if (width >=
MHz_u{320})
513 bool hadFramesToTransmit,
514 bool checkMediumBusy)
516 NS_LOG_FUNCTION(
this << txop << hadFramesToTransmit << checkMediumBusy);
548 if (!hadFramesToTransmit && txop->HasFramesToTransmit(
m_linkId) &&
551 if (checkMediumBusy && !
IsBusy())
577 m_phy->NotifyChannelAccessRequested();
590 if (
const auto diff = txop->GetBackoffStart(
m_linkId) - accessGrantStart;
591 txop->IsQosTxop() && diff.IsStrictlyPositive())
595 const auto div = diff /
GetSlot();
596 const uint32_t nIntSlots = div.GetHigh() + (div.GetLow() > 0 ? 1 : 0);
597 txop->UpdateBackoffSlotsNow(0, accessGrantStart + (nIntSlots *
GetSlot()),
m_linkId);
602 txop->NotifyAccessRequested(
m_linkId);
614 if (accessGrantStart > now)
631 NS_LOG_DEBUG(
"dcf " << k <<
" needs access. backoff expired. access granted. slots="
632 << txop->GetBackoffSlots(
m_linkId));
635 std::vector<Ptr<Txop>> internalCollisionTxops;
636 for (
auto j = i; j !=
m_txops.end(); j++, k++)
643 "dcf " << k <<
" needs access. backoff expired. internal collision. slots="
644 << otherTxop->GetBackoffSlots(
m_linkId));
650 internalCollisionTxops.push_back(otherTxop);
671 (
m_phy->GetOperatingChannel().IsOfdm() &&
m_phy->GetChannelWidth() >
MHz_u{20})
673 :
m_phy->GetChannelWidth();
676 for (
auto& collidingTxop : internalCollisionTxops)
678 m_feManager->NotifyInternalCollision(collidingTxop);
686 txop->UpdateBackoffSlotsNow(0, now,
m_linkId);
690 k = std::distance(
m_txops.begin(), i);
704 const auto sleepForTooLong =
706 const auto offForTooLong =
709 if (noPhyForTooLong || sleepForTooLong || offForTooLong)
720std::multimap<Time, WifiExpectedAccessReason>
726 std::multimap<Time, WifiExpectedAccessReason> ret;
759 <<
", busy access start=" << busyAccessStart.As(
Time::US)
761 <<
", nav access start=" << navAccessStart.As(
Time::US)
763 <<
", no PHY start=" << noPhyStart.As(
Time::US)
764 <<
", sleep access start=" << lastSleepEnd.As(
Time::US)
765 <<
", off access start=" << lastOffEnd.As(
Time::US));
776 const auto accessGrantedStart = timeReasonMap.crbegin()->first;
779 return accessGrantedStart +
GetSifs();
792 const auto mostRecentEvent =
793 std::max({txop->GetBackoffStart(
m_linkId),
795 NS_LOG_DEBUG(
"Backoff start for " << txop->GetWifiMacQueue()->GetAc() <<
": "
798 return mostRecentEvent;
813 NS_LOG_DEBUG(
"Backoff end for " << txop->GetWifiMacQueue()->GetAc() <<
": "
825 const auto deadline = now + delay;
828 auto accessGrantStart = timeReasonMap.crbegin()->first;
830 if (accessGrantStart >= deadline)
833 for (
const auto& [time, reason] : timeReasonMap)
835 if (time >= deadline)
842 <<
") too late for reason " << reason);
846 NS_ABORT_MSG(
"No reason found that exceeds the deadline!");
859 if (!txop->HasFramesToTransmit(
m_linkId))
871 if (backoffEnd >= now && backoffEnd <= deadline)
873 NS_LOG_DEBUG(
"Backoff end for " << txop->GetWifiMacQueue()->GetAc() <<
" on link "
879 NS_LOG_DEBUG(
"Access grant not expected for reason: " << reason);
912 if (txop->IsQosTxop())
917 NS_LOG_DEBUG(
"dcf " << k <<
" dec backoff slots=" << n);
918 Time backoffUpdateBound = backoffStart + (n *
GetSlot());
919 txop->UpdateBackoffSlotsNow(n, backoffUpdateBound,
m_linkId);
942 backoffEnd > now && backoffEnd < expectedBackoffEnd)
944 expectedBackoffEnd = backoffEnd;
949 NS_LOG_DEBUG(
"Access timeout needed: " << (nextTxop !=
nullptr));
952 const auto aci = nextTxop->GetWifiMacQueue()->GetAc();
953 NS_LOG_DEBUG(
"expected backoff end=" << expectedBackoffEnd <<
" by " << aci);
954 auto expectedBackoffDelay = expectedBackoffEnd - now;
958 const auto expectedNotifyTime =
962 if (expectedNotifyTime > now)
965 expectedBackoffDelay = expectedNotifyTime - now;
1009 if (lastIdle.second.start <= end - interval && lastIdle.second.end >= end)
1012 width = (width ==
MHz_u{0}) ?
MHz_u{20} : (2 * width);
1029 NS_ASSERT_MSG(indices.size() == 1 && *indices.cbegin() == 0,
1030 "Index 0 only can be specified if the channel width is less than 40 MHz");
1034 for (
const auto index : indices)
1039 NS_LOG_DEBUG(
"20 MHz channel with index " << +index <<
" is busy");
1053 NS_LOG_DEBUG(
"Backoff will resume at time " << resume <<
" with "
1054 << qosTxop->GetBackoffSlots(
m_linkId)
1055 <<
" remaining slot(s)");
1056 qosTxop->UpdateBackoffSlotsNow(0, resume,
m_linkId);
1130 const std::vector<Time>& per20MhzDurations)
1138 lastBusyEndIt->second = now + duration;
1140 "Size of received vector (" << per20MhzDurations.size()
1141 <<
") differs from the expected size ("
1143 for (std::size_t chIdx = 0; chIdx < per20MhzDurations.size(); ++chIdx)
1145 if (per20MhzDurations[chIdx].IsStrictlyPositive())
1158 txop->GetBackoffSlots(
m_linkId) == 0)
1160 NS_LOG_DEBUG(
"Generate backoff for " << txop->GetWifiMacQueue()->GetAc());
1185 phy->GetOperatingChannel() == emlsrInfoIt->second.channel)
1194 ehtFem->NotifySwitchingEmlsrLink(phy, emlsrInfoIt->second.linkId, duration);
1210 for (
const auto& txop :
m_txops)
1247 if (remainingSlots > 0)
1261 for (
const auto& txop :
m_txops)
1335 NS_LOG_DEBUG(
"Do not reset NAV, CTS may have been missed due to the main PHY switching "
1336 "to another link to take over a TXOP while receiving the CTS");
1404 if (idleStart >= now)
1412 if (busyEnd.second < now)
1414 auto lastIdleIt =
m_lastIdle.find(busyEnd.first);
1416 lastIdleIt->second = {std::max(idleStart, busyEnd.second), now};
1418 << lastIdleIt->second.end.As(
Time::S)
1419 <<
") on channel " << lastIdleIt->first);
1430 return (os <<
"ACCESS EXPECTED");
1432 return (os <<
"NOT_REQUESTED");
1434 return (os <<
"NOTHING_TO_TX");
1436 return (os <<
"RX_END");
1438 return (os <<
"BUSY_END");
1440 return (os <<
"TX_END");
1442 return (os <<
"NAV_END");
1444 return (os <<
"ACK_TIMER_END");
1446 return (os <<
"CTS_TIMER_END");
1448 return (os <<
"SWITCHING_END");
1450 return (os <<
"NO_PHY_END");
1452 return (os <<
"SLEEP_END");
1454 return (os <<
"OFF_END");
1456 return (os <<
"BACKOFF_END");
1459 return (os <<
"Unknown");
AttributeValue implementation for Boolean.
Manage a set of ns3::Txop.
bool m_proactiveBackoff
whether a new backoff value is generated when a CCA busy period starts and the backoff counter is zer...
std::vector< Time > m_lastPer20MHzBusyEnd
the last busy end time per 20 MHz channel (HE stations and channel width > 20 MHz only)
bool IsBusy() const
Check if the device is busy sending or receiving, or NAV or CCA busy.
void ResetBackoff(Ptr< Txop > txop)
Reset the backoff for the given DCF/EDCAF.
void DoRestartAccessTimeoutIfNeeded()
void NotifyRxStartNow(Time duration)
void NotifySwitchingStartNow(PhyListener *phyListener, Time duration)
NSlotsLeftTracedCallback m_nSlotsLeftCallback
traced callback for NSlotsLeft alerts
Time GetBackoffStartFor(Ptr< Txop > txop) const
Return the time when the backoff procedure started for the given Txop.
void ResetState()
Reset the state variables of this channel access manager.
void NotifySwitchingEmlsrLink(Ptr< WifiPhy > phy, const WifiPhyOperatingChannel &channel, uint8_t linkId)
Notify that the given PHY is about to switch to the given operating channel, which is used by the giv...
void ResetAllBackoffs()
Reset the backoff for all the DCF/EDCAF.
void NotifyWakeupNow()
Notify the Txop that the device has been resumed from sleep mode.
bool m_lastRxReceivedOk
the last receive OK
std::unordered_map< Ptr< WifiPhy >, EmlsrLinkSwitchInfo > m_switchingEmlsrLinks
Store information about the PHY objects that are going to operate on another EMLSR link.
std::map< WifiChannelListType, Timespan > m_lastIdle
the last idle start and end time for each channel type
Ptr< WifiPhy > m_phy
pointer to the unique active PHY
void NotifyAckTimeoutResetNow()
Notify that ack timer has reset.
void SetGenerateBackoffOnNoTx(bool enable)
Set the member variable indicating whether the backoff should be invoked when an AC gains the right t...
void NotifyTxStartNow(Time duration)
void NotifyRxEndOkNow()
Notify the Txop that a packet reception was just completed successfully.
virtual Time GetEifsNoDifs() const
Return the EIFS duration minus a DIFS.
uint8_t m_linkId
the ID of the link this object is associated with
uint8_t m_nSlotsLeft
fire the NSlotsLeftAlert trace source when the backoff counter with the minimum value among all ACs r...
void NotifyCcaBusyStartNow(Time duration, WifiChannelListType channelType, const std::vector< Time > &per20MhzDurations)
Time m_lastAckTimeoutEnd
the last Ack timeout end time
Timespan m_lastNoPhy
the last start and end time no PHY was operating on the link
Time m_cachedSlot
cached value for slot, to be only used without a PHY
Time m_eifsNoDifs
EIFS no DIFS time.
virtual Time GetSlot() const
Return the slot duration for this PHY.
Time m_nSlotsLeftMinDelay
the minimum gap between the end of a medium busy event and the time the NSlotsLeftAlert trace source ...
void NotifyAckTimeoutStartNow(Time duration)
Notify that ack timer has started for the given duration.
void AccessTimeout()
Called when access timeout should occur (e.g.
Time GetBackoffEndFor(Ptr< Txop > txop) const
Return the time when the backoff procedure ended (or will end) for the given Txop.
void UpdateBackoff()
Update backoff slots for all Txops.
void DeactivatePhyListener(Ptr< WifiPhy > phy)
Deactivate current registered listener for PHY events on the given PHY.
void SetLinkId(uint8_t linkId)
Set the ID of the link this Channel Access Manager is associated with.
void SetupFrameExchangeManager(Ptr< FrameExchangeManager > feManager)
Set up the Frame Exchange Manager.
bool NeedBackoffUponAccess(Ptr< Txop > txop, bool hadFramesToTransmit, bool checkMediumBusy)
Determine if a new backoff needs to be generated as per letter a) of Section 10.23....
void NotifyCtsTimeoutStartNow(Time duration)
Notify that CTS timer has started for the given duration.
void RequestAccess(Ptr< Txop > txop)
Time m_lastSwitchingEnd
the last switching end time
Timespan m_lastRx
the last receive start and end time
std::map< WifiChannelListType, Time > m_lastBusyEnd
the last busy end time for each channel type
void RemovePhyListener(Ptr< WifiPhy > phy)
Remove current registered listener for PHY events on the given PHY.
bool m_generateBackoffOnNoTx
whether the backoff should be invoked when the AC gains the right to start a TXOP but it does not tra...
Time m_lastTxEnd
the last transmit end time
void SetupPhyListener(Ptr< WifiPhy > phy)
Set up (or reactivate) listener for PHY events on the given PHY.
Time m_lastCtsTimeoutEnd
the last CTS timeout end time
MHz_u GetLargestIdlePrimaryChannel(Time interval, Time end)
Return the width of the largest primary channel that has been idle for the given time interval before...
void DoDispose() override
Destructor implementation.
WifiExpectedAccessReason GetExpectedAccessWithin(const Time &delay) const
Check whether channel access is expected to be granted within the given delay.
void NotifySleepNow()
Notify the Txop that the device has been put in sleep mode.
Ptr< FrameExchangeManager > m_feManager
pointer to the Frame Exchange Manager
void NotifyRxEndErrorNow(const WifiTxVector &txVector)
Notify the Txop that a packet reception was just completed unsuccessfully.
Timespan m_lastSleep
the last sleep start and end time
void UpdateLastIdlePeriod()
This method determines whether the medium has been idle during a period (of non-null duration) immedi...
void DisableEdcaFor(Ptr< Txop > qosTxop, Time duration)
void DoInitialize() override
Initialize() implementation.
Txops m_txops
the vector of managed Txops
std::multimap< Time, WifiExpectedAccessReason > DoGetAccessGrantStart(bool ignoreNav) const
Return a map containing (Time, WifiExpectedAccessReason) pairs sorted in increasing order of times.
bool GetPer20MHzBusy(const std::set< uint8_t > &indices) const
static TypeId GetTypeId()
Get the type ID.
void DoGrantDcfAccess()
Grant access to Txop using DCF/EDCF contention rules.
void ResizeLastBusyStructs()
Resize the structures holding busy end times per channel type (primary, secondary,...
std::shared_ptr< PhyListener > GetPhyListener(Ptr< WifiPhy > phy) const
Get current registered listener for PHY events on the given PHY.
Time m_lastNavEnd
the last NAV end time
~ChannelAccessManager() override
void NotifyCtsTimeoutResetNow()
Notify that CTS timer has reset.
void NotifyOffNow()
Notify the Txop that the device has been put in off mode.
void NotifyNavResetNow(Time duration)
Time GetAccessGrantStart(bool ignoreNav=false) const
Access will never be granted to the medium before the time returned by this method.
void Add(Ptr< Txop > txop)
Time m_cachedSifs
cached value for SIFS, to be only used without a PHY
void NotifyOnNow()
Notify the Txop that the device has been resumed from off mode.
PhyListenerMap m_phyListeners
the PHY listeners
Timespan m_lastOff
the last off start and end time
virtual Time GetSifs() const
Return the Short Interframe Space (SIFS) for this PHY.
static const Time DEFAULT_N_SLOTS_LEFT_MIN_DELAY
default value for the NSlotsLeftMinDelay attribute, corresponds to a PIFS in 5GHz/6GHz bands
Time m_resetBackoffThreshold
if no PHY operates on a link for a period greater than this threshold, the backoff on that link is re...
void NotifyNavStartNow(Time duration)
EventId m_accessTimeout
the access timeout ID
bool GetGenerateBackoffOnNoTx() const
void InitLastBusyStructs()
Initialize the structures holding busy end times per channel type (primary, secondary,...
A base class which provides memory management and object aggregation.
bool m_active
whether this PHY listener is active
PhyListener(ns3::ChannelAccessManager *cam)
Create a PhyListener for the given ChannelAccessManager.
void NotifyOff() override
Notify listeners that we went to switch off.
void NotifySleep() override
Notify listeners that we went to sleep.
ns3::ChannelAccessManager * m_cam
ChannelAccessManager to forward events to.
void NotifyRxStart(Time duration) override
void NotifyOn() override
Notify listeners that we went to switch on.
void NotifySwitchingStart(Time duration) override
void SetActive(bool active)
Set this listener to be active or not.
void NotifyRxEndOk() override
We have received the last bit of a packet for which NotifyRxStart was invoked first and,...
void NotifyWakeup() override
Notify listeners that we woke up.
void NotifyCcaBusyStart(Time duration, WifiChannelListType channelType, const std::vector< Time > &per20MhzDurations) override
void NotifyRxEndError(const WifiTxVector &txVector) override
void NotifyTxStart(Time duration, dBm_u txPower) override
Smart pointer class similar to boost::intrusive_ptr.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
static Time Now()
Return the current simulation virtual time.
static Time GetMaximumSimulationTime()
Get the maximum representable simulation time.
static Time GetDelayLeft(const EventId &id)
Get the remaining time until this event will execute.
Simulation virtual time values and global simulation resolution.
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
AttributeValue implementation for Time.
a unique identifier for an interface.
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Hold an unsigned integer type.
receive notifications about PHY events.
Class that keeps track of all information about the current PHY operating channel.
This class mimics the TXVECTOR which is to be passed to the PHY in order to define the parameters whi...
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Ptr< const AttributeChecker > MakeBooleanChecker()
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Ptr< const AttributeChecker > MakeUintegerChecker()
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
#define NS_ABORT_MSG(msg)
Unconditional abnormal program termination with a message.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Time MicroSeconds(uint64_t value)
Construct a Time in the indicated unit.
Time Seconds(double value)
Construct a Time in the indicated unit.
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
WifiExpectedAccessReason
Enumeration values for the outcome of the check whether channel access is expected to be gained withi...
WifiChannelListType
Enumeration of the possible channel-list parameter elements defined in Table 8-5 of IEEE 802....
@ WIFI_PHY_BAND_2_4GHZ
The 2.4 GHz band.
@ WIFI_CHANLIST_SECONDARY40
@ WIFI_CHANLIST_SECONDARY
@ WIFI_CHANLIST_SECONDARY160
@ WIFI_CHANLIST_SECONDARY80
Every class exported by the ns3 library is enclosed in the ns3 namespace.
std::ostream & operator<<(std::ostream &os, const Angles &a)
double MHz_u
MHz weak type.
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Time GetEstimatedAckTxTime(const WifiTxVector &txVector)
std::size_t Count20MHzSubchannels(MHz_u channelWidth)
Return the number of 20 MHz subchannels covering the channel width.
double dBm_u
dBm weak type
Ptr< T1 > StaticCast(const Ptr< T2 > &p)
Cast a Ptr.
Information associated with each PHY that is going to operate on another EMLSR link.
Structure defining start time and end time for a given state.