diff --git a/docs/cli-design.md b/docs/cli-design.md index e0b209176..c4d12efaf 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1869,7 +1869,11 @@ cannot honor the settings reports a capacity error in the section 6 form. ### Experimental RoCE ring configuration `ignition export` and `ignition debug-serve` accept `--roce-ring` or `--roce-chain` with `--ranks N`; -`flare run` and `flare orbit run` accept it with a multi-host core. Rank +`flare run`, `flare orbit run`, and `flare orbit push` accept `--roce-ring`, `--roce-chain`, or +`--roce-hairpin` with a multi-host core (mutually exclusive). `--roce-hairpin` opens direct +all-to-all RoCEv2 queue pairs over a switchless physical ring configured with ConnectX-7 NIC-level +hardware hairpin (`skip_sw` `in_hw`), without native CPU proxy relaying, while keeping +neighbor-relayed TCP paths for core distribution. Rank order defines the ring, including the cluster's node order when agents launch ranks. The transport accepts 2..16 ranks, while recipe validation retains each model's supported TP sizes. This diff --git a/docs/roce-ring.md b/docs/roce-ring.md index 810bd03e8..a7731b1fe 100644 --- a/docs/roce-ring.md +++ b/docs/roce-ring.md @@ -26,8 +26,11 @@ authenticated agent sessions and signed grants. See [core transfers](orbit.md#core-transfers-through-fabric-interfaces). The ring can run over a switch or hosts cabled directly to their neighbors. -Forwarding runs on host CPUs; ConnectX hardware hairpin forwarding is not -implemented. +With `--roce-ring` or `--roce-chain`, forwarding runs on host CPUs through the +native proxy. With `--roce-hairpin`, every rank opens direct RoCEv2 queue pairs +to every peer without CPU proxy relaying, relying on ConnectX-7 NIC-level +hardware hairpin (`skip_sw` `in_hw`) configured on intermediate hosts to forward +non-neighbor RoCEv2 packets between physical ports. ## Rank order and routes @@ -397,6 +400,54 @@ and reserves zero as the healthy error sentinel. It applies to mesh and ring routing, independently of the number of model steps or requests. Sequence wrap is unsupported; restarting the proxy thread alone does not reset the runtime. +## Hardware-hairpin ring (`--roce-hairpin`) + +`--roce-hairpin` (mutually exclusive with `--roce-ring` and `--roce-chain`) +targets switchless physical rings whose intermediate ConnectX-7 NICs forward +non-neighbor RoCEv2 UDP/4791 packets directly in hardware (`tc flower skip_sw` +`in_hw`), bypassing host CPU and PCIe relay hops. + +### Route planning and proxy behavior + +- Every rank opens direct RC queue pairs to every peer (`Shape::HairpinRing` + with `relays() == false`), using the unmodified native RoCE proxy ABI and + existing exported cores without re-export. +- Direct ring neighbors (`(rank + 1) % N` and `(rank + N - 1) % N`) use their + physical point-to-point cable links, matching `--roce-ring`. +- Non-neighbor peers pair each rank's arc-entry device with the peer's arc-exit + device along the shorter arc around the cycle. +- On equal-length arcs (diagonals `0 <-> 2` and `1 <-> 3` in a 4-Spark ring), + a two-rail topology splits traffic across both arcs: Rail 0 crosses the + clockwise arc and Rail 1 crosses the counter-clockwise arc, choosing rail + slots that keep PCIe links and physical ports disjoint at both ends. +- Bulk TCP core distribution (`flare-cli/src/fabric.rs`) retains neighbor-relayed + ring paths so NIC hairpin rules need only offload RoCEv2 traffic. + +### Host setup and verification + +Flare does not modify host NIC switchdev mode, `tc` offload filters, static +routes, or ARP tables. Configure and verify hardware hairpin on each ring node +before launching `flare run --roce-hairpin` or `flare orbit run --roce-hairpin`. + +[scripts/setup_cx7_hairpin_ring.sh](../scripts/setup_cx7_hairpin_ring.sh) +generates (dry-run by default), applies (`--apply`), verifies (`--verify`), or +removes (`--teardown`) the per-node ConnectX-7 `tc flower skip_sw` L3 hairpin +rules (`pedit` MAC rewrite plus `mirred egress redirect`) and static `/32` +routes and permanent neighbor entries for a 4-node ring. + +Before running model traffic, confirm: + +1. Every intermediate node's transit filter reports `in_hw` in + `tc -s filter show dev ingress` (no software fallback). +2. Direct 2-hop RDMA latency (`ib_write_lat -d -x 3 `) + succeeds across both diagonal pairs (`0 <-> 2` and `1 <-> 3`) on both arcs + with zero dropped or retransmitted packets. +3. Priority flow control (PFC) on TC 0 remains active on all ring ports. + +Physical switchless 4-Spark hardware validation of `--roce-hairpin` is pending; +unit tests cover route symmetry, PCIe-link and physical-port separation, proxy +preflight, CLI forwarding, and Orbit grant validation. + ## Failures | Symptom | Check | diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 8981d380f..fe14d15a5 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -516,6 +516,10 @@ pub struct OrbitPush { #[arg(long, conflicts_with = "roce_ring")] pub roce_chain: bool, + /// Stream core data through fabric interfaces in hardware-hairpin ring order. + #[arg(long, conflicts_with_all = ["roce_ring", "roce_chain"])] + pub roce_hairpin: bool, + /// Parallel TCP streams per destination file over the fabric [default: 8]. #[arg(long, value_name = "N", value_parser = clap::value_parser!(u8).range(1..=64))] pub transfer_streams: Option, @@ -535,6 +539,7 @@ impl OrbitPush { no_advertise: false, roce_ring: self.roce_ring, roce_chain: self.roce_chain, + roce_hairpin: self.roce_hairpin, rendezvous: None, rank: None, hosts: Vec::new(), @@ -624,6 +629,16 @@ pub struct OrbitRun { )] pub roce_chain: bool, + /// Experimental hardware-hairpin ring in rank order: hosts cabled in a ring with ConnectX-7 + /// NIC-level hardware hairpin (`skip_sw` `in_hw`); all ranks open direct RoCE QPs without CPU + /// proxy relaying. + #[arg( + long, + conflicts_with_all = ["roce_ring", "roce_chain"], + help_heading = "Multi-host options" + )] + pub roce_hairpin: bool, + /// IP address for rank zero's HTTP server [default: saved group or 127.0.0.1]. #[arg(long, value_name = "ADDR", help_heading = "Serving options")] pub host: Option, @@ -724,6 +739,7 @@ impl OrbitRun { no_advertise: self.no_advertise, roce_ring: self.roce_ring, roce_chain: self.roce_chain, + roce_hairpin: self.roce_hairpin, rendezvous: None, rank: None, hosts: Vec::new(), @@ -808,6 +824,16 @@ pub struct Run { )] pub roce_chain: bool, + /// Experimental hardware-hairpin ring in rank order: hosts cabled in a ring with ConnectX-7 + /// NIC-level hardware hairpin (`skip_sw` `in_hw`); all ranks open direct RoCE QPs without CPU + /// proxy relaying. + #[arg( + long, + conflicts_with_all = ["roce_ring", "roce_chain"], + help_heading = "Multi-host options" + )] + pub roce_hairpin: bool, + /// Rank zero's rendezvous address: where rank zero listens, or on a peer, where it joins rank zero. #[arg(long, value_name = "HOST:PORT", help_heading = "Multi-host options")] pub rendezvous: Option, @@ -1125,8 +1151,11 @@ impl Run { /// graphs and capacities on every host. #[cfg(test)] pub fn rank_options(&self) -> Vec { - self.serving - .rank_options(Shape::from_flags(self.roce_ring, self.roce_chain)) + self.serving.rank_options(Shape::from_flags( + self.roce_ring, + self.roce_chain, + self.roce_hairpin, + )) } pub fn load_options(&self) -> LoadOptions { @@ -1154,6 +1183,7 @@ impl ServingOptions { Shape::Mesh => {} Shape::Ring => options.push("--roce-ring".into()), Shape::Chain => options.push("--roce-chain".into()), + Shape::HairpinRing => options.push("--roce-hairpin".into()), } if self.roce_switch_only { options.push(ROCE_SWITCH_ONLY.into()); @@ -1865,6 +1895,38 @@ mod tests { assert_eq!(args.rank_options(), vec!["--roce-ring"]); } + #[test] + fn hairpin_flag_is_forwarded_and_excludes_ring_and_chain() { + let args = run(&["flare", "run", "model.safetensors", "--roce-hairpin"]); + assert!(args.roce_hairpin && !args.roce_ring && !args.roce_chain); + assert_eq!(args.rank_options(), vec!["--roce-hairpin"]); + assert!( + Cli::try_parse_from(["flare", "run", "m.safetensors", "--roce-hairpin", "--roce-ring"]) + .is_err() + ); + assert!( + Cli::try_parse_from([ + "flare", + "run", + "m.safetensors", + "--roce-hairpin", + "--roce-chain", + ]) + .is_err() + ); + assert!( + Cli::try_parse_from([ + "flare", + "orbit", + "run", + "m.safetensors", + "--roce-hairpin", + "--roce-ring", + ]) + .is_err() + ); + } + #[test] fn switch_only_flag_is_forwarded_to_every_agent_started_rank() { let args = run(&["flare", "run", "model.safetensors", "--roce-switch-only"]); diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 3531faecc..b570d2aae 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -100,6 +100,7 @@ fn connected(transport: &RoceTransport) -> String { Shape::Mesh => "peer", Shape::Ring => "neighbor (experimental CPU relay ring)", Shape::Chain => "neighbor (experimental CPU relay chain)", + Shape::HairpinRing => "peer (experimental hardware-hairpin ring)", }, match topology.links { Links::All => "", @@ -110,8 +111,8 @@ fn connected(transport: &RoceTransport) -> String { } /// The transport shape a rank was started with and the links it may route over, as the ranks -/// exchange them before planning routes: `mesh`, `ring` or `chain`, followed by ` switch-only` -/// when direct cables are excluded. +/// exchange them before planning routes: `mesh`, `ring`, `chain`, or `hairpin-ring`, followed by +/// ` switch-only` when direct cables are excluded. #[cfg(all(target_os = "linux", any(target_arch = "aarch64", feature = "roce")))] fn shape_record(routing: Routing) -> Vec { let links = match routing.links { @@ -331,6 +332,13 @@ mod routing_tests { }; assert_eq!(shape_record(mesh), b"mesh"); assert_eq!(shape_record(switched), b"mesh switch-only"); + let hairpin = Routing { + shape: Shape::HairpinRing, + links: Links::All, + }; + assert_eq!(shape_record(hairpin), b"hairpin-ring"); + assert!(agree_shape(&vec![shape_record(hairpin); 4], hairpin).is_ok()); + assert!(agree_shape(&[shape_record(hairpin), shape_record(mesh)], hairpin).is_err()); assert!(agree_shape(&vec![shape_record(switched); 2], switched).is_ok()); let error = agree_shape(&[shape_record(mesh), shape_record(switched)], mesh) .unwrap_err() diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index e3fb73192..34186090d 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -238,6 +238,7 @@ pub fn root( &endpoints.iter().map(|e| e.port).collect::>(), args.roce_ring, args.roce_chain, + args.roce_hairpin, args.serving.roce_switch_only, )?; let relay = Relay::start(0, streams, topology.clone(), network, source.port)?; @@ -396,6 +397,9 @@ pub fn peer(args: &mut Run, progress: &mut StartupProgress) -> Result Result>>, } @@ -47,11 +49,13 @@ pub fn discover() -> Result, Failure> { impl Topology { #[cfg(test)] pub fn plan(records: &[Vec], ports: &[u16], ring: bool) -> Result { - Self::plan_shape(records, ports, ring, false, false) + Self::plan_shape(records, ports, ring, false, false, false) } - /// Plans direct, ring or chain links; at most one of `ring` and `chain` is set. Each edge uses - /// the devices the RDMA transport routes between the same two ranks, planned over every rank's + /// Plans direct, ring, chain, or hairpin-ring links; at most one of `ring`, `chain`, and + /// `hairpin` is set. Hairpin rings keep neighbor-relayed TCP links for core distribution so + /// ConnectX-7 hardware hairpin filters need only forward RoCEv2 traffic. Each edge uses the + /// devices the RDMA transport routes between the same two ranks, planned over every rank's /// endpoints: a cabled partner over its cable, other peers over the switch, and with /// `switch_only` every peer over subnets that every rank holds. pub fn plan_shape( @@ -59,11 +63,13 @@ impl Topology { ports: &[u16], ring: bool, chain: bool, + hairpin: bool, switch_only: bool, ) -> Result { - if ring && chain { - return Err("fabric transfers use a ring or a chain, not both".into()); + if usize::from(ring) + usize::from(chain) + usize::from(hairpin) > 1 { + return Err("fabric transfers select at most one of ring, chain, or hairpin".into()); } + let ring_links = ring || hairpin; let world = records.len(); if !(2..=16).contains(&world) || ports.len() != world || ports.contains(&0) { return Err("fabric transfers need 2..16 ranks and their listener ports".into()); @@ -76,7 +82,7 @@ impl Topology { let mut links = vec![vec![Vec::new(); world]; world]; for from in 0..world { for to in from + 1..world { - if ring && to != from + 1 && !(from == 0 && to == world - 1) { + if ring_links && to != from + 1 && !(from == 0 && to == world - 1) { continue; } if chain && to != from + 1 { @@ -113,6 +119,7 @@ impl Topology { let topology = Self { ring, chain, + hairpin, switch_only, links, }; @@ -125,13 +132,14 @@ impl Topology { if !(2..=16).contains(&world) || self.links.iter().any(|row| row.len() != world) { return Err("invalid fabric topology dimensions".into()); } - if self.ring && self.chain { - return Err("fabric topology is both a ring and a chain".into()); + if usize::from(self.ring) + usize::from(self.chain) + usize::from(self.hairpin) > 1 { + return Err("fabric topology selects more than one of ring, chain, or hairpin".into()); } + let ring_links = self.ring || self.hairpin; for from in 0..world { for to in 0..world { let connected = from != to - && (!self.ring || to == (from + 1) % world || from == (to + 1) % world); + && (!ring_links || to == (from + 1) % world || from == (to + 1) % world); let connected = connected && (!self.chain || from.abs_diff(to) == 1); let links = &self.links[from][to]; if connected != !links.is_empty() || links.len() > roce_fabric::MAX_RAILS { @@ -171,7 +179,7 @@ impl Topology { (destination..=source).rev().collect() }); } - if !self.ring { + if !(self.ring || self.hairpin) { return Ok(vec![source, destination]); } let clockwise = (destination + world - source) % world; @@ -270,7 +278,7 @@ mod tests { #[test] fn transfer_links_follow_the_partner_cable_or_the_switch_when_switch_only() { let records = switch_with_partner_cables(); - let topology = Topology::plan_shape(&records, &[29900; 4], false, false, false).unwrap(); + let topology = Topology::plan_shape(&records, &[29900; 4], false, false, false, false).unwrap(); // Each partner uses both cable functions, one on each PCIe root port; the rest use the switch. assert_eq!(third_octets(&topology, 1, 2), [2, 3]); assert_eq!(third_octets(&topology, 0, 3), [4, 5]); @@ -280,7 +288,7 @@ mod tests { let encoded = serde_json::to_string(&topology).unwrap(); assert!(!encoded.contains("switch_only"), "{encoded}"); - let switched = Topology::plan_shape(&records, &[29900; 4], false, false, true).unwrap(); + let switched = Topology::plan_shape(&records, &[29900; 4], false, false, false, true).unwrap(); for (from, to) in [(1, 2), (0, 3), (1, 0), (2, 3)] { assert_eq!(third_octets(&switched, from, to), [0, 1], "{from} to {to}"); } @@ -328,7 +336,7 @@ mod tests { .map(|rank| format!("a 10.0.0.{rank}/24 -\n").into_bytes()) .collect::>(); let topology = - Topology::plan_shape(&records, &vec![29900; world], false, true, false).unwrap(); + Topology::plan_shape(&records, &vec![29900; world], false, true, false, false).unwrap(); assert_eq!(topology.links[0][world - 1].is_empty(), world > 2); for source in 0..world { for destination in 0..world { @@ -357,11 +365,14 @@ mod tests { "b 10.0.2.2/24 -\n", ] .map(|s| s.as_bytes().to_vec()); - let topology = Topology::plan_shape(&records, &[29900; 4], false, true, false).unwrap(); + let topology = Topology::plan_shape(&records, &[29900; 4], false, true, false, false).unwrap(); assert_eq!(topology.path(3, 0).unwrap(), [3, 2, 1, 0]); assert!(topology.hop(0, 3, 0).is_err()); assert!(Topology::plan(&records, &[29900; 4], true).is_err()); - assert!(Topology::plan_shape(&records, &[29900; 4], true, true, false).is_err()); + assert!(Topology::plan_shape(&records, &[29900; 4], true, true, false, false).is_err()); + assert!(Topology::plan_shape(&records, &[29900; 4], true, false, true, false).is_err()); + assert!(Topology::plan_shape(&records, &[29900; 4], false, true, true, false).is_err()); + assert!(Topology::plan_shape(&records, &[29900; 4], false, false, true, false).is_err()); let mut both = topology.clone(); both.ring = true; assert!(both.validate().is_err()); @@ -369,4 +380,28 @@ mod tests { direct.chain = false; assert!(direct.validate().is_err()); } + + #[test] + fn hairpin_ring_uses_neighbor_relays_for_tcp_distribution() { + let records: Vec> = (0..4) + .map(|rank| { + let prev = (rank + 3) % 4; + format!( + "p0f0 10.{}.0.1/30 -\np0f1 10.{}.1.1/30 -\np1f0 10.{}.0.2/30 -\np1f1 10.{}.1.2/30 -\n", + rank + 1, + rank + 1, + prev + 1, + prev + 1 + ) + .into_bytes() + }) + .collect(); + let hairpin = + Topology::plan_shape(&records, &[29900; 4], false, false, true, false).unwrap(); + assert!(hairpin.hairpin && !hairpin.ring && !hairpin.chain); + assert_eq!(hairpin.path(0, 2).unwrap(), vec![0, 1, 2]); + assert_eq!(hairpin.path(0, 3).unwrap(), vec![0, 3]); + assert!(hairpin.links[0][2].is_empty()); + assert_eq!(hairpin.links[0][1].len(), 2); + } } diff --git a/flare-cli/src/fabric_transport.rs b/flare-cli/src/fabric_transport.rs index 9c091be00..161fbb82c 100644 --- a/flare-cli/src/fabric_transport.rs +++ b/flare-cli/src/fabric_transport.rs @@ -322,7 +322,8 @@ pub fn run(path: &Path) -> Result<(), Failure> { } let ports = endpoints.iter().map(|e| e.port).collect::>(); let records = endpoints.into_iter().map(|e| e.record).collect::>(); - let topology = Topology::plan_shape(&records, &ports, config.ring, config.chain, false)?; + let topology = + Topology::plan_shape(&records, &ports, config.ring, config.chain, false, false)?; network.set_nonblocking(true)?; local_listener.set_nonblocking(true)?; reply(serde_json::json!({"ready": true}))?; @@ -499,7 +500,8 @@ mod tests { .map(|s| s.local_addr().unwrap().port()) .collect::>(); let records = vec![b"a 127.0.0.1/8 -\n".to_vec(); world]; - let topology = Topology::plan_shape(&records, &ports, ring, chain, false).unwrap(); + let topology = + Topology::plan_shape(&records, &ports, ring, chain, false, false).unwrap(); let stopping = AtomicBool::new(false); let streams = 4; thread::scope(|scope| { diff --git a/flare-cli/src/launch.rs b/flare-cli/src/launch.rs index 10f01b149..1f3ff5a5a 100644 --- a/flare-cli/src/launch.rs +++ b/flare-cli/src/launch.rs @@ -154,6 +154,7 @@ impl Peers { rank_zero: Vec::new(), roce_ring: args.roce_ring, roce_chain: args.roce_chain, + roce_hairpin: args.roce_hairpin, transfer_fabric: None, single_host: false, issued, diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index 0261de211..ace758ee4 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -190,6 +190,7 @@ fn run() -> Result> { || !args.hosts.is_empty() || args.roce_ring || args.roce_chain + || args.roce_hairpin { return Err("multi-host serving is not supported on Windows".into()); } @@ -260,8 +261,11 @@ fn run() -> Result> { return Err("--rendezvous applies only to a multi-host core".into()); } (None, None) => { - if args.roce_ring || args.roce_chain { - return Err("--roce-ring and --roce-chain require a multi-host core".into()); + if args.roce_ring || args.roce_chain || args.roce_hairpin { + return Err( + "--roce-ring, --roce-chain, and --roce-hairpin require a multi-host core" + .into(), + ); } None } @@ -296,7 +300,7 @@ fn run() -> Result> { let local_devices: Vec = (0..args.gpus.len() as i32).collect(); let bypass_performance_check = args.bypass_performance_check; let routing = cluster::Routing { - shape: cluster::Shape::from_flags(args.roce_ring, args.roce_chain), + shape: cluster::Shape::from_flags(args.roce_ring, args.roce_chain, args.roce_hairpin), links: cluster::Links::from_switch_only(args.serving.roce_switch_only), }; let rendezvous = args.rendezvous; @@ -540,6 +544,7 @@ fn orbit_command(args: cli::OrbitArgs, matches: &clap::ArgMatches) -> Result<(), roce_ring: run.roce_ring, transfer_streams: run.transfer_streams, roce_chain: run.roce_chain, + roce_hairpin: run.roce_hairpin, executable: run.executable.clone(), detach: run.detach, verify_weights: run.serving.verify_weights, diff --git a/flare-cli/src/orbit/agent.rs b/flare-cli/src/orbit/agent.rs index f7e85ceca..3eeb22ea3 100644 --- a/flare-cli/src/orbit/agent.rs +++ b/flare-cli/src/orbit/agent.rs @@ -2223,8 +2223,12 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { grant.rendezvous.clone() }); } - if grant.roce_ring && grant.roce_chain { - return Err("grant selects both a ring and a chain".into()); + if usize::from(grant.roce_ring) + + usize::from(grant.roce_chain) + + usize::from(grant.roce_hairpin) + > 1 + { + return Err("grant selects more than one of ring, chain, or hairpin".into()); } let strip_tp = grant.core.tensor_parallel.is_some(); let mut skip_next = false; @@ -2233,7 +2237,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { skip_next = false; continue; } - if arg == "--roce-ring" || arg == "--roce-chain" { + if arg == "--roce-ring" || arg == "--roce-chain" || arg == "--roce-hairpin" { continue; } if strip_tp { @@ -2259,6 +2263,9 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { if grant.roce_chain { command.arg("--roce-chain"); } + if grant.roce_hairpin { + command.arg("--roce-hairpin"); + } // The controller accepted the publisher at its own terminal; the rank still verifies the // core and matches the exact key and namespace before loading. command @@ -3061,6 +3068,7 @@ pub mod tests { roce_ring: false, transfer_fabric: None, roce_chain: false, + roce_hairpin: false, single_host: false, issued: now(), expires: now() + 60, @@ -3647,6 +3655,7 @@ pub mod tests { roce_ring: false, transfer_fabric: None, roce_chain: false, + roce_hairpin: false, single_host: false, issued: now(), expires: now() + 60, @@ -4099,6 +4108,7 @@ pub mod tests { roce_ring: false, transfer_fabric: None, roce_chain: false, + roce_hairpin: false, single_host: false, issued: now(), expires: now() + 60, @@ -4201,7 +4211,8 @@ pub mod tests { rank_zero: vec![], roce_ring: ring, roce_chain: false, - transfer_fabric: Some(fabric::plan(&nodes, &records, ring, false, false).unwrap()), + roce_hairpin: false, + transfer_fabric: Some(fabric::plan(&nodes, &records, ring, false, false, false).unwrap()), single_host: false, issued: now(), expires: now() + 60, @@ -4316,7 +4327,7 @@ pub mod tests { // A dead next hop never falls back to the management address. Cache hits need no hop. grant.transfer_fabric = - Some(fabric::plan(&nodes, &records, ring, false, false).unwrap()); + Some(fabric::plan(&nodes, &records, ring, false, false, false).unwrap()); let closed = TcpListener::bind("127.0.0.1:0").unwrap(); let port = closed.local_addr().unwrap().port(); drop(closed); @@ -4403,6 +4414,7 @@ pub mod tests { roce_ring: false, transfer_fabric: None, roce_chain: false, + roce_hairpin: false, single_host: false, issued: now(), expires: now() + 60, @@ -4615,6 +4627,7 @@ pub mod tests { roce_ring: false, transfer_fabric: None, roce_chain: false, + roce_hairpin: false, single_host: false, issued: now().saturating_sub(120), expires: now().saturating_sub(1), @@ -4715,6 +4728,7 @@ pub mod tests { rank_zero: vec![], roce_ring: false, roce_chain: true, + roce_hairpin: false, transfer_fabric: None, single_host: false, issued: now(), @@ -5184,6 +5198,7 @@ pub mod tests { transfer_fabric: None, single_host: true, roce_chain: false, + roce_hairpin: false, issued: now(), expires: now() + 60, }, @@ -5345,6 +5360,7 @@ pub mod tests { transfer_fabric: None, single_host: false, roce_chain: false, + roce_hairpin: false, issued: now(), expires: now() + 60, }, diff --git a/flare-cli/src/orbit/controller.rs b/flare-cli/src/orbit/controller.rs index 27dddba3e..333440c6d 100644 --- a/flare-cli/src/orbit/controller.rs +++ b/flare-cli/src/orbit/controller.rs @@ -169,6 +169,7 @@ pub struct RunOptions { pub roce_ring: bool, pub transfer_streams: Option, pub roce_chain: bool, + pub roce_hairpin: bool, /// An executable to upload; absent means each node uses its installed agent executable. pub executable: Option, /// Return once every rank has started instead of following the group. @@ -193,8 +194,10 @@ pub struct LaunchOptions { /// Place and verify the core on the members without sending the executable or /// starting ranks; the returned launch then has no rank sessions. pub stage_only: bool, - /// Serve over a chain in rank order (exclusive with roce_ring). + /// Serve over a chain in rank order (exclusive with roce_ring and roce_hairpin). pub roce_chain: bool, + /// Serve over a hardware-hairpin ring in rank order (exclusive with roce_ring and roce_chain). + pub roce_hairpin: bool, } /// A `flare orbit run` core argument. @@ -714,12 +717,14 @@ impl Controller { let mut rank_zero = spec.as_ref().map_or_else(Vec::new, |s| s.rank_zero.clone()); rank_zero.extend(options.rank_zero.iter().cloned()); // An explicit shape on the command line replaces the saved one; otherwise the saved shape holds. - let (roce_ring, roce_chain) = if options.roce_ring || options.roce_chain { - (options.roce_ring, options.roce_chain) - } else { - spec.as_ref() - .map_or((false, false), |s| (s.roce_ring, s.roce_chain)) - }; + let (roce_ring, roce_chain, roce_hairpin) = + if options.roce_ring || options.roce_chain || options.roce_hairpin { + (options.roce_ring, options.roce_chain, options.roce_hairpin) + } else { + spec.as_ref().map_or((false, false, false), |s| { + (s.roce_ring, s.roce_chain, s.roce_hairpin) + }) + }; let transfer_streams = options .transfer_streams .or_else(|| spec.as_ref().and_then(|s| s.transfer_streams)); @@ -876,6 +881,7 @@ impl Controller { roce_ring, transfer_streams, roce_chain, + roce_hairpin, executable: options .executable .as_deref() @@ -920,6 +926,7 @@ impl Controller { transfer_streams, stage_only: false, roce_chain, + roce_hairpin, }, )?; eprintln!( @@ -968,6 +975,7 @@ impl Controller { stage_only: true, roce_ring: run_args.roce_ring, roce_chain: run_args.roce_chain, + roce_hairpin: run_args.roce_hairpin, transfer_streams, ..LaunchOptions::default() }; @@ -985,9 +993,9 @@ impl Controller { ); return Ok(()); } - if run_args.roce_ring || run_args.roce_chain { + if run_args.roce_ring || run_args.roce_chain || run_args.roce_hairpin { return Err( - "--roce-ring and --roce-chain push require one target node per core rank, in rank order" + "--roce-ring, --roce-chain, and --roce-hairpin push require one target node per core rank, in rank order" .into(), ); } @@ -1262,11 +1270,12 @@ impl Controller { format!("{} placements for {world} ranks", options.placements.len()).into(), ); } - if (options.roce_ring || options.roce_chain) + if (options.roce_ring || options.roce_chain || options.roce_hairpin) && !(core.needs.multi_host && (2..=16).contains(&world)) { return Err( - "--roce-ring and --roce-chain require a multi-host core with 2..16 ranks".into(), + "--roce-ring, --roce-chain, and --roce-hairpin require a multi-host core with 2..16 ranks" + .into(), ); } // Parallel streams require the signed fabric plan. A transfer from a source outside the @@ -1355,6 +1364,7 @@ impl Controller { &records, options.roce_ring, options.roce_chain, + options.roce_hairpin, switch_only, )?) } else { @@ -1395,6 +1405,7 @@ impl Controller { transfer_fabric, single_host: !core.needs.multi_host, roce_chain: options.roce_chain, + roce_hairpin: options.roce_hairpin, issued, expires: issued + GRANT_SECONDS, }; @@ -3071,6 +3082,7 @@ mod tests { transfer_streams: Some(8), stage_only: false, roce_chain: false, + roce_hairpin: false, }, ) .unwrap(); diff --git a/flare-cli/src/orbit/fabric.rs b/flare-cli/src/orbit/fabric.rs index c3386b255..056ccd24f 100644 --- a/flare-cli/src/orbit/fabric.rs +++ b/flare-cli/src/orbit/fabric.rs @@ -15,6 +15,7 @@ pub fn plan( records: &[Vec], ring: bool, chain: bool, + hairpin: bool, switch_only: bool, ) -> Result { let ports = nodes @@ -28,7 +29,7 @@ pub fn plan( .map_err(Into::into) }) .collect::, Failure>>()?; - Topology::plan_shape(records, &ports, ring, chain, switch_only) + Topology::plan_shape(records, &ports, ring, chain, hairpin, switch_only) } pub fn topology(grant: &Grant) -> Result<&Topology, Failure> { @@ -40,6 +41,7 @@ pub fn topology(grant: &Grant) -> Result<&Topology, Failure> { if topology.links.len() != grant.members.len() || topology.ring != grant.roce_ring || topology.chain != grant.roce_chain + || topology.hairpin != grant.roce_hairpin { return Err("fabric topology differs from the launch membership".into()); } @@ -92,7 +94,7 @@ mod tests { .iter() .map(|s| s.as_bytes().to_vec()) .collect::>(); - let ring = plan(&nodes, &records, true, false, false).unwrap(); + let ring = plan(&nodes, &records, true, false, false, false).unwrap(); for (rank, subnets) in [[4, 5], [6, 7], [2, 3], [0, 1]].into_iter().enumerate() { let edge = &ring.links[rank][(rank + 1) % 4]; assert_eq!(edge.len(), 2); @@ -102,8 +104,11 @@ mod tests { assert_ne!(link.from.ip(), link.to.ip()); } } + let hairpin = plan(&nodes, &records, false, false, true, false).unwrap(); + assert!(hairpin.hairpin && !hairpin.ring && !hairpin.chain); + assert_eq!(hairpin.links, ring.links); let mut broken = records.clone(); broken[2] = b"a 192.168.0.1/24 -\n".to_vec(); - assert!(plan(&nodes, &broken, true, false, false).is_err()); + assert!(plan(&nodes, &broken, true, false, false, false).is_err()); } } diff --git a/flare-cli/src/orbit/grant.rs b/flare-cli/src/orbit/grant.rs index 6efaa9762..d6a90deec 100644 --- a/flare-cli/src/orbit/grant.rs +++ b/flare-cli/src/orbit/grant.rs @@ -127,6 +127,9 @@ pub struct Grant { /// Serve over a chain in rank order; a grant without the field is not a chain. #[serde(default)] pub roce_chain: bool, + /// Serve over a hardware-hairpin ring in rank order; a grant without the field is not one. + #[serde(default)] + pub roce_hairpin: bool, pub issued: u64, pub expires: u64, } @@ -252,6 +255,7 @@ mod tests { transfer_fabric: None, single_host: false, roce_chain: false, + roce_hairpin: false, issued: 100, expires: 700, } diff --git a/flare-cli/src/orbit/store.rs b/flare-cli/src/orbit/store.rs index 4fc73a608..67b6802d2 100644 --- a/flare-cli/src/orbit/store.rs +++ b/flare-cli/src/orbit/store.rs @@ -244,10 +244,14 @@ pub struct GroupSpec { pub roce_ring: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub transfer_streams: Option, - /// Serve over a chain in rank order; exclusive with `roce_ring`. A record without the field - /// loads as not a chain. + /// Serve over a chain in rank order; exclusive with `roce_ring` and `roce_hairpin`. A record + /// without the field loads as not a chain. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub roce_chain: bool, + /// Serve over a hardware-hairpin ring in rank order; exclusive with `roce_ring` and + /// `roce_chain`. A record without the field loads as not a hairpin ring. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub roce_hairpin: bool, /// Controller-local executable override; absent sends the controller's running binary. #[serde(default, skip_serializing_if = "Option::is_none")] pub executable: Option, @@ -462,6 +466,7 @@ mod tests { roce_ring: true, transfer_streams: Some(8), roce_chain: false, + roce_hairpin: false, executable: Some("/bin/flare-pinned".into()), publisher_keys: vec!["/keys/publisher.json".into()], trust_store: Some("/keys/trust.toml".into()), diff --git a/helios/src/execution/roce.rs b/helios/src/execution/roce.rs index 9b29e9c44..9218fedbd 100644 --- a/helios/src/execution/roce.rs +++ b/helios/src/execution/roce.rs @@ -219,7 +219,7 @@ impl RoceTransport { return Err(failure(format!("RoCE transport setup failed: {text}"))); } let enabled = match topology.shape { - Shape::Mesh => 0, + Shape::Mesh | Shape::HairpinRing => 0, Shape::Ring => unsafe { roce_enable_ring(context) }, Shape::Chain => unsafe { roce_enable_ring_open(context) }, }; diff --git a/helios/src/execution/roce_fabric.rs b/helios/src/execution/roce_fabric.rs index 63cb04e7d..f66c44108 100644 --- a/helios/src/execution/roce_fabric.rs +++ b/helios/src/execution/roce_fabric.rs @@ -237,13 +237,19 @@ pub enum Shape { /// Experimental chain in rank order: a ring with no link between rank 0 and the last rank, so /// the ends have one neighbor and the proxy forwards along the chain. Chain, + /// Experimental hardware-hairpin ring in rank order: hosts are cabled as a physical ring, + /// intermediate ConnectX-7 NICs forward non-neighbor RoCEv2 packets in hardware (`skip_sw` + /// `in_hw`), and every rank opens direct queue pairs to every peer without CPU proxy relaying. + HairpinRing, } impl Shape { - /// The shape two command-line flags select; the chain flag wins because it implies relaying. - pub fn from_flags(ring: bool, chain: bool) -> Self { + /// The shape three command-line flags select; mutually exclusive flags are checked by the CLI. + pub fn from_flags(ring: bool, chain: bool, hairpin: bool) -> Self { if chain { Shape::Chain + } else if hairpin { + Shape::HairpinRing } else if ring { Shape::Ring } else { @@ -256,18 +262,20 @@ impl Shape { Shape::Mesh => "mesh", Shape::Ring => "ring", Shape::Chain => "chain", + Shape::HairpinRing => "hairpin-ring", } } /// Whether the native proxy relays writes between ranks that hold no direct link. pub fn relays(self) -> bool { - self != Shape::Mesh + matches!(self, Shape::Ring | Shape::Chain) } - /// Whether `rank` holds a direct link to `peer` among `world` ranks; a rank never links to itself. + /// Whether `rank` holds a direct queue pair to `peer` among `world` ranks; a rank never links + /// to itself. pub fn linked(self, rank: usize, peer: usize, world: usize) -> bool { match self { - Shape::Mesh => peer != rank, + Shape::Mesh | Shape::HairpinRing => peer != rank, Shape::Ring => { peer != rank && (peer == (rank + 1) % world || peer == (rank + world - 1) % world) } @@ -948,7 +956,7 @@ pub fn plan_link( } /// Per peer of `rank`, whether every rail rides a direct cable: its two devices are LLDP neighbors, -/// or, with three or more ranks, its subnet is narrower than the world. +/// or, with three or more ranks, both ends share a subnet narrower than the world. fn direct_peers(endpoints: &[Vec], rank: usize, routes: &[Vec<(u32, u32)>]) -> Vec { let world = endpoints.len(); let breadths = breadths(endpoints); @@ -959,8 +967,10 @@ fn direct_peers(endpoints: &[Vec], rank: usize, routes: &[Vec<(u32, u3 !links.is_empty() && links.iter().all(|&(local, remote)| { let x = &endpoints[rank][local as usize]; - lldp_adjacent(x, &endpoints[peer][remote as usize]) + let y = &endpoints[peer][remote as usize]; + lldp_adjacent(x, y) || (world > 2 + && same_link(x, y) && x.network() .is_some_and(|network| breadths[&network] < world)) }) @@ -968,10 +978,124 @@ fn direct_peers(endpoints: &[Vec], rank: usize, routes: &[Vec<(u32, u3 .collect() } +/// Pair rails for two opposite ranks (`dist_cw == dist_ccw`) in a hardware-hairpin ring. +/// Rail 0 rides the clockwise arc from `a` to `b`; when a second rail is present, Rail 1 rides +/// the opposite counter-clockwise arc, preferring distinct devices, PCIe links, and physical ports +/// at both ends. Callers pass `a < b` and mirror pairs when `rank > peer` so both ends agree. +fn hairpin_equal_arc_pair( + endpoints: &[Vec], + a: usize, + b: usize, + cw_a: &[u32], + ccw_a: &[u32], + cw_b: &[u32], + ccw_b: &[u32], + rails: usize, +) -> Vec<(u32, u32)> { + let l0 = cw_a[0]; + let r0 = ccw_b[0]; + let mut pairs = vec![(l0, r0)]; + if rails == 1 { + return pairs; + } + let mut best: Option<((usize, usize, usize, usize, usize), (u32, u32))> = None; + for j in 0..rails { + let l1 = ccw_a[j]; + let r1 = cw_b[j]; + let dup_dev = usize::from(l1 == l0) + usize::from(r1 == r0); + let shared_link = shared_links([&endpoints[a][l0 as usize], &endpoints[a][l1 as usize]]) + + shared_links([&endpoints[b][r0 as usize], &endpoints[b][r1 as usize]]); + let shared_port = shared_ports([&endpoints[a][l0 as usize], &endpoints[a][l1 as usize]]) + + shared_ports([&endpoints[b][r0 as usize], &endpoints[b][r1 as usize]]); + let same_slot = usize::from(j == 0); + let score = (dup_dev, shared_link, shared_port, same_slot, j); + if best.as_ref().is_none_or(|(current, _)| score < *current) { + best = Some((score, (l1, r1))); + } + } + if let Some((_, pair)) = best { + pairs.push(pair); + } + pairs +} + +/// Plan direct all-to-all routes for a hardware-hairpin ring: direct neighbors use their physical +/// ring links, while non-neighbors pair each rank's arc-entry device with the peer's arc-exit +/// device so intermediate ConnectX-7 NICs hairpin the transit RoCEv2 packets in hardware. +fn plan_hairpin_ring_routes( + endpoints: &[Vec], + rank: usize, + rails: usize, + links: Links, +) -> Result>> { + let world = endpoints.len(); + let planner = Planner::new(endpoints, rails, links)?; + let cw_edges: Vec> = (0..world) + .map(|r| planner.peer(r, (r + 1) % world)) + .collect::>>()?; + let cw_out: Vec> = cw_edges + .iter() + .map(|edge| edge.iter().map(|&(l, _)| l).collect()) + .collect(); + let ccw_out: Vec> = (0..world) + .map(|r| { + cw_edges[(r + world - 1) % world] + .iter() + .map(|&(_, rem)| rem) + .collect() + }) + .collect(); + let mut routes = Vec::with_capacity(world); + for peer in 0..world { + if peer == rank { + routes.push(Vec::new()); + continue; + } + let dist_cw = (peer + world - rank) % world; + let dist_ccw = world - dist_cw; + if dist_cw == 1 { + routes.push(cw_edges[rank].clone()); + } else if dist_ccw == 1 { + routes.push(cw_edges[peer].iter().map(|&(l, r)| (r, l)).collect()); + } else if dist_cw < dist_ccw { + routes.push( + (0..rails) + .map(|h| (cw_out[rank][h], ccw_out[peer][h])) + .collect(), + ); + } else if dist_ccw < dist_cw { + routes.push( + (0..rails) + .map(|h| (ccw_out[rank][h], cw_out[peer][h])) + .collect(), + ); + } else { + let (a, b) = if rank < peer { + (rank, peer) + } else { + (peer, rank) + }; + let mut pairs = hairpin_equal_arc_pair( + endpoints, a, b, &cw_out[a], &ccw_out[a], &cw_out[b], &ccw_out[b], rails, + ); + if rank > peer { + for pair in &mut pairs { + *pair = (pair.1, pair.0); + } + } + routes.push(pairs); + } + } + Ok(routes) +} + /// The routes of `shape` for `rank`: a mesh routes to every rank; a ring or chain routes only to -/// the ranks `shape` links, and the native proxy forwards writes to the others. The same plan works -/// over a switch while keeping unlinked QPs unconnected. Routes are planned over every rank's -/// endpoints, so both ends of an edge see the same subnet breadths and index-pairing validity. +/// the ranks `shape` links, and the native proxy forwards writes to the others; a hairpin ring +/// routes every rank directly using neighbor links for adjacent ranks and arc-entry/exit device +/// pairs for non-neighbors forwarded by ConnectX-7 hardware hairpin. The same plan works over a +/// switch while keeping unlinked QPs unconnected in ring/chain mode. Routes are planned over every +/// rank's endpoints, so both ends of an edge see the same subnet breadths and index-pairing +/// validity. pub fn plan_shape_routes( endpoints: &[Vec], rank: usize, @@ -985,6 +1109,9 @@ pub fn plan_shape_routes( if !(2..=16).contains(&endpoints.len()) || rank >= endpoints.len() { return Err(failure("experimental RoCE ring requires 2..16 ranks")); } + if shape == Shape::HairpinRing { + return plan_hairpin_ring_routes(endpoints, rank, rails, links); + } let world = endpoints.len(); let planner = Planner::new(endpoints, rails, links)?; (0..world) @@ -2122,4 +2249,121 @@ mod tests { } } } + + #[test] + fn hairpin_ring_on_four_sparks_splits_diagonals_across_both_arcs_and_pcie_links() { + // Four Sparks cabled in a physical ring: each host's port 0 connects to (rank + 1) % 4's + // port 1 across two PCIe Gen5 x4 functions on distinct /30 subnets. + let endpoints: Vec> = (0..4) + .map(|rank| { + let prev = (rank + 3) % 4; + vec![ + Endpoint { + link: Some("0000:01:00".into()), + port: Some(format!("sw{rank}:p0")), + ..endpoint("p0f0", &format!("10.{}.0.1/30", rank + 1)) + }, + Endpoint { + link: Some("0002:01:00".into()), + port: Some(format!("sw{rank}:p0")), + ..endpoint("p0f1", &format!("10.{}.1.1/30", rank + 1)) + }, + Endpoint { + link: Some("0000:01:00".into()), + port: Some(format!("sw{rank}:p1")), + ..endpoint("p1f0", &format!("10.{}.0.2/30", prev + 1)) + }, + Endpoint { + link: Some("0002:01:00".into()), + port: Some(format!("sw{rank}:p1")), + ..endpoint("p1f1", &format!("10.{}.1.2/30", prev + 1)) + }, + ] + }) + .collect(); + let plans: Vec<_> = (0..4) + .map(|r| plan_shape_routes(&endpoints, r, 2, Shape::HairpinRing, Links::All).unwrap()) + .collect(); + assert_both_ends_agree(&plans, "4-spark hairpin ring"); + // Direct neighbors ride their physical cables; diagonals split Rail 0 CW and Rail 1 CCW + // across disjoint PCIe links and physical ports. + assert_eq!(plans[0][1], vec![(0, 2), (1, 3)]); + assert_eq!(plans[0][3], vec![(2, 0), (3, 1)]); + assert_eq!(plans[0][2], vec![(0, 2), (3, 1)]); + assert_eq!(plans[2][0], vec![(2, 0), (1, 3)]); + assert_eq!(plans[1][3], vec![(0, 2), (3, 1)]); + assert_eq!(plans[3][1], vec![(2, 0), (1, 3)]); + for rank in 0..4 { + let fabric = Fabric { + gid_index: 3, + traffic_class: 0, + endpoints: endpoints[rank].clone(), + }; + let topo = fabric + .topology(&endpoints, rank, Shape::HairpinRing, Links::All) + .unwrap(); + assert!(!topo.shape.relays()); + assert_eq!(topo.rails, 2); + for peer in 0..4 { + if peer == rank { + assert!(topo.routes[peer].is_empty()); + assert!(!topo.direct[peer]); + continue; + } + let is_neighbor = peer == (rank + 1) % 4 || peer == (rank + 3) % 4; + assert_eq!(topo.direct[peer], is_neighbor, "rank {rank} to {peer}"); + let local_devs: Vec<&Endpoint> = topo.routes[peer] + .iter() + .map(|&(l, _)| &endpoints[rank][l as usize]) + .collect(); + assert_eq!(shared_links(local_devs.iter().copied()), 0); + if !is_neighbor { + assert_eq!(shared_ports(local_devs.iter().copied()), 0); + } + } + } + } + + #[test] + fn variable_size_hairpin_rings_route_all_peers_symmetrically() { + for world in [2, 3, 4, 5, 6, 8, 16] { + for switched in [false, true] { + let endpoints: Vec> = (0..world) + .map(|rank| { + if switched { + return vec![ + endpoint("f0", &format!("10.1.0.{}/24", rank + 1)), + endpoint("f1", &format!("10.2.0.{}/24", rank + 1)), + ]; + } + let previous = (rank + world - 1) % world; + vec![ + endpoint("p0f0", &format!("10.{}.0.1/30", rank + 1)), + endpoint("p0f1", &format!("10.{}.1.1/30", rank + 1)), + endpoint("p1f0", &format!("10.{}.0.2/30", previous + 1)), + endpoint("p1f1", &format!("10.{}.1.2/30", previous + 1)), + ] + }) + .collect(); + let plans: Vec<_> = (0..world) + .map(|r| { + plan_shape_routes(&endpoints, r, 2, Shape::HairpinRing, Links::All) + .unwrap() + }) + .collect(); + assert_both_ends_agree(&plans, &format!("hairpin world={world} switched={switched}")); + for rank in 0..world { + assert!(plans[rank][rank].is_empty()); + for peer in (0..world).filter(|&p| p != rank) { + assert_eq!(plans[rank][peer].len(), 2); + assert_ne!(plans[rank][peer][0].0, plans[rank][peer][1].0); + assert_ne!(plans[rank][peer][0].1, plans[rank][peer][1].1); + } + } + } + } + assert!(plan_shape_routes(&[], 0, 2, Shape::HairpinRing, Links::All).is_err()); + let single = vec![vec![endpoint("f0", "10.0.0.1/30")]; 4]; + assert!(plan_shape_routes(&single, 0, 2, Shape::HairpinRing, Links::All).is_err()); + } } diff --git a/scripts/setup_cx7_hairpin_ring.sh b/scripts/setup_cx7_hairpin_ring.sh new file mode 100755 index 000000000..c5e463e2a --- /dev/null +++ b/scripts/setup_cx7_hairpin_ring.sh @@ -0,0 +1,243 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 +# +# Configure, verify, or tear down ConnectX-7 ASIC hardware hairpin (`skip_sw` +# `in_hw`) on one node of a switchless 4-node physical RoCEv2 ring (0-1-2-3-0) +# for `flare run --roce-hairpin`. +# +# Default mode is dry-run: commands are printed without modifying the host. +# Pass --apply to configure, --verify to inspect `in_hw` offload state, or +# --teardown to remove the hairpin rules and static routes. +# +# Ring wiring model (per rail, two rails per 4-Spark ring): +# Rank r's clockwise port (CW_DEV) connects to rank (r+1)%4's counter-clockwise +# port (CCW_DEV) on subnet 10...0/30. +# +# Diagonal RoCEv2 traffic (0 <-> 2 and 1 <-> 3): +# - Rail 0 uses the clockwise arc: 0 --CW--> 1 (hairpin CCW->CW) --CW--> 2 +# 1 --CW--> 2 (hairpin CCW->CW) --CW--> 3 +# - Rail 1 uses the counter-clockwise: 0 --CCW-> 3 (hairpin CW->CCW) --CCW-> 2 +# 1 --CCW-> 0 (hairpin CW->CCW) --CCW-> 3 +# +# Example (rank 1 forwarding 0 <-> 2 on Rail 0, and sending to rank 3): +# ./scripts/setup_cx7_hairpin_ring.sh \ +# --config /path/to/ring4.env --rank 1 [--apply|--verify|--teardown] +# +# Config file format (sourced shell variables for ranks 0..3, rails 0..1): +# # Netdev names on each rank r for clockwise (CW) and counter-clockwise (CCW) rails: +# R0_CW0_DEV=enp1s0f0np0 R0_CW0_IP=10.1.0.1 R0_CW0_MAC=aa:bb:cc:dd:00:01 +# R0_CW1_DEV=enP2p1s0f0np0 R0_CW1_IP=10.1.1.1 R0_CW1_MAC=aa:bb:cc:dd:00:02 +# R0_CCW0_DEV=enp1s0f1np1 R0_CCW0_IP=10.4.0.2 R0_CCW0_MAC=aa:bb:cc:dd:00:03 +# R0_CCW1_DEV=enP2p1s0f1np1 R0_CCW1_IP=10.4.1.2 R0_CCW1_MAC=aa:bb:cc:dd:00:04 +# ... (same for R1_*, R2_*, R3_*) +# # Optional: RDMA HCA names for `ib_write_lat` verification hints: +# R0_CW0_HCA=rocep1s0f0 R0_CW1_HCA=roceP2p1s0f0 R0_CCW0_HCA=rocep1s0f1 R0_CCW1_HCA=roceP2p1s0f1 +# # Optional: RoCEv2 GID index (default 3 on DGX Spark) and UDP port (default 4791) +# GID_INDEX=3 +# ROCE_UDP_PORT=4791 + +set -euo pipefail + +MODE="dry-run" +CONFIG="" +RANK="" +PRIO_BASE=100 + +usage() { + sed -n '2,42p' "$0" | sed 's/^# \{0,1\}//' +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --config) CONFIG="${2:?missing path}"; shift 2 ;; + --rank) RANK="${2:?missing rank}"; shift 2 ;; + --apply) MODE="apply"; shift ;; + --verify) MODE="verify"; shift ;; + --teardown) MODE="teardown"; shift ;; + --dry-run) MODE="dry-run"; shift ;; + -h|--help) usage; exit 0 ;; + *) echo "unknown option: $1" >&2; usage >&2; exit 2 ;; + esac +done + +if [[ -z "$CONFIG" || -z "$RANK" ]]; then + echo "error: --config PATH and --rank 0..3 are required" >&2 + exit 2 +fi +if [[ ! -f "$CONFIG" ]]; then + echo "error: config file not found: $CONFIG" >&2 + exit 2 +fi +if ! [[ "$RANK" =~ ^[0-3]$ ]]; then + echo "error: --rank must be 0, 1, 2, or 3 (got '$RANK')" >&2 + exit 2 +fi + +# shellcheck disable=SC1090 +source "$CONFIG" + +GID_INDEX="${GID_INDEX:-3}" +ROCE_UDP_PORT="${ROCE_UDP_PORT:-4791}" + +get_var() { + local name="$1" + if [[ -z "${!name:-}" ]]; then + echo "error: missing required config variable: $name" >&2 + exit 2 + fi + printf '%s' "${!name}" +} + +run_cmd() { + if [[ "$MODE" == "apply" || "$MODE" == "teardown" ]]; then + echo "+ $*" + "$@" + else + echo "[dry-run] $*" + fi +} + +CW_PEER=$(( (RANK + 1) % 4 )) +OPP_PEER=$(( (RANK + 2) % 4 )) +CCW_PEER=$(( (RANK + 3) % 4 )) + +# Local interfaces on this rank +L_CW0_DEV=$(get_var "R${RANK}_CW0_DEV") +L_CW0_MAC=$(get_var "R${RANK}_CW0_MAC") +L_CW1_DEV=$(get_var "R${RANK}_CW1_DEV") +L_CW1_MAC=$(get_var "R${RANK}_CW1_MAC") +L_CCW0_DEV=$(get_var "R${RANK}_CCW0_DEV") +L_CCW0_MAC=$(get_var "R${RANK}_CCW0_MAC") +L_CCW1_DEV=$(get_var "R${RANK}_CCW1_DEV") +L_CCW1_MAC=$(get_var "R${RANK}_CCW1_MAC") + +# Direct neighbor facing interfaces +CW_NEIGH_CCW0_MAC=$(get_var "R${CW_PEER}_CCW0_MAC") +CW_NEIGH_CCW1_MAC=$(get_var "R${CW_PEER}_CCW1_MAC") +CCW_NEIGH_CW0_MAC=$(get_var "R${CCW_PEER}_CW0_MAC") +CCW_NEIGH_CW1_MAC=$(get_var "R${CCW_PEER}_CW1_MAC") + +# Opposite peer endpoints reached from this rank: +# - Rail 0 (CW arc through CW_PEER): local CW0 <-> opposite CCW0 +# - Rail 1 (CCW arc through CCW_PEER): local CCW1 <-> opposite CW1 +# For RANK < OPP_PEER (0->2, 1->3): +# Rail 0 = CW0 -> OPP CCW0 (via CW_PEER) +# Rail 1 = CCW1 -> OPP CW1 (via CCW_PEER) +# For RANK > OPP_PEER (2->0, 3->1), the exact mirror uses the same physical arcs: +# Rail 0 = CCW0 -> OPP CW0 (via CCW_PEER) +# Rail 1 = CW1 -> OPP CCW1 (via CW_PEER) +if (( RANK < OPP_PEER )); then + R0_LOC_DEV="$L_CW0_DEV" + R0_NH_MAC="$CW_NEIGH_CCW0_MAC" + R0_DST_IP=$(get_var "R${OPP_PEER}_CCW0_IP") + + R1_LOC_DEV="$L_CCW1_DEV" + R1_NH_MAC="$CCW_NEIGH_CW1_MAC" + R1_DST_IP=$(get_var "R${OPP_PEER}_CW1_IP") +else + R0_LOC_DEV="$L_CCW0_DEV" + R0_NH_MAC="$CCW_NEIGH_CW0_MAC" + R0_DST_IP=$(get_var "R${OPP_PEER}_CW0_IP") + + R1_LOC_DEV="$L_CW1_DEV" + R1_NH_MAC="$CW_NEIGH_CCW1_MAC" + R1_DST_IP=$(get_var "R${OPP_PEER}_CCW1_IP") +fi + +# Transit flows hairpinned BY this rank between CCW_PEER and CW_PEER: +# 1) CCW_PEER -> CW_PEER on Rail 0 (arrives on L_CCW0_DEV, exits L_CW0_DEV): +# Destination IP is CW_PEER's CCW0 (when CCW_PEER < CW_PEER) or CW0 (reverse). +# Actually both directions of a diagonal pair (CCW_PEER <-> CW_PEER) transit this rank! +# - If CCW_PEER < CW_PEER (this rank is 1 handling 0<->2 on Rail 0, or rank 2 handling 1<->3 on Rail 0): +# Forward (CCW_PEER -> CW_PEER): in L_CCW0_DEV, dst_ip = CW_PEER_CCW0_IP -> out L_CW0_DEV (dst MAC CW_NEIGH_CCW0_MAC) +# Reverse (CW_PEER -> CCW_PEER): in L_CW0_DEV, dst_ip = CCW_PEER_CW0_IP -> out L_CCW0_DEV (dst MAC CCW_NEIGH_CW0_MAC) +# - If CCW_PEER > CW_PEER (this rank is 3 handling 2<->0 on Rail 1, or rank 0 handling 3<->1 on Rail 1): +# Forward (CW_PEER -> CCW_PEER): in L_CW1_DEV, dst_ip = CCW_PEER_CW1_IP -> out L_CCW1_DEV (dst MAC CCW_NEIGH_CW1_MAC) +# Reverse (CCW_PEER -> CW_PEER): in L_CCW1_DEV, dst_ip = CW_PEER_CCW1_IP -> out L_CW1_DEV (dst MAC CW_NEIGH_CCW1_MAC) +if (( CCW_PEER < CW_PEER )); then + TR_RAIL=0 + TR_CCW_DEV="$L_CCW0_DEV" + TR_CCW_MAC="$L_CCW0_MAC" + TR_CW_DEV="$L_CW0_DEV" + TR_CW_MAC="$L_CW0_MAC" + TR_CW_DST_IP=$(get_var "R${CW_PEER}_CCW0_IP") + TR_CW_NH_MAC="$CW_NEIGH_CCW0_MAC" + TR_CCW_DST_IP=$(get_var "R${CCW_PEER}_CW0_IP") + TR_CCW_NH_MAC="$CCW_NEIGH_CW0_MAC" +else + TR_RAIL=1 + TR_CCW_DEV="$L_CCW1_DEV" + TR_CCW_MAC="$L_CCW1_MAC" + TR_CW_DEV="$L_CW1_DEV" + TR_CW_MAC="$L_CW1_MAC" + TR_CW_DST_IP=$(get_var "R${CW_PEER}_CCW1_IP") + TR_CW_NH_MAC="$CW_NEIGH_CCW1_MAC" + TR_CCW_DST_IP=$(get_var "R${CCW_PEER}_CW1_IP") + TR_CCW_NH_MAC="$CCW_NEIGH_CW1_MAC" +fi + +if [[ "$MODE" == "verify" ]]; then + echo "=== Rank $RANK ConnectX-7 hairpin verification (transit rail $TR_RAIL: $CCW_PEER <-> $CW_PEER) ===" + for dev in "$TR_CCW_DEV" "$TR_CW_DEV"; do + echo "--- devlink eswitch ($dev) ---" + pci=$(basename "$(readlink -f "/sys/class/net/${dev}/device")") + devlink dev eswitch show "pci/${pci}" || true + echo "--- tc ingress filters ($dev) ---" + tc -s filter show dev "$dev" ingress | sed -n '1,40p' + done + echo "--- static routes & neighbors to opposite rank $OPP_PEER ---" + ip route get "$R0_DST_IP" || true + ip neigh show to "$R0_DST_IP" dev "$R0_LOC_DEV" || true + ip route get "$R1_DST_IP" || true + ip neigh show to "$R1_DST_IP" dev "$R1_LOC_DEV" || true + echo "--- 2-hop RDMA latency smoke test (run server on rank $OPP_PEER, client on rank $RANK) ---" + echo " Rail 0 target IP: $R0_DST_IP (egress dev $R0_LOC_DEV, GID index $GID_INDEX)" + echo " Rail 1 target IP: $R1_DST_IP (egress dev $R1_LOC_DEV, GID index $GID_INDEX)" + echo " Example: ib_write_lat -d -x $GID_INDEX -F --report_gbits $R0_DST_IP" + exit 0 +fi + +if [[ "$MODE" == "teardown" ]]; then + echo "=== Tearing down ConnectX-7 hairpin rules on rank $RANK ===" + run_cmd tc filter del dev "$TR_CCW_DEV" ingress pref "$PRIO_BASE" || true + run_cmd tc filter del dev "$TR_CW_DEV" ingress pref "$PRIO_BASE" || true + run_cmd ip route del "${R0_DST_IP}/32" dev "$R0_LOC_DEV" || true + run_cmd ip neigh del "$R0_DST_IP" dev "$R0_LOC_DEV" || true + run_cmd ip route del "${R1_DST_IP}/32" dev "$R1_LOC_DEV" || true + run_cmd ip neigh del "$R1_DST_IP" dev "$R1_LOC_DEV" || true + exit 0 +fi + +echo "=== Configuring ConnectX-7 ASIC hairpin on rank $RANK (mode: $MODE) ===" +echo "# Endpoint routes to opposite rank $OPP_PEER:" +echo "# Rail 0: $R0_LOC_DEV -> $R0_DST_IP (next-hop MAC $R0_NH_MAC)" +echo "# Rail 1: $R1_LOC_DEV -> $R1_DST_IP (next-hop MAC $R1_NH_MAC)" +run_cmd ip route replace "${R0_DST_IP}/32" dev "$R0_LOC_DEV" +run_cmd ip neigh replace "$R0_DST_IP" lladdr "$R0_NH_MAC" dev "$R0_LOC_DEV" nud permanent +run_cmd ip route replace "${R1_DST_IP}/32" dev "$R1_LOC_DEV" +run_cmd ip neigh replace "$R1_DST_IP" lladdr "$R1_NH_MAC" dev "$R1_LOC_DEV" nud permanent + +echo "# Hardware-offloaded (skip_sw) transit hairpin on rail $TR_RAIL ($CCW_PEER <-> $CW_PEER):" +run_cmd tc qdisc replace dev "$TR_CCW_DEV" clsact +run_cmd tc qdisc replace dev "$TR_CW_DEV" clsact + +# Transit CCW -> CW (e.g. rank 0 -> rank 2 via rank 1) +run_cmd tc filter replace dev "$TR_CCW_DEV" ingress protocol ip pref "$PRIO_BASE" \ + flower skip_sw ip_proto udp dst_port "$ROCE_UDP_PORT" dst_ip "${TR_CW_DST_IP}/32" \ + action pedit ex \ + munge eth dst set "$TR_CW_NH_MAC" \ + munge eth src set "$TR_CW_MAC" \ + pipe action mirred egress redirect dev "$TR_CW_DEV" + +# Transit CW -> CCW (e.g. rank 2 -> rank 0 via rank 1) +run_cmd tc filter replace dev "$TR_CW_DEV" ingress protocol ip pref "$PRIO_BASE" \ + flower skip_sw ip_proto udp dst_port "$ROCE_UDP_PORT" dst_ip "${TR_CCW_DST_IP}/32" \ + action pedit ex \ + munge eth dst set "$TR_CCW_NH_MAC" \ + munge eth src set "$TR_CCW_MAC" \ + pipe action mirred egress redirect dev "$TR_CCW_DEV" + +if [[ "$MODE" == "apply" ]]; then + echo "Applied. Run with --verify to confirm 'in_hw' offload on $TR_CCW_DEV and $TR_CW_DEV." +fi