diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 7f665290..832cc811 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -22,7 +22,9 @@ use core::future::Future; use core::ops::{Deref, DerefMut}; use core::sync::atomic::{AtomicBool, AtomicU32, Ordering as AtomicOrdering}; use core::time::Duration; +use ziggurat_zigbee::debouncer::Debouncer; use ziggurat_zigbee::flat_map::FlatMap; +use ziggurat_zigbee::nwk::activity::ActivityParams; use ziggurat_zigbee::nwk::frame::{NwkFrame, NwkSecurityHeaderKeyId}; mod aps; @@ -350,6 +352,10 @@ pub struct Nib { /// The neighbor table: link quality accounting, link status digestion, aging pub neighbors: Neighbors, + /// When the next link status broadcast is due + pub link_status_debouncer: Debouncer, + /// When the next many-to-one route request is due + pub mtorr_debouncer: Debouncer, /// NWK routing state and decision logic (route/discovery/record tables) pub routing: Routing, /// Broadcast deduplication and passive acknowledgment accounting @@ -508,6 +514,8 @@ impl State { update_id: config.update_id, tx_total: 0, neighbors: Neighbors::default(), + link_status_debouncer: Debouncer::default(), + mtorr_debouncer: Debouncer::default(), routing: Routing::default(), broadcasts: Broadcasts::default(), nwk_security: NwkSecurity::new( @@ -716,13 +724,15 @@ pub struct ZigbeeStack { /// network-wide broadcast storm (spec 2.4.3.1.12.2) pub(crate) parent_annce_received: Mutex>, - /// Wakes the MTORR scheduler before its max interval when accumulated route - /// errors or delivery failures cross their thresholds - pub(crate) mtorr_kick: Notify, + /// Wakes the many-to-one route request task when its next advertisement moved + /// earlier + pub(crate) mtorr_wake: Notify, /// Signaled whenever a link status command is digested; the MTORR startup wait /// uses it to advertise as soon as a neighbor link is established pub(crate) link_status_received: Notify, + /// Wakes the link status task when the next link status broadcast moved earlier + pub(crate) link_status_wake: Notify, pub(crate) address_conflict_wake: Notify, /// Wakes the beacon-spam reactor when a beacon request opens its spray window. pub(crate) beacon_spam_wake: Notify, @@ -798,6 +808,34 @@ impl ZigbeeStack { R::sleep(deadline.saturating_duration_since(self.core_now())).await; } + /// What the tables need to keep their activity counters. + pub fn activity_params(&self) -> ActivityParams { + ActivityParams { + initial_count: self.tunables.router_age_limit(), + period: self.tunables.link_status_period(), + } + } + + /// Sleep until a debouncer fires. `wake` signals that a request moved its next + /// firing earlier: the sleep then starts again, until the new time. + async fn wait_for_debouncer( + &self, + debouncer: impl Fn(&Nib) -> &Debouncer + Send, + wake: &Notify, + ) { + loop { + let next = debouncer(&self.core().nib).next(); + let due = core::pin::pin!(self.sleep_until_core(next)); + let moved = core::pin::pin!(wake.notified()); + + if let futures::future::Either::Left(((), _)) = + futures::future::select(due, moved).await + { + return; + } + } + } + /// Run `future`, failing with [`Elapsed`] if a [`CoreInstant`] deadline passes first. async fn timeout_at_core( &self, @@ -841,8 +879,9 @@ impl ZigbeeStack { src_match_sync: Notify::new(), src_match_written: Mutex::new(SrcMatchTable::default()), parent_annce_received: Mutex::new(None), - mtorr_kick: Notify::new(), + mtorr_wake: Notify::new(), link_status_received: Notify::new(), + link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), beacon_spam_wake: Notify::new(), maintenance_wake: Notify::new(), diff --git a/crates/ziggurat-driver/src/zigbee_stack/joining.rs b/crates/ziggurat-driver/src/zigbee_stack/joining.rs index 5c80c16e..7142ec8f 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/joining.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/joining.rs @@ -117,6 +117,7 @@ impl ZigbeeStack { relationship: neighbors::Relationship::UnauthenticatedChild, }, self.core_now(), + self.activity_params(), ); // A new child deadline may precede everything the maintenance task knows @@ -1180,6 +1181,7 @@ impl ZigbeeStack { }, }, self.core_now(), + self.activity_params(), ); // A new child deadline may precede everything the maintenance task knows diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 02bf4a7d..a1b5d0c6 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -1,8 +1,10 @@ use crate::runtime::Runtime; use alloc::vec::Vec; +use core::time::Duration; use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_phy::RadioPhy; +use ziggurat_zigbee::nwk::NwkDeviceType; use ziggurat_zigbee::nwk::commands::{NwkCommand, NwkLinkStatusCommand}; use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame}; @@ -17,7 +19,43 @@ const MAX_LINK_STATUSES: usize = 7; impl ZigbeeStack { pub(super) fn maybe_recompute_lqa(&self, sender_nwk: Nwk, lqi: u8, _rssi: i8) { - self.core().nib.neighbors.record_lqa(sender_nwk, lqi); + let link_status_due = self.core().nib.neighbors.record_lqa(sender_nwk, lqi); + + if link_status_due { + self.request_link_status_for_new_router(); + } + } + + /// Send the next link status soon: a router it will newly list waits for it to + /// learn its cost. + fn request_link_status_for_new_router(&self) { + // Coordinator only. Routers must not run this as it is: every router that + // hears a new neighbor would send within the same half second, each with its + // whole list, and most of those frames would collide. + if self.state.role == NwkDeviceType::Coordinator { + self.request_early_link_status(); + } + } + + /// Send the next link status after the delay of a gratuitous one (spec 3.6.4.4.2). + fn request_early_link_status(&self) { + let min_jitter = self.tunables.min_router_bootstrap_jitter(); + let max_jitter = self.tunables.max_router_bootstrap_jitter(); + let jitter = min_jitter + + max_jitter + .saturating_sub(min_jitter) + .mul_f32(crate::rng::random_f32::()); + + let at = self.core_now() + jitter; + + if self + .core() + .nib + .link_status_debouncer + .request(at, Duration::ZERO) + { + self.link_status_wake.notify_one(); + } } pub(super) fn end_device_child_eui64(&self, nwk: Nwk) -> Option { @@ -84,6 +122,7 @@ impl ZigbeeStack { lqi, &link_status_cmd, self.core_now(), + self.activity_params(), ); // The neighbor no longer answers at its old address, so routes through it @@ -101,6 +140,14 @@ impl ZigbeeStack { self.invalidate_routes_via(neighbor_nwk); } + if outcome.link_status_answer_due { + self.request_early_link_status(); + } else if outcome.link_status_due + && self.tunables.hack_early_link_status_for_unknown_routers() + { + self.request_link_status_for_new_router(); + } + self.link_status_received.notify_one(); } @@ -114,21 +161,12 @@ impl ZigbeeStack { return Err(EnqueueError::NotStarted); } - // Decrement the `recent_activity` field of every active routing table entry - self.core().nib.routing.decay_activity(); - self.maybe_age_neighbors(); - // Decrement the inbound and outbound activity fields for neighbors - let mut link_statuses = { - let mut core = self.core(); - core.nib.neighbors.decay_activity(); - - if empty { - Vec::new() - } else { - core.nib.neighbors.link_status_entries() - } + let mut link_statuses = if empty { + Vec::new() + } else { + self.core().nib.neighbors.link_status_entries() }; // Link statuses are sorted in ascending order @@ -184,19 +222,28 @@ impl ZigbeeStack { } } + fn restart_link_status_period(&self) { + let now = self.core_now(); + let period = self.tunables.link_status_period(); + + self.core().nib.link_status_debouncer.fired(now, period); + } + pub async fn periodic_link_status_broadcast_task(&self) { - let mut next = self.core_now() + self.tunables.link_status_period(); + // The network start has just sent one + self.restart_link_status_period(); loop { - self.sleep_until_core(next).await; + self.wait_for_debouncer(|nib| &nib.link_status_debouncer, &self.link_status_wake) + .await; + + self.restart_link_status_period(); // The link status broadcast has a radius of 1 so delivery does not wait for // a relay quorum. if let Ok(link_status) = self.send_link_status_broadcast(false) { let _ = link_status.delivered().await; } - - next = next + self.tunables.link_status_period(); } } } diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index b5569389..078ee6cb 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -53,7 +53,12 @@ impl ZigbeeStack { } pub(super) fn forget_nwk_state_in(&self, mut core: CoreGuard<'_>, nwk: Nwk) { - core.nib.routing.forget(self.state.network_address, nwk); + core.nib.routing.forget( + self.state.network_address, + nwk, + self.core_now(), + self.activity_params(), + ); core.sends.fail_unrouted(nwk); self.commit_sends(core); } @@ -442,6 +447,7 @@ impl ZigbeeStack { now, self.tunables.route_discovery_time(), self.tunables.pending_route_discovery_attempts(), + self.activity_params(), ); if let Some(route_request_identifier) = route_request_identifier { self.broadcast_discovery_request( @@ -569,13 +575,19 @@ impl ZigbeeStack { let relaying_ieee = core.nib.address_map.eui64_for(next_hop_address); if let Some(relaying_ieee) = relaying_ieee { - core.nib.neighbors.record_outbound_activity(relaying_ieee); + core.nib.neighbors.record_outbound_activity( + relaying_ieee, + self.core_now(), + self.tunables.link_status_period(), + ); } // And the routing table counters - core.nib - .routing - .record_usage(nwk_frame.nwk_header.destination); + core.nib.routing.record_usage( + nwk_frame.nwk_header.destination, + self.core_now(), + self.tunables.link_status_period(), + ); } self.increment_tx_total(); @@ -836,10 +848,11 @@ impl ZigbeeStack { self.maybe_recompute_lqa(sender_nwk, lqi, rssi); // Receiving a unicast from a neighbor counts as inbound activity - self.core() - .nib - .neighbors - .record_inbound_activity(sender_nwk); + self.core().nib.neighbors.record_inbound_activity( + sender_nwk, + self.core_now(), + self.tunables.link_status_period(), + ); // Spec 3.6.2.2: the radius is decremented on receipt and a frame that reaches // zero is never retransmitted diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index 3dbcc177..a5e653a7 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -44,6 +44,7 @@ impl ZigbeeStack { nwk_frame.nwk_header.source, updated_path_cost, now, + self.activity_params(), ); let (next_hop_nwk, path_cost) = match outcome.disposition { @@ -158,6 +159,7 @@ impl ZigbeeStack { route_request_cmd.many_to_one, self.core_now(), self.tunables.route_discovery_time(), + self.activity_params(), ); if !outcome.accepted { @@ -233,10 +235,11 @@ impl ZigbeeStack { // many-to-one requests are addressed to a broadcast address, so there is no // destination to track for them. if !many_to_one { - self.core() - .nib - .routing - .note_relayed_discovery(route_request_cmd.destination_address); + self.core().nib.routing.note_relayed_discovery( + route_request_cmd.destination_address, + self.core_now(), + self.activity_params(), + ); } let rebroadcast_radius = nwk_frame.nwk_header.radius.saturating_sub(1); @@ -344,25 +347,28 @@ impl ZigbeeStack { } loop { - let min_deadline = self.core_now() + self.tunables.mtorr_min_interval(); - let max_deadline = self.core_now() + self.tunables.mtorr_max_interval(); + let now = self.core_now(); + let max_interval = self.tunables.mtorr_max_interval(); + self.core().nib.mtorr_debouncer.fired(now, max_interval); let _ = self.send_many_to_one_route_request().delivered().await; self.core().nib.routing.reset_mtorr_triggers(); - // Advertise every max interval, sooner when accumulated route errors or - // delivery failures signal that routes toward us have gone bad, but never - // within the min interval - let max_sleep = core::pin::pin!(self.sleep_until_core(max_deadline)); - let kicked = core::pin::pin!(self.mtorr_kick.notified()); + // Advertise every max interval, or sooner when one was requested + self.wait_for_debouncer(|nib| &nib.mtorr_debouncer, &self.mtorr_wake) + .await; + } + } - if let futures::future::Either::Right(((), _)) = - futures::future::select(max_sleep, kicked).await - { - // Kicked early: still honor the minimum spacing before re-advertising. - self.sleep_until_core(min_deadline).await; - } + /// Advertise the many-to-one route again soon, but never within the min interval + /// of the last advertisement. + fn request_many_to_one_route_request(&self) { + let now = self.core_now(); + let min_interval = self.tunables.mtorr_min_interval(); + + if self.core().nib.mtorr_debouncer.request(now, min_interval) { + self.mtorr_wake.notify_one(); } } @@ -380,7 +386,7 @@ impl ZigbeeStack { .note_route_error(self.tunables.mtorr_route_error_threshold()); if kick { - self.mtorr_kick.notify_one(); + self.request_many_to_one_route_request(); } } @@ -398,7 +404,7 @@ impl ZigbeeStack { .note_delivery_failure(self.tunables.mtorr_delivery_failure_threshold()); if kick { - self.mtorr_kick.notify_one(); + self.request_many_to_one_route_request(); } } diff --git a/crates/ziggurat-driver/src/zigbee_stack/sends.rs b/crates/ziggurat-driver/src/zigbee_stack/sends.rs index b07cab0a..3d54d05c 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/sends.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/sends.rs @@ -372,6 +372,7 @@ impl ZigbeeStack { self.state.network_address, now, self.tunables.route_discovery_time(), + self.activity_params(), |destination| core.sends.has_unrouted(destination), ); diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 00651768..05a23e45 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -202,6 +202,7 @@ pub fn apply_children( relationship: Relationship::Child, }, now, + stack.activity_params(), ); core.nib.address_map.update_mapping(entry.ieee, entry.nwk); } @@ -223,9 +224,13 @@ pub fn apply_route_table( ) { let mut core = stack.state.core.lock(); for entry in payload.entries { - core.nib - .routing - .restore_route(entry.destination, entry.next_hop, entry.path_cost); + core.nib.routing.restore_route( + entry.destination, + entry.next_hop, + entry.path_cost, + stack.core_now(), + stack.activity_params(), + ); } } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 4035fb2b..3f8aa143 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -315,6 +315,14 @@ tunables! { /// The time between link status command frames. link_status_period: Duration = Duration::from_secs(15), + /// `nwkcMinRouterBootstrapJitter`: the shortest delay before a gratuitous link + /// status. + min_router_bootstrap_jitter: Duration = Duration::from_millis(500), + + /// `nwkcMaxRouterBootstrapJitter`: the longest delay before a gratuitous link + /// status. + max_router_bootstrap_jitter: Duration = Duration::from_secs(1), + /// The number of missed link status command frames before resetting the link costs /// to zero. router_age_limit: u8 = 3, @@ -406,6 +414,13 @@ tunables! { /// that permanently permit joins. Zero disables it (a single beacon per request, /// the spec behaviour). hack_beacon_spam_duration: Duration = Duration::from_millis(100), + + /// Uncooperative on a large network: as the coordinator, send an extra link status + /// within a second of the first link status from a router we did not know, so it + /// learns its cost without waiting for the next period. After a restart every + /// router is unknown, which means a burst of link statuses. When false, such a + /// router waits for the periodic link status. + hack_early_link_status_for_unknown_routers: bool = true, } #[cfg(test)] diff --git a/crates/ziggurat-zigbee/src/debouncer.rs b/crates/ziggurat-zigbee/src/debouncer.rs new file mode 100644 index 00000000..b9e6bc75 --- /dev/null +++ b/crates/ziggurat-zigbee/src/debouncer.rs @@ -0,0 +1,98 @@ +//! A timer that fires at a fixed interval, or sooner when asked. + +use core::time::Duration; + +use crate::Instant; + +/// A periodic deadline that a request can move earlier. A burst of requests fires once. +#[derive(Debug, Default)] +pub struct Debouncer { + next: Instant, + last_fired: Instant, +} + +impl Debouncer { + pub const fn next(&self) -> Instant { + self.next + } + + /// Ask for a firing by `at`, but no sooner than `min_interval` after the last one. + /// Returns whether the next firing moved earlier: it stays where it is if it is + /// already due sooner. + pub fn request(&mut self, at: Instant, min_interval: Duration) -> bool { + let at = at.max(self.last_fired + min_interval); + let earlier = at < self.next; + + if earlier { + self.next = at; + } + + earlier + } + + /// It fires at `now`: the next firing is due an `interval` later. + pub fn fired(&mut self, now: Instant, interval: Duration) { + self.last_fired = now; + self.next = now + interval; + } +} + +#[cfg(test)] +mod test { + use super::*; + + const INTERVAL: Duration = Duration::from_secs(15); + + fn at(millis: u64) -> Instant { + Instant::from_micros(0) + Duration::from_millis(millis) + } + + fn started() -> Debouncer { + let mut debouncer = Debouncer::default(); + debouncer.fired(at(0), INTERVAL); + debouncer + } + + #[test] + fn test_requests_close_together_share_the_earliest_time() { + let mut debouncer = started(); + + assert!(debouncer.request(at(700), Duration::ZERO)); + assert!(!debouncer.request(at(900), Duration::ZERO)); + assert!(debouncer.request(at(600), Duration::ZERO)); + + assert_eq!(debouncer.next(), at(600)); + } + + #[test] + fn test_request_after_the_interval_end_changes_nothing() { + let mut debouncer = started(); + + assert!(!debouncer.request(at(15_500), Duration::ZERO)); + assert_eq!(debouncer.next(), at(15_000)); + } + + #[test] + fn test_firing_restarts_the_interval() { + let mut debouncer = started(); + debouncer.request(at(700), Duration::ZERO); + + debouncer.fired(at(700), INTERVAL); + assert_eq!(debouncer.next(), at(15_700)); + } + + #[test] + fn test_request_waits_out_the_minimum_interval() { + let min_interval = Duration::from_secs(10); + let mut debouncer = started(); + + // Too soon after the last firing: held until the minimum interval has passed + assert!(debouncer.request(at(2_000), min_interval)); + assert_eq!(debouncer.next(), at(10_000)); + + // A request after it is taken as it is + debouncer.fired(at(10_000), INTERVAL); + assert!(debouncer.request(at(21_000), min_interval)); + assert_eq!(debouncer.next(), at(21_000)); + } +} diff --git a/crates/ziggurat-zigbee/src/lib.rs b/crates/ziggurat-zigbee/src/lib.rs index a060f8e8..8444f3aa 100644 --- a/crates/ziggurat-zigbee/src/lib.rs +++ b/crates/ziggurat-zigbee/src/lib.rs @@ -6,6 +6,7 @@ pub mod aps; pub mod beacon; pub mod constants; pub mod crypto; +pub mod debouncer; pub mod flat_map; pub mod gp; pub mod nwk; diff --git a/crates/ziggurat-zigbee/src/nwk.rs b/crates/ziggurat-zigbee/src/nwk.rs index ebd20ec8..818c5d89 100644 --- a/crates/ziggurat-zigbee/src/nwk.rs +++ b/crates/ziggurat-zigbee/src/nwk.rs @@ -1,3 +1,4 @@ +pub mod activity; pub mod address_conflicts; pub mod addresses; pub mod broadcast_budget; diff --git a/crates/ziggurat-zigbee/src/nwk/activity.rs b/crates/ziggurat-zigbee/src/nwk/activity.rs new file mode 100644 index 00000000..4bf77424 --- /dev/null +++ b/crates/ziggurat-zigbee/src/nwk/activity.rs @@ -0,0 +1,137 @@ +use core::time::Duration; + +use crate::Instant; + +const STEPS_PER_COUNT: u16 = 256; + +/// A spec activity counter (`RecentActivity`, `RouterOutboundActivity`, +/// `RouterInboundActivity`). +/// +/// It is held in steps of 1/256 of a count, so it decays by the time that has passed +/// and not once per period. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Activity { + steps: u16, +} + +impl Activity { + const MAX_STEPS: u16 = u8::MAX as u16 * STEPS_PER_COUNT; + + pub const fn new(count: u8) -> Self { + Self { + steps: count as u16 * STEPS_PER_COUNT, + } + } + + /// The whole counts held. + pub const fn count(&self) -> u8 { + (self.steps / STEPS_PER_COUNT) as u8 + } + + pub fn record_use(&mut self) { + self.steps = self + .steps + .saturating_add(STEPS_PER_COUNT) + .min(Self::MAX_STEPS); + } + + pub const fn decay(&mut self, steps: u16) { + self.steps = self.steps.saturating_sub(steps); + } +} + +/// What a table needs to keep activity counters. +#[derive(Debug, Clone, Copy)] +pub struct ActivityParams { + /// The count a new counter starts at (`nwkRouterAgeLimit`) + pub initial_count: u8, + /// The time one count takes to decay (`nwkLinkStatusPeriod`) + pub period: Duration, +} + +/// The decay steps owed for the time from `*decayed_at` to `now`, at one count per +/// `period`. `*decayed_at` moves forward by the steps returned, so the rest of the time +/// counts toward the next call. +pub fn take_decay_steps(decayed_at: &mut Instant, now: Instant, period: Duration) -> u16 { + let steps_per_count = u64::from(STEPS_PER_COUNT); + let period = u64::try_from(period.as_micros()).unwrap(); + let elapsed = now.as_micros().saturating_sub(decayed_at.as_micros()); + let steps = elapsed * steps_per_count / period; + + // Rounded up, so a step shorter than a microsecond still moves `*decayed_at` + let taken = (steps * period).div_ceil(steps_per_count); + + // All of the steps are taken, even when they are more than a counter can hold: + // none is left over to decay a use recorded after this call + *decayed_at = Instant::from_micros(decayed_at.as_micros() + taken); + u16::try_from(steps).unwrap_or(u16::MAX) +} + +#[cfg(test)] +mod test { + use super::*; + + const PERIOD: Duration = Duration::from_secs(16); + + fn at(millis: u64) -> Instant { + Instant::from_micros(0) + Duration::from_millis(millis) + } + + #[test] + fn test_activity_decays_by_the_time_passed() { + let mut activity = Activity::new(3); + let mut decayed_at = at(0); + + // Half a period is half a count: the whole count drops from 3 to 2 + activity.decay(take_decay_steps(&mut decayed_at, at(8_000), PERIOD)); + assert_eq!(activity.count(), 2); + + // The same instant again owes nothing + assert_eq!(take_decay_steps(&mut decayed_at, at(8_000), PERIOD), 0); + + // The other half completes one whole count of decay + activity.decay(take_decay_steps(&mut decayed_at, at(16_000), PERIOD)); + assert_eq!(activity, Activity::new(2)); + } + + #[test] + fn test_time_shorter_than_a_step_carries_over() { + let mut decayed_at = at(0); + + // One step is 16 s / 256 = 62.5 ms + assert_eq!(take_decay_steps(&mut decayed_at, at(60), PERIOD), 0); + assert_eq!(take_decay_steps(&mut decayed_at, at(125), PERIOD), 2); + } + + #[test] + fn test_period_shorter_than_256_microseconds_decays() { + let period = Duration::from_micros(100); + let mut decayed_at = at(0); + let now = Instant::from_micros(50); + + // Half a period is half a count, and the same instant again owes nothing + assert_eq!(take_decay_steps(&mut decayed_at, now, period), 128); + assert_eq!(take_decay_steps(&mut decayed_at, now, period), 0); + } + + #[test] + fn test_long_gap_is_taken_in_one_call() { + let mut decayed_at = at(0); + + // Two hours hold more steps than a counter does + let now = at(2 * 60 * 60 * 1000); + assert_eq!(take_decay_steps(&mut decayed_at, now, PERIOD), u16::MAX); + assert_eq!(take_decay_steps(&mut decayed_at, now, PERIOD), 0); + } + + #[test] + fn test_activity_stays_between_0_and_255() { + let mut activity = Activity::new(254); + activity.record_use(); + activity.record_use(); + assert_eq!(activity, Activity::new(255)); + + activity.decay(u16::MAX); + assert_eq!(activity, Activity::new(0)); + } +} diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index e7e8ab40..cc09af65 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -3,6 +3,7 @@ use alloc::vec::Vec; use core::cmp; use crate::Instant; +use crate::nwk::activity::{Activity, ActivityParams, take_decay_steps}; use crate::nwk::commands::{NwkLinkStatus, NwkLinkStatusCommand}; use crate::nwk::frame::NwkHeader; use crate::ring_buffer::RingBuffer; @@ -126,12 +127,18 @@ pub struct TableEntry { pub router_connectivity: u8, pub router_neighbor_set_diversity: u8, - pub router_outbound_activity: u8, - pub router_inbound_activity: u8, + pub router_outbound_activity: Activity, + pub router_inbound_activity: Activity, pub security_timer: u8, } impl TableEntry { + /// Whether our link status lists this neighbor: a router we have heard from. A + /// neighbor without a sample has no cost to report. + pub fn is_in_link_status(&self) -> bool { + self.device_type == NwkDeviceType::Router && !self.lqas.is_empty() + } + pub fn incoming_link_cost(&self) -> u8 { self.lqas.median().map_or(0, lqi_to_link_cost) } @@ -188,6 +195,13 @@ pub struct LinkStatusOutcome { pub lost_link: Option, /// The sender's previous network address, if the link status came from a new one. pub replaced_address: Option, + /// Our link status lists the sender from now on and did not before, so the sender + /// has yet to learn its cost from us. + pub link_status_due: bool, + /// The sender's list was empty: it just started and asks who its neighbors are. + /// The spec owes an answer only to an unknown sender (3.6.4.4.2). We answer a + /// known one too so a restarted neighbor hears us at once. + pub link_status_answer_due: bool, } /// The neighbor table: link quality accounting, link status digestion, and aging. @@ -197,19 +211,25 @@ pub struct Neighbors { /// LQI samples for senders that have no neighbor entry yet, capped at /// [`PENDING_LQA_CAP`] entries. pending_lqas: FlatMap, + /// Up to when the activity counters have been decayed + activity_decayed_at: Instant, } impl Neighbors { /// Record an LQI sample for the device that transmitted a frame to us. LQA is a /// property of the radio link to the MAC transmitter; the frame's NWK originator - /// may be several hops away. - pub fn record_lqa(&mut self, sender_nwk: Nwk, lqi: u8) { + /// may be several hops away. Returns whether a link status is due: ours lists the + /// sender from now on and did not before. + pub fn record_lqa(&mut self, sender_nwk: Nwk, lqi: u8) -> bool { if let Some(entry) = self .table .values_mut() .find(|entry| entry.network_address == sender_nwk) { + let was_in_link_status = entry.is_in_link_status(); entry.lqas.push(lqi); + + !was_in_link_status && entry.is_in_link_status() } else { // No neighbor entry yet (e.g. a sibling router that has not sent a link // status command). Buffer the sample so the entry starts with usable link @@ -221,6 +241,8 @@ impl Neighbors { } self.pending_lqas.entry(sender_nwk).or_default().push(lqi); + + false } } @@ -522,17 +544,30 @@ impl Neighbors { /// across attachment retries. The fields a device may change between attachments /// are refreshed even on existing entries: a device may re-attach with different /// capabilities (e.g. re-flashed from router to end device). - pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant) { - self.upsert(child, now, Some(now)); + pub fn upsert_child(&mut self, child: ChildDescriptor, now: Instant, activity: ActivityParams) { + self.upsert(child, now, Some(now), activity); } /// Seed a child entry restored by the client on startup. Unlike a device that /// associates or rejoins, a restored child did not just attach to us. - pub fn restore_child(&mut self, child: ChildDescriptor, now: Instant) { - self.upsert(child, now, None); + pub fn restore_child( + &mut self, + child: ChildDescriptor, + now: Instant, + activity: ActivityParams, + ) { + self.upsert(child, now, None, activity); } - fn upsert(&mut self, child: ChildDescriptor, now: Instant, attached_at: Option) { + fn upsert( + &mut self, + child: ChildDescriptor, + now: Instant, + attached_at: Option, + activity: ActivityParams, + ) { + self.decay_activity(now, activity.period); + let entry = self.table.entry(child.eui64).or_insert_with(|| TableEntry { extended_address: child.eui64, network_address: child.network_address, @@ -555,8 +590,8 @@ impl Neighbors { attached_at, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: 0, - router_inbound_activity: 0, + router_outbound_activity: Activity::new(activity.initial_count), + router_inbound_activity: Activity::new(activity.initial_count), security_timer: 0, }); @@ -652,30 +687,40 @@ impl Neighbors { stale_neighbors } - /// Called once per `nwkLinkStatusPeriod`: decrement the inbound and outbound - /// activity counters for every neighbor. - pub fn decay_activity(&mut self) { + /// Decay the inbound and outbound activity of every neighbor by the time passed + /// since the last call, at one count per `period` (`nwkLinkStatusPeriod`). + pub fn decay_activity(&mut self, now: Instant, period: Duration) { + let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + + if steps == 0 { + return; + } + for entry in self.table.values_mut() { - entry.router_outbound_activity = entry.router_outbound_activity.saturating_sub(1); - entry.router_inbound_activity = entry.router_inbound_activity.saturating_sub(1); + entry.router_outbound_activity.decay(steps); + entry.router_inbound_activity.decay(steps); } } /// A unicast was forwarded through this neighbor. - pub fn record_outbound_activity(&mut self, eui64: Eui64) { + pub fn record_outbound_activity(&mut self, eui64: Eui64, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self.table.get_mut(&eui64) { - entry.router_outbound_activity = entry.router_outbound_activity.saturating_add(1); + entry.router_outbound_activity.record_use(); } } /// A unicast from this neighbor was received for relaying. - pub fn record_inbound_activity(&mut self, nwk: Nwk) { + pub fn record_inbound_activity(&mut self, nwk: Nwk, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self .table .values_mut() .find(|entry| entry.network_address == nwk) { - entry.router_inbound_activity = entry.router_inbound_activity.saturating_add(1); + entry.router_inbound_activity.record_use(); } } @@ -699,20 +744,18 @@ impl Neighbors { .values() // Only include routers in the link status list. Otherwise, we advertise // sleepy end devices that cannot be routed through. - .filter(|neighbor| neighbor.device_type == NwkDeviceType::Router) - .filter_map(|neighbor| { - // A neighbor we have not heard from yet has no cost to report - neighbor.lqas.median().map(|lqa| NwkLinkStatus { - address: neighbor.network_address, - incoming_cost: lqi_to_link_cost(lqa), - outgoing_cost: neighbor.outgoing_cost, - }) + .filter(|neighbor| neighbor.is_in_link_status()) + .map(|neighbor| NwkLinkStatus { + address: neighbor.network_address, + incoming_cost: neighbor.incoming_link_cost(), + outgoing_cost: neighbor.outgoing_cost, }) .collect() } /// Digest a received link status command, updating the sender's entry (creating a /// sibling entry for previously unseen routers). + #[allow(clippy::too_many_arguments)] pub fn on_link_status( &mut self, own_address: Nwk, @@ -721,7 +764,10 @@ impl Neighbors { lqi: u8, link_status_cmd: &NwkLinkStatusCommand, now: Instant, + activity: ActivityParams, ) -> LinkStatusOutcome { + self.decay_activity(now, activity.period); + // Collect the set of already-connected neighbors before mutating the state, for // the neighbor set diversity computation let neighbors_with_nonzero_outgoing_cost = self @@ -769,6 +815,11 @@ impl Neighbors { } } + let was_in_link_status = self + .table + .get(&source_ieee) + .is_some_and(TableEntry::is_in_link_status); + let neighbor_entry = self.table.entry(source_ieee).or_insert_with(|| { tracing::info!("Creating new neighbor entry for {source_ieee:?}"); @@ -794,8 +845,8 @@ impl Neighbors { attached_at: None, router_connectivity: 0, router_neighbor_set_diversity: 0, - router_outbound_activity: 0, - router_inbound_activity: 0, + router_outbound_activity: Activity::new(activity.initial_count), + router_inbound_activity: Activity::new(activity.initial_count), security_timer: 0, }; @@ -860,11 +911,6 @@ impl Neighbors { } } - if link_status_cmd.link_statuses.is_empty() { - // TODO: Initiate a gratuitous link status broadcast, jittered by - // nwkcMinRouterBootstrapJitter < nwkcMaxRouterBootstrapJitter - } - tracing::trace!("Updated neighbor table entry: {neighbor_entry:?}"); let lost_link = previous_outgoing_cost > 0 && neighbor_entry.outgoing_cost == 0; @@ -872,6 +918,8 @@ impl Neighbors { LinkStatusOutcome { lost_link: lost_link.then_some(neighbor_entry.network_address), replaced_address, + link_status_due: !was_in_link_status && neighbor_entry.is_in_link_status(), + link_status_answer_due: link_status_cmd.link_statuses.is_empty(), } } } @@ -883,6 +931,10 @@ mod test { use hex_literal::hex; const CHILD_NWK: Nwk = Nwk(0x1234); + const ACTIVITY: ActivityParams = ActivityParams { + initial_count: 3, + period: Duration::from_secs(15), + }; fn neighbors_with(device_type: NwkDeviceType) -> Neighbors { let mut neighbors = Neighbors::default(); @@ -896,6 +948,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), + ACTIVITY, ); neighbors } @@ -964,8 +1017,7 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - let outcome = neighbors.on_link_status(own, router, old, 200, &link_status, now); - assert_eq!(outcome, LinkStatusOutcome::default()); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); neighbors.record_lqa(old, 200); neighbors.record_lqa(old, 200); assert_eq!(neighbors.link(old).unwrap().eui64, router); @@ -975,12 +1027,14 @@ mod test { // link status carries the new address with the router's EUI64 neighbors.record_lqa(new, 40); neighbors.record_lqa(new, 40); - let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now); + let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now, ACTIVITY); assert_eq!( outcome, LinkStatusOutcome { lost_link: None, replaced_address: Some(old), + link_status_due: false, + link_status_answer_due: false, } ); @@ -1001,7 +1055,7 @@ mod test { assert_eq!(advertised, vec![new]); // A later link status from the same address changes nothing - let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now); + let outcome = neighbors.on_link_status(own, router, new, 40, &link_status, now, ACTIVITY); assert_eq!(outcome, LinkStatusOutcome::default()); } @@ -1019,6 +1073,7 @@ mod test { 200, &listing, Instant::from_micros(0), + ACTIVITY, ); let empty = NwkLinkStatusCommand { @@ -1027,12 +1082,89 @@ mod test { link_statuses: vec![], }; let later = Instant::from_micros(1); - let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, later); + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &empty, later, ACTIVITY); - assert_eq!(outcome, LinkStatusOutcome::default()); + assert_eq!(outcome.lost_link, None); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 1); } + #[test] + fn test_link_status_from_unknown_router_makes_ours_due() { + let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); + let (own, router_nwk) = (Nwk(0x0000), Nwk(0x1111)); + let now = Instant::from_micros(0); + let empty = link_status_frame(true, true, &[]); + let mut neighbors = Neighbors::default(); + + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ACTIVITY); + assert_eq!( + outcome, + LinkStatusOutcome { + lost_link: None, + replaced_address: None, + link_status_due: true, + link_status_answer_due: true, + } + ); + + // The router is known now: its empty list is still owed an answer + let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &empty, now, ACTIVITY); + assert_eq!( + outcome, + LinkStatusOutcome { + lost_link: None, + replaced_address: None, + link_status_due: false, + link_status_answer_due: true, + } + ); + + // Another unknown router makes one due too, whatever its list holds + let other = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:22"); + let listing = link_status_listing(own); + let outcome = + neighbors.on_link_status(own, other, Nwk(0x2222), 200, &listing, now, ACTIVITY); + assert!(outcome.link_status_due); + assert!(!outcome.link_status_answer_due); + } + + #[test] + fn test_first_frame_from_a_router_without_samples_makes_our_link_status_due() { + let mut neighbors = neighbors_with(NwkDeviceType::Router); + + assert!(neighbors.record_lqa(CHILD_NWK, 200)); + assert!(!neighbors.record_lqa(CHILD_NWK, 200)); + } + + #[test] + fn test_frames_from_other_senders_do_not_make_our_link_status_due() { + // An end device is never listed + let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); + assert!(!neighbors.record_lqa(CHILD_NWK, 200)); + + // Neither is a sender without a neighbor entry + assert!(!neighbors.record_lqa(Nwk(0x2222), 200)); + } + + #[test] + fn test_link_status_from_a_heard_end_device_makes_ours_due() { + // A child restored without its device type is loaded as an end device + let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); + neighbors.record_lqa(CHILD_NWK, 200); + + let outcome = neighbors.on_link_status( + Nwk(0x0000), + Eui64::from_hex("00:11:22:33:44:55:66:77"), + CHILD_NWK, + 200, + &link_status_listing(Nwk(0x0000)), + Instant::from_micros(0), + ACTIVITY, + ); + assert!(outcome.link_status_due); + } + #[test] fn test_link_status_leaving_us_out_zeroes_outgoing_cost() { let router = Eui64::from_hex("aa:bb:cc:dd:ee:ff:00:11"); @@ -1041,16 +1173,19 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status(own, router, router_nwk, 200, &listing, now); + neighbors.on_link_status(own, router, router_nwk, 200, &listing, now, ACTIVITY); let without_us = link_status_listing(Nwk(0x2222)); - let outcome = neighbors.on_link_status(own, router, router_nwk, 200, &without_us, now); + let outcome = + neighbors.on_link_status(own, router, router_nwk, 200, &without_us, now, ACTIVITY); assert_eq!( outcome, LinkStatusOutcome { lost_link: Some(router_nwk), replaced_address: None, + link_status_due: false, + link_status_answer_due: false, } ); assert_eq!(neighbors.link(router_nwk).unwrap().outgoing_cost, 0); @@ -1083,8 +1218,8 @@ mod test { let mut neighbors = Neighbors::default(); let listing = link_status_listing(own); - neighbors.on_link_status(own, router, router_nwk, 200, &listing, now); - neighbors.on_link_status(own, router, router_nwk, 200, frame, now); + neighbors.on_link_status(own, router, router_nwk, 200, &listing, now, ACTIVITY); + neighbors.on_link_status(own, router, router_nwk, 200, frame, now, ACTIVITY); neighbors.link(router_nwk).unwrap().outgoing_cost } @@ -1138,7 +1273,7 @@ mod test { |neighbors: &Neighbors| neighbors.link(router_nwk).unwrap().incoming_cost; // One sample is the link quality, and the router is listed at once - neighbors.on_link_status(own, router, router_nwk, 200, &link_status, now); + neighbors.on_link_status(own, router, router_nwk, 200, &link_status, now, ACTIVITY); assert_eq!(incoming_cost(&neighbors), lqi_to_link_cost(200)); assert_eq!(neighbors.link_status_entries().len(), 1); @@ -1169,14 +1304,21 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 200, &link_status, now); - neighbors.on_link_status(own, other, contested, 200, &link_status, now); + neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); + neighbors.on_link_status(own, other, contested, 200, &link_status, now, ACTIVITY); // The router's link status from an address the other neighbor holds, or from // our own address, is an address conflict: the router keeps its entry's address for conflicting in [contested, own] { - let outcome = - neighbors.on_link_status(own, router, conflicting, 200, &link_status, now); + let outcome = neighbors.on_link_status( + own, + router, + conflicting, + 200, + &link_status, + now, + ACTIVITY, + ); assert_eq!(outcome, LinkStatusOutcome::default()); assert_eq!(neighbors.link(old).unwrap().eui64, router); assert_eq!(neighbors.link(contested).unwrap().eui64, other); @@ -1193,13 +1335,13 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 10, &link_status, now); + neighbors.on_link_status(own, router, old, 10, &link_status, now, ACTIVITY); // More samples than the window buffered under the new address: the ring wraps for lqi in [10, 20, 200, 220] { neighbors.record_lqa(new, lqi); } - neighbors.on_link_status(own, router, new, 220, &link_status, now); + neighbors.on_link_status(own, router, new, 220, &link_status, now, ACTIVITY); // The window is [20, 200, 220] and its oldest (20) is replaced next, giving // [200, 220, 30]: a scrambled order would replace 220 and drop the median to 30 @@ -1210,6 +1352,46 @@ mod test { ); } + fn inbound_activity(neighbors: &Neighbors) -> u8 { + let entry = neighbors.entries().next().unwrap(); + entry.router_inbound_activity.count() + } + + #[test] + fn test_new_neighbor_is_not_charged_for_time_before_it_existed() { + // Created a minute in: the minute before must not decay its counters + let created = Instant::from_micros(0) + Duration::from_secs(60); + let mut neighbors = Neighbors::default(); + neighbors.restore_child( + ChildDescriptor { + eui64: Eui64::from_hex("00:11:22:33:44:55:66:77"), + network_address: CHILD_NWK, + device_type: NwkDeviceType::Router, + rx_on_when_idle: true, + device_timeout: None, + relationship: Relationship::Child, + }, + created, + ACTIVITY, + ); + + neighbors.decay_activity(created + Duration::from_secs(1), ACTIVITY.period); + assert_eq!(inbound_activity(&neighbors), ACTIVITY.initial_count - 1); + } + + #[test] + fn test_use_is_not_charged_for_time_before_it() { + // By a minute in, the count the neighbor started with has decayed away + let used = Instant::from_micros(0) + Duration::from_secs(60); + let mut neighbors = neighbors_with(NwkDeviceType::Router); + neighbors.record_inbound_activity(CHILD_NWK, used, ACTIVITY.period); + neighbors.record_inbound_activity(CHILD_NWK, used, ACTIVITY.period); + + // The two uses lose only the second that follows them + neighbors.decay_activity(used + Duration::from_secs(1), ACTIVITY.period); + assert_eq!(inbound_activity(&neighbors), 1); + } + #[test] fn test_only_end_device_children_time_out() { let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); @@ -1223,6 +1405,7 @@ mod test { relationship: Relationship::Child, }, Instant::from_micros(0), + ACTIVITY, ); assert_eq!( @@ -1261,6 +1444,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), + ACTIVITY, ); // Still a child for parent duties while unauthenticated @@ -1288,6 +1472,7 @@ mod test { relationship: Relationship::UnauthenticatedChild, }, Instant::from_micros(0), + ACTIVITY, ); assert_eq!( relationship_of(&neighbors, eui64), diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index 49c92b8c..f0ce768e 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -2,6 +2,7 @@ use crate::flat_map::FlatMap; use alloc::vec::Vec; use crate::Instant; +use crate::nwk::activity::{Activity, ActivityParams, take_decay_steps}; use crate::nwk::commands::NwkRouteRequestManyToOne; use core::time::Duration; use ziggurat_ieee_802154::types::Nwk; @@ -69,11 +70,16 @@ pub struct TableEntry { /// used to forward a state packet towards its destination; and decremented /// unconditionally once every `nwkLinkStatusPeriod`. A value of 0 indicates no /// packets have recently been forwarded along this route. - pub recent_activity: u8, + pub recent_activity: Activity, } impl TableEntry { - const fn new(destination: Nwk, status: Status, next_hop_address: Nwk) -> Self { + const fn new( + destination: Nwk, + status: Status, + next_hop_address: Nwk, + activity: ActivityParams, + ) -> Self { Self { destination, status, @@ -84,7 +90,7 @@ impl TableEntry { next_hop_address, path_cost: u8::MAX, total_usage_count: 0, - recent_activity: 0, + recent_activity: Activity::new(activity.initial_count), } } @@ -248,6 +254,9 @@ pub struct Routing { /// originating in a particular router; the latter is used to identify stale routing /// information." request_sequence_number: RouteRequestId, + + /// Up to when `recent_activity` has been decayed + activity_decayed_at: Instant, } impl Routing { @@ -335,7 +344,10 @@ impl Routing { now: Instant, route_discovery_time: Duration, attempts: u8, + activity: ActivityParams, ) -> Option { + self.decay_activity(now, activity.period); + if self.discoveries_left.contains_key(&destination) { return None; } @@ -347,7 +359,13 @@ impl Routing { return None; } - Some(self.begin_discovery(own_address, destination, now, route_discovery_time)) + Some(self.begin_discovery( + own_address, + destination, + now, + route_discovery_time, + activity, + )) } /// Decide what becomes of each destination our frames wait for a route to. @@ -358,8 +376,11 @@ impl Routing { own_address: Nwk, now: Instant, route_discovery_time: Duration, + activity: ActivityParams, wanted: impl Fn(Nwk) -> bool, ) -> DiscoveryTick { + self.decay_activity(now, activity.period); + let mut tick = DiscoveryTick::default(); self.expire_discoveries(now); @@ -381,8 +402,13 @@ impl Routing { // route was lost before the frame could use it if *discoveries_left > 0 { *discoveries_left -= 1; - let request_id = - self.begin_discovery(own_address, destination, now, route_discovery_time); + let request_id = self.begin_discovery( + own_address, + destination, + now, + route_discovery_time, + activity, + ); tick.restarted.push((destination, request_id)); true } else { @@ -405,20 +431,27 @@ impl Routing { } /// A frame was forwarded along the route: bump its usage counters. - pub fn record_usage(&mut self, destination: Nwk) { + pub fn record_usage(&mut self, destination: Nwk, now: Instant, period: Duration) { + self.decay_activity(now, period); + if let Some(entry) = self.route_table.get_mut(&destination) { - entry.recent_activity = entry.recent_activity.saturating_add(1); + entry.recent_activity.record_use(); entry.total_usage_count = entry.total_usage_count.saturating_add(1); } } - /// Called once per `nwkLinkStatusPeriod`: decrement the `recent_activity` field of - /// every active routing table entry. - pub fn decay_activity(&mut self) { + /// Decay the `recent_activity` of every routing table entry by the time passed + /// since the last call, at one count per `period` (`nwkLinkStatusPeriod`). + pub fn decay_activity(&mut self, now: Instant, period: Duration) { + let steps = take_decay_steps(&mut self.activity_decayed_at, now, period); + + if steps == 0 { + return; + } + + // Spec Table 3-77: "decremented unconditionally", whatever the route's status for entry in self.route_table.values_mut() { - if entry.status == Status::Active { - entry.recent_activity = entry.recent_activity.saturating_sub(1); - } + entry.recent_activity.decay(steps); } } @@ -448,7 +481,9 @@ impl Routing { } /// The device at `nwk` left or joined again, clear associated state. - pub fn forget(&mut self, own_address: Nwk, nwk: Nwk) { + pub fn forget(&mut self, own_address: Nwk, nwk: Nwk, now: Instant, activity: ActivityParams) { + self.decay_activity(now, activity.period); + self.route_table.remove(&nwk); self.route_record_table.remove(&nwk); self.discoveries_left.remove(&nwk); @@ -471,15 +506,24 @@ impl Routing { { self.route_table.insert( nwk, - TableEntry::new(nwk, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP), + TableEntry::new(nwk, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP, activity), ); } } /// Seed an active routing entry restored by the client on startup. Unlike a route /// learned at runtime, this does not record a change (the client already has it). - pub fn restore_route(&mut self, destination: Nwk, next_hop: Nwk, path_cost: u8) { - let mut entry = TableEntry::new(destination, Status::Active, next_hop); + pub fn restore_route( + &mut self, + destination: Nwk, + next_hop: Nwk, + path_cost: u8, + now: Instant, + activity: ActivityParams, + ) { + self.decay_activity(now, activity.period); + + let mut entry = TableEntry::new(destination, Status::Active, next_hop, activity); entry.path_cost = path_cost; self.route_table.insert(destination, entry); } @@ -571,16 +615,16 @@ impl Routing { destination: Nwk, now: Instant, route_discovery_time: Duration, + activity: ActivityParams, ) -> RouteRequestId { // Expire stale discoveries before establishing the new one. A just-expired // discovery toward this same destination would otherwise tear down the // `DiscoveryUnderway` route entry created below. self.expire_discoveries(now); - let route_table_entry = self - .route_table - .entry(destination) - .or_insert_with(|| TableEntry::new(destination, Status::Inactive, UNKNOWN_NEXT_HOP)); + let route_table_entry = self.route_table.entry(destination).or_insert_with(|| { + TableEntry::new(destination, Status::Inactive, UNKNOWN_NEXT_HOP, activity) + }); route_table_entry.status = Status::DiscoveryUnderway; self.request_sequence_number = self.request_sequence_number.wrapping_add(1); @@ -656,7 +700,10 @@ impl Routing { many_to_one: NwkRouteRequestManyToOne, now: Instant, route_discovery_time: Duration, + activity: ActivityParams, ) -> RouteRequestOutcome { + self.decay_activity(now, activity.period); + self.expire_discoveries(now); let fresh = match self.discovery_table.get_mut(&(originator, request_id)) { @@ -701,10 +748,9 @@ impl Routing { // Spec 3.6.4.5.1.2: the route back to the originator runs through the device we // accepted the request from, subject to the 3.6.4.5.3 suitability rule. - let originator_entry = self - .route_table - .entry(originator) - .or_insert_with(|| TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP)); + let originator_entry = self.route_table.entry(originator).or_insert_with(|| { + TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP, activity) + }); let route_changed = originator_entry.consider_route(sender, updated_path_cost); @@ -740,7 +786,14 @@ impl Routing { /// Before relaying a route request: mark the destination's entry as /// `DiscoveryUnderway`, so the reply we relay back finds it (spec 3.6.4.5.1.2). - pub fn note_relayed_discovery(&mut self, destination: Nwk) { + pub fn note_relayed_discovery( + &mut self, + destination: Nwk, + now: Instant, + activity: ActivityParams, + ) { + self.decay_activity(now, activity.period); + self.route_table .entry(destination) .and_modify(|entry| { @@ -749,7 +802,12 @@ impl Routing { } }) .or_insert_with(|| { - TableEntry::new(destination, Status::DiscoveryUnderway, UNKNOWN_NEXT_HOP) + TableEntry::new( + destination, + Status::DiscoveryUnderway, + UNKNOWN_NEXT_HOP, + activity, + ) }); } @@ -766,7 +824,10 @@ impl Routing { sender: Nwk, updated_path_cost: u8, now: Instant, + activity: ActivityParams, ) -> RouteReplyOutcome { + self.decay_activity(now, activity.period); + // A reply to a discovery that has lapsed finds no entry and is dropped self.expire_discoveries(now); @@ -857,10 +918,9 @@ impl Routing { // Spec 3.6.4.5.2.1: relaying the reply also establishes the reverse route // toward the originator of the route request, subject to the 3.6.4.5.3 // suitability rule so a worse path never replaces a good ACTIVE route. - let reverse_entry = self - .route_table - .entry(originator) - .or_insert_with(|| TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP)); + let reverse_entry = self.route_table.entry(originator).or_insert_with(|| { + TableEntry::new(originator, Status::Inactive, UNKNOWN_NEXT_HOP, activity) + }); let update = reverse_entry .consider_route(next_hop, forward_cost) diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 28909239..2fcc1c1a 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -18,6 +18,11 @@ const NEIGHBOR: Nwk = Nwk(0x4444); const START: Instant = Instant::from_micros(0); const ROUTE_DISCOVERY_TIME: Duration = Duration::from_secs(10); const MAX_SOURCE_ROUTE: u8 = 11; +const ROUTER_AGE_LIMIT: u8 = 3; +const ACTIVITY: ActivityParams = ActivityParams { + initial_count: ROUTER_AGE_LIMIT, + period: Duration::from_secs(15), +}; /// A route request relayed to us by `NEIGHBOR`. #[derive(Clone, Copy)] @@ -39,6 +44,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { NwkRouteRequestManyToOne::NotManyToOne, now, ROUTE_DISCOVERY_TIME, + ACTIVITY, ) .accepted } @@ -48,7 +54,7 @@ fn receive(routing: &mut Routing, request: RouteRequest, now: Instant) -> bool { #[test] fn test_forget_drops_our_discovery_toward_the_device() { let mut routing = Routing::default(); - routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME); + routing.begin_discovery(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, ACTIVITY); assert_eq!( routing.own_discovery_lapse(OWN, DEVICE, START), Some(START + ROUTE_DISCOVERY_TIME) @@ -58,20 +64,47 @@ fn test_forget_drops_our_discovery_toward_the_device() { Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.own_discovery_lapse(OWN, DEVICE, START), None); assert_eq!(routing.route_status(DEVICE), None); } +#[test] +fn test_recent_activity_decays_on_an_inactive_route() { + let period = Duration::from_secs(15); + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.invalidate_via(NEIGHBOR); + assert_eq!(routing.route_status(DEVICE), Some(Status::Inactive)); + + routing.decay_activity(START + period, period); + + let entry = routing.entries().next().unwrap(); + assert_eq!(entry.recent_activity, Activity::new(ROUTER_AGE_LIMIT - 1)); +} + +#[test] +fn test_new_route_is_not_charged_for_time_before_it_existed() { + // Created a minute in: the minute before must not decay its counter + let created = START + Duration::from_secs(60); + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, created, ACTIVITY); + + routing.decay_activity(created + Duration::from_secs(1), ACTIVITY.period); + + let entry = routing.entries().next().unwrap(); + assert_eq!(entry.recent_activity.count(), ROUTER_AGE_LIMIT - 1); +} + #[test] fn test_forget_drops_the_route_and_the_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); routing.store_route_record(DEVICE, vec![ROUTER]); assert!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE).is_some()); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!(routing.route_to(DEVICE, MAX_SOURCE_ROUTE), None); @@ -80,10 +113,10 @@ fn test_forget_drops_the_route_and_the_route_record() { #[test] fn test_forget_leaves_other_destinations_alone() { let mut routing = Routing::default(); - routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3); - routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.begin_discovery(OWN, ROUTER, START, ROUTE_DISCOVERY_TIME, ACTIVITY); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(OTHER_DEVICE), Some(NEIGHBOR)); assert_eq!( @@ -105,7 +138,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_the_device_originated() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); let late_copy = RouteRequest { path_cost: 7, @@ -124,7 +157,7 @@ fn test_forget_keeps_the_duplicate_check_for_a_request_toward_the_device() { }; assert!(receive(&mut routing, request, START)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); let late_copy = RouteRequest { path_cost: 7, @@ -145,15 +178,15 @@ fn test_forget_keeps_a_relayed_discovery_toward_the_device_answerable() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) ); - let reply = routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START); + let reply = routing.accept_route_reply(OWN, ROUTER, 1, DEVICE, DEVICE, 1, START, ACTIVITY); assert_eq!( reply.disposition, RouteReplyDisposition::Relay { @@ -174,10 +207,10 @@ fn test_forget_placeholder_for_a_relayed_discovery_expires_with_it() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.restore_route(DEVICE, OTHER_DEVICE, 3); - routing.note_relayed_discovery(DEVICE); + routing.restore_route(DEVICE, OTHER_DEVICE, 3, START, ACTIVITY); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_hop(DEVICE), None); assert_eq!( routing.route_status(DEVICE), @@ -208,13 +241,13 @@ fn test_relayed_discovery_still_expires_after_its_originator_is_forgotten() { path_cost: 5, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(OTHER_DEVICE); + routing.note_relayed_discovery(OTHER_DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(OTHER_DEVICE), Some(Status::DiscoveryUnderway) ); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); // Any later request runs the expiry let unrelated = RouteRequest { @@ -278,7 +311,7 @@ fn test_unchanged_route_record_reports_a_relay_route_it_restores() { fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { for relays in [vec![], vec![ROUTER]] { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); routing.store_route_record(DEVICE, relays); assert!(routing.forget_route_to(DEVICE)); @@ -289,7 +322,7 @@ fn test_forget_route_to_drops_the_route_record_and_the_routing_entry() { #[test] fn test_forget_route_to_reports_only_a_removed_route_record() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); assert!(!routing.forget_route_to(DEVICE)); assert_eq!(routing.next_hop(DEVICE), None); @@ -311,13 +344,13 @@ fn test_forget_route_to_leaves_other_destinations_alone() { /// A frame of ours wants a route to `DEVICE`. Returns whether that starts a discovery. fn want(routing: &mut Routing, now: Instant, attempts: u8) -> bool { routing - .want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts) + .want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY) .is_some() } /// Run a timer pass, with a frame still waiting for the route or not. fn tick(routing: &mut Routing, now: Instant, wanted: bool) -> DiscoveryTick { - routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, |_| wanted) + routing.tick_discoveries(OWN, now, ROUTE_DISCOVERY_TIME, ACTIVITY, |_| wanted) } #[test] @@ -423,7 +456,7 @@ fn test_relayed_discovery_toward_the_destination_is_not_ours() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert!(want(&mut routing, START, 1)); } @@ -454,11 +487,11 @@ fn test_relayed_discovery_does_not_keep_ours_alive() { #[test] fn test_removing_the_route_keeps_a_discovery_underway() { let mut routing = Routing::default(); - routing.restore_route(DEVICE, NEIGHBOR, 3); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); assert!(routing.remove_route(DEVICE)); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); assert!(!routing.remove_route(DEVICE)); assert!(!routing.forget_route_to(DEVICE)); @@ -470,13 +503,13 @@ fn test_removing_the_route_keeps_a_discovery_underway() { /// `DEVICE` answers our route request through `NEIGHBOR`. fn reply(routing: &mut Routing, request_id: RouteRequestId, now: Instant) -> RouteReplyOutcome { - routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, 3, now) + routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, 3, now, ACTIVITY) } /// Start a discovery toward `DEVICE` and have the device answer it. fn answered_discovery(routing: &mut Routing, attempts: u8) { let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, attempts) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY) .unwrap(); let reply = reply(routing, request_id, START); @@ -513,7 +546,7 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { path_cost: 3, }; assert!(receive(&mut routing, request, START)); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert_eq!( routing.route_status(DEVICE), Some(Status::DiscoveryUnderway) @@ -527,15 +560,24 @@ fn test_relayed_discovery_does_not_revive_our_answered_one() { fn test_reply_with_the_highest_path_cost_answers_the_discovery() { let mut routing = Routing::default(); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); - let reply = routing.accept_route_reply(OWN, OWN, request_id, DEVICE, NEIGHBOR, u8::MAX, START); + let reply = routing.accept_route_reply( + OWN, + OWN, + request_id, + DEVICE, + NEIGHBOR, + u8::MAX, + START, + ACTIVITY, + ); assert_eq!(reply.disposition, RouteReplyDisposition::Established); assert_eq!(tick(&mut routing, START, false), DiscoveryTick::default()); routing.invalidate_via(NEIGHBOR); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); assert!(want(&mut routing, START, 1)); } @@ -563,7 +605,7 @@ fn test_forget_ends_our_discovery_toward_the_device() { let mut routing = Routing::default(); assert!(want(&mut routing, START, 1)); - routing.forget(OWN, DEVICE); + routing.forget(OWN, DEVICE, START, ACTIVITY); assert_eq!(routing.next_discovery_lapse(OWN, START), None); assert!(want(&mut routing, START, 1)); @@ -575,7 +617,7 @@ fn test_forget_ends_our_discovery_toward_the_device() { fn test_reply_to_a_lapsed_discovery_is_dropped() { let mut routing = Routing::default(); let request_id = routing - .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1) + .want_route(OWN, DEVICE, START, ROUTE_DISCOVERY_TIME, 1, ACTIVITY) .unwrap(); let late = reply(&mut routing, request_id, START + ROUTE_DISCOVERY_TIME); @@ -670,7 +712,8 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { // The driver only holds a frame when it has no route Step::Hold if routing.next_hop(DEVICE).is_some() => {} Step::Hold => { - let started = routing.want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts); + let started = + routing.want_route(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, attempts, ACTIVITY); // Only the first frame to wait can start a discovery, and a discovery // of ours that is still underway serves it @@ -780,7 +823,7 @@ fn check_own_discovery(steps: &[Step], attempts: u8) { path_cost: 3, }; assert!(receive(&mut routing, request, now), "{steps:?}"); - routing.note_relayed_discovery(DEVICE); + routing.note_relayed_discovery(DEVICE, START, ACTIVITY); model.expire(); model.relayed_live = true; @@ -851,6 +894,7 @@ fn receive_copy(routing: &mut Routing, path_cost: u8) -> RouteRequestOutcome { NwkRouteRequestManyToOne::NotManyToOne, START, ROUTE_DISCOVERY_TIME, + ACTIVITY, ) } diff --git a/crates/ziggurat-zigbee/src/time.rs b/crates/ziggurat-zigbee/src/time.rs index 1049fa6a..28595510 100644 --- a/crates/ziggurat-zigbee/src/time.rs +++ b/crates/ziggurat-zigbee/src/time.rs @@ -6,7 +6,7 @@ use core::time::Duration; /// The sans-io core never reads a clock; the driver passes `now` in and converts its own /// platform clock (tokio, embassy, a sim) to and from this type at the boundary. Replacing /// `std::time::Instant` is what lets this crate build for `no_std` targets. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Instant { micros: u64, }