From e481409d15586e56a1a6d47525c417ed75a8a848 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:32:00 -0600 Subject: [PATCH 1/4] transport-core: fix shm_verbs lock inversion & overflow, sysfs/verbs portability, topology parser parity (P0-5, P1-3, P1-4, P1-6) --- docs/transport-core.md | 2 - transport-core/Makefile | 2 +- transport-core/include/sircl_core/core.h | 2 + transport-core/include/sircl_core/verbs.h | 13 +- transport-core/include/sircl_fabric.h | 109 ----- transport-core/src/fabric.c | 439 ------------------ transport-core/src/shm_verbs.c | 25 +- transport-core/src/sysfs.c | 36 +- transport-core/src/topology.c | 45 +- transport-core/tests/test_emulator_lifetime.c | 39 +- transport-core/tests/test_planning.py | 27 +- transport-core/tests/test_verbs.c | 42 ++ 12 files changed, 194 insertions(+), 587 deletions(-) delete mode 100644 transport-core/include/sircl_fabric.h delete mode 100644 transport-core/src/fabric.c diff --git a/docs/transport-core.md b/docs/transport-core.md index 3f8bc8e..6685724 100644 --- a/docs/transport-core.md +++ b/docs/transport-core.md @@ -28,8 +28,6 @@ provenance and the historical 0.1.0 measurement hashes. The version macro and it test use 0.1.2; the ABI remains 1. The component version and ABI do not identify hardware-qualified source bytes. The following code is research-only and is not part of the plugin's transport: -- `transport-core/src/fabric.c` and `include/sircl_fabric.h`: collective planner - from libsircl, the originating project's C collective library. The core build compiles it; the source-retention test requires both files; `fabric.c` includes the header. - `transport-core/src/verbs_dl.c` and `include/sircl_core/verbs_dl.c`: optional dynamic verbs loader. The latter includes the former, and the core build compiles the loader. The plugin links libibverbs directly. diff --git a/transport-core/Makefile b/transport-core/Makefile index a22c662..5cbce8b 100644 --- a/transport-core/Makefile +++ b/transport-core/Makefile @@ -5,7 +5,7 @@ BUILD ?= build CFLAGS ?= -O2 -g CFLAGS += -std=c11 -fPIC -Wall -Wextra -Werror -pthread CPPFLAGS += -Iinclude -include $(BUILD)/core_identity.h -SOURCES = core topology sysfs fabric +SOURCES = core topology sysfs OBJECTS = $(addprefix $(BUILD)/,$(addsuffix .o,$(SOURCES))) all: $(BUILD)/libsircl-core.a $(BUILD)/verbs_dl.o $(BUILD): diff --git a/transport-core/include/sircl_core/core.h b/transport-core/include/sircl_core/core.h index d04918d..cf02e04 100644 --- a/transport-core/include/sircl_core/core.h +++ b/transport-core/include/sircl_core/core.h @@ -70,6 +70,8 @@ SIRCL_CORE_API int sircl_core_topology_route(const struct sircl_core_topology *t int local, int peer, const char **functions, int *relays); SIRCL_CORE_API uint64_t sircl_core_sysfs_guid(const char *root, const char *device); SIRCL_CORE_API void sircl_core_sysfs_netdev(const char *root, const char *device, char *out, size_t len); +SIRCL_CORE_API void sircl_core_sysfs_gid_netdev(const char *root, const char *device, unsigned port, + int gid_index, char *out, size_t len); SIRCL_CORE_API int sircl_core_gid_index(const char *root, const char *device, unsigned port); #ifdef __cplusplus } diff --git a/transport-core/include/sircl_core/verbs.h b/transport-core/include/sircl_core/verbs.h index bf9bb3b..291d558 100644 --- a/transport-core/include/sircl_core/verbs.h +++ b/transport-core/include/sircl_core/verbs.h @@ -49,8 +49,9 @@ static inline struct ibv_mr *sircl_core_reg_mr(struct ibv_pd *pd, void *p, size_ static inline struct ibv_cq *sircl_core_create_cq(struct ibv_context *ctx, int depth) { return ibv_create_cq(ctx, depth, NULL, NULL, 0); } -static inline struct ibv_qp *sircl_core_create_rc_qp(struct ibv_pd *pd, struct ibv_cq *cq, - unsigned depth, unsigned inline_bytes) { +static inline struct ibv_qp *sircl_core_create_rc_qp_ex(struct ibv_pd *pd, struct ibv_cq *cq, + unsigned depth, unsigned inline_bytes, + unsigned *granted_inline) { struct ibv_qp_init_attr attr; memset(&attr, 0, sizeof attr); attr.send_cq = attr.recv_cq = cq; @@ -59,7 +60,13 @@ static inline struct ibv_qp *sircl_core_create_rc_qp(struct ibv_pd *pd, struct i attr.cap.max_recv_wr = 1; attr.cap.max_send_sge = attr.cap.max_recv_sge = 1; attr.cap.max_inline_data = inline_bytes; - return ibv_create_qp(pd, &attr); + struct ibv_qp *qp = ibv_create_qp(pd, &attr); + if (qp && granted_inline) *granted_inline = attr.cap.max_inline_data; + return qp; +} +static inline struct ibv_qp *sircl_core_create_rc_qp(struct ibv_pd *pd, struct ibv_cq *cq, + unsigned depth, unsigned inline_bytes) { + return sircl_core_create_rc_qp_ex(pd, cq, depth, inline_bytes, NULL); } static inline int sircl_core_qp_init(struct ibv_qp *qp, unsigned port, int access) { struct ibv_qp_attr a; diff --git a/transport-core/include/sircl_fabric.h b/transport-core/include/sircl_fabric.h deleted file mode 100644 index 637055f..0000000 --- a/transport-core/include/sircl_fabric.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef SIRCL_FABRIC_H -#define SIRCL_FABRIC_H - -/* Implemented offline planning. Hardware qualification is pending. */ -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define SIRCL_FABRIC_MAX_WORLD 16 -#define SIRCL_FABRIC_MAX_LANES 2 -#define SIRCL_FABRIC_MAX_CABLES 16 -#define SIRCL_FABRIC_DEFAULT_MAX_RELAYS 3 -#define SIRCL_PROTOCOL_MAX_PHASES 8 -#define SIRCL_PROTOCOL_OP_BYTES_MASK UINT32_C(0x3fffffff) - -typedef struct { int code; char message[192]; } sircl_fabric_error; -enum { SIRCL_FABRIC_INVALID = 1, SIRCL_FABRIC_UNREACHABLE = 2, - SIRCL_FABRIC_MISMATCH = 3, SIRCL_FABRIC_LIMIT = 4 }; -/* The role value is port * 2 + secondary. Device names are case sensitive. */ -enum { SIRCL_CW_PRIMARY = 0, SIRCL_CW_SECONDARY = 1, - SIRCL_CCW_PRIMARY = 2, SIRCL_CCW_SECONDARY = 3 }; -typedef struct { int a, a_port, b, b_port; } sircl_cable; -typedef struct { int src, src_port, dst, dst_port; } sircl_fabric_step; -typedef struct { - int cable_count, node_count, world, cycle; - sircl_cable cables[SIRCL_FABRIC_MAX_CABLES]; - int nodes[SIRCL_FABRIC_MAX_WORLD], positions[SIRCL_FABRIC_MAX_WORLD]; -} sircl_fabric_layout; -typedef struct { - uint8_t count[SIRCL_FABRIC_MAX_WORLD]; - uint8_t role[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES]; -} sircl_route_map; -typedef struct { - int local_role, remote_role, hops; - sircl_fabric_step steps[SIRCL_FABRIC_MAX_WORLD]; -} sircl_lane_route; -typedef struct { - sircl_fabric_layout layout; - int lanes; - sircl_lane_route route[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES]; -} sircl_fabric_routes; -typedef struct { - const char *local_error; - /* Canonical serialized shared settings only: no pointers, padding, or rank-local fields. */ - const void *shared_settings; - size_t shared_size; - sircl_route_map map; -} sircl_fabric_rank_record; -typedef struct { uint64_t first, count; } sircl_pack_range; -typedef struct { int first, end, peer, namespace_id; } sircl_phase; -enum { SIRCL_ALGORITHM_AUTO = -1, SIRCL_ALGORITHM_ONESHOT = 0, - SIRCL_ALGORITHM_TWOSHOT = 1, SIRCL_ALGORITHM_SWING = 2 }; - -/* Planning/encoding functions return 0 on success and -1 on error. Error is optional. - * Role getters return the role or name, or -1/NULL if unknown. Input bounds and - * wire encodings are checked. Output contents after an error are unspecified. */ -const char *sircl_fabric_role_device(int role); -int sircl_fabric_role_of(const char *device); -int sircl_fabric_layout_init(sircl_fabric_layout *out, const sircl_cable *cables, - int cable_count, const int *positions, int world, - sircl_fabric_error *error); -int sircl_fabric_layout_parse(const char *text, sircl_fabric_layout *out, sircl_fabric_error *error); -int sircl_fabric_derive(const sircl_fabric_layout *layout, int lanes, - sircl_fabric_routes *out, sircl_fabric_error *error); -int sircl_fabric_map(const sircl_fabric_routes *routes, int rank, - sircl_route_map *out, sircl_fabric_error *error); -int sircl_fabric_map_parse(const char *text, sircl_route_map *out, sircl_fabric_error *error); -int sircl_fabric_map_format(const sircl_route_map *map, int world, char *out, - size_t capacity, sircl_fabric_error *error); -int sircl_fabric_map_validate(const sircl_fabric_layout *layout, const sircl_route_map *map, - int rank, int world, int max_relays, sircl_fabric_error *error); -int sircl_fabric_complementary(const sircl_fabric_layout *layout, const sircl_route_map *maps, - sircl_fabric_error *error); -int sircl_fabric_agree(const sircl_fabric_layout *layout, int world, int lanes, - const sircl_fabric_rank_record *records, int max_relays, - sircl_fabric_error *error); -int sircl_fabric_post_order(const sircl_fabric_routes *routes, int rank, - const char *order, int *peers, sircl_fabric_error *error); -int sircl_fabric_relay_load(const sircl_fabric_routes *routes, int *busiest, - double *factor, sircl_fabric_error *error); -int sircl_fabric_forward_windows(const sircl_fabric_routes *routes, int rank, - uint64_t max_window, uint64_t chunk, uint64_t queue_bytes, - uint64_t out[SIRCL_FABRIC_MAX_WORLD][SIRCL_FABRIC_MAX_LANES], - sircl_fabric_error *error); -int sircl_fabric_chain_order(const sircl_fabric_routes *routes, int *order, - sircl_fabric_error *error); -int sircl_fabric_ring_window(const sircl_fabric_routes *routes, const int *order, - uint64_t chunk, uint64_t queue_bytes, uint64_t *window, - sircl_fabric_error *error); - -int sircl_protocol_stripe(uint64_t packs, int lanes, int lane, sircl_pack_range *out); -int sircl_protocol_chunk(uint64_t packs, int world, int index, sircl_pack_range *out); -int sircl_protocol_flag_index(int namespace_id, int source, int slot, int lane, - int world, int lanes, uint32_t *out); -int sircl_protocol_op_word(int op, uint32_t bytes, uint32_t *out); -int sircl_protocol_descriptor(const sircl_phase *phase, int world, uint32_t *out); -int sircl_protocol_swing(int world, int rank, int *owners, - sircl_phase phases[SIRCL_PROTOCOL_MAX_PHASES], int *phase_count); -int sircl_protocol_select(uint64_t bytes, int algorithm, int large_algorithm, - uint64_t oneshot_max, uint64_t swing_above, - unsigned available_mask, int *out); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/transport-core/src/fabric.c b/transport-core/src/fabric.c deleted file mode 100644 index 5204fc8..0000000 --- a/transport-core/src/fabric.c +++ /dev/null @@ -1,439 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0; extracted from libsircl 947bce1e. */ -#include "sircl_fabric.h" -#include -#include -#include -#include -#include -#include -#include - -#define FW SIRCL_FABRIC_MAX_WORLD -#define FL SIRCL_FABRIC_MAX_LANES - -static int fail(sircl_fabric_error *e, int code, const char *fmt, ...) { - if (e) { va_list ap; e->code = code; va_start(ap, fmt); - vsnprintf(e->message, sizeof e->message, fmt, ap); va_end(ap); } - return -1; -} -static void clear_error(sircl_fabric_error *e) { if (e) memset(e, 0, sizeof *e); } -static const char *devices[4] = {"rocep1s0f0", "roceP2p1s0f0", "rocep1s0f1", "roceP2p1s0f1"}; -const char *sircl_fabric_role_device(int role) { return role >= 0 && role < 4 ? devices[role] : NULL; } -int sircl_fabric_role_of(const char *device) { - int i; if (!device) return -1; - for (i = 0; i < 4; i++) if (!strcmp(device, devices[i])) return i; - return -1; -} -static int node_at(const sircl_fabric_layout *l, int position) { - int i; for (i = 0; i < l->node_count; i++) if (l->nodes[i] == position) return i; - return -1; -} -static int cross(const sircl_fabric_layout *l, int position, int port, sircl_fabric_step *s) { - int i; for (i = 0; i < l->cable_count; i++) { - const sircl_cable *c = &l->cables[i]; - if (c->a == position && c->a_port == port) { - *s = (sircl_fabric_step){position, port, c->b, c->b_port}; return 1; - } - if (c->b == position && c->b_port == port) { - *s = (sircl_fabric_step){position, port, c->a, c->a_port}; return 1; - } - } return 0; -} -static int walk(const sircl_fabric_layout *l, int a, int port, int b, - sircl_fabric_step steps[FW]) { - int n, here = a, out = port; - for (n = 0; n < l->node_count; n++) { - if (!cross(l, here, out, &steps[n])) return 0; - if (steps[n].dst == b) return n + 1; - here = steps[n].dst; out = 1 - steps[n].dst_port; - } return 0; -} -static int layout_valid(const sircl_fabric_layout *l) { - sircl_fabric_layout checked; - if (!l || l->world < 2 || l->world > FW || l->node_count < l->world || - l->node_count > FW || l->cable_count < 1 || l->cable_count > FW) return 0; - if (sircl_fabric_layout_init(&checked, l->cables, l->cable_count, l->positions, l->world, NULL)) return 0; - return l->node_count == checked.node_count && l->cycle == checked.cycle && - !memcmp(l->nodes, checked.nodes, (size_t)l->node_count * sizeof l->nodes[0]); -} -static int routes_valid(const sircl_fabric_routes *r) { - int rank, peer, lane; - if (!r || !layout_valid(&r->layout) || r->lanes < 1 || r->lanes > FL) return 0; - for (rank = 0; rank < r->layout.world; rank++) for (peer = 0; peer < r->layout.world; peer++) if (rank != peer) - for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; - int k, here = r->layout.positions[rank], port; - if (route->hops < 1 || route->hops > r->layout.node_count || route->local_role < 0 || - route->local_role > 3 || route->remote_role < 0 || route->remote_role > 3) return 0; - port = route->local_role / 2; - for (k = 0; k < route->hops; k++) { - sircl_fabric_step expected; - const sircl_fabric_step *step = &route->steps[k]; - if (!cross(&r->layout, here, port, &expected) || step->src != expected.src || - step->src_port != expected.src_port || step->dst != expected.dst || step->dst_port != expected.dst_port) return 0; - here = step->dst; port = 1 - step->dst_port; - } - if (here != r->layout.positions[peer] || route->remote_role != - route->steps[route->hops - 1].dst_port * 2 + route->local_role % 2) return 0; - } - return 1; -} -int sircl_fabric_layout_init(sircl_fabric_layout *out, const sircl_cable *cables, - int cable_count, const int *positions, int world, sircl_fabric_error *e) { - sircl_fabric_layout t; int i, j, degree[FW] = {0}, reached[FW] = {0}; - clear_error(e); - if (!out || !cables || !positions || world < 2 || world > FW || cable_count < 1 || cable_count > FW) - return fail(e, SIRCL_FABRIC_INVALID, "a fabric needs 2-16 ranks and 1-16 cables"); - memset(&t, 0, sizeof t); t.world = world; t.cable_count = cable_count; - for (i = 0; i < cable_count; i++) { - const sircl_cable *c = &cables[i]; int ends[2] = {c->a, c->b}; - if (c->a < 0 || c->b < 0 || c->a == c->b || c->a_port < 0 || c->a_port > 1 || c->b_port < 0 || c->b_port > 1) - return fail(e, SIRCL_FABRIC_INVALID, "cable %d has invalid endpoints or ports", i); - for (j = 0; j < i; j++) { - const sircl_cable *d = &cables[j]; - if ((c->a == d->a && c->a_port == d->a_port) || (c->a == d->b && c->a_port == d->b_port) || - (c->b == d->a && c->b_port == d->a_port) || (c->b == d->b && c->b_port == d->b_port)) - return fail(e, SIRCL_FABRIC_INVALID, "cable %d reuses a fabric port", i); - } - t.cables[i] = *c; - for (j = 0; j < 2; j++) if (node_at(&t, ends[j]) < 0) { - if (t.node_count == FW) return fail(e, SIRCL_FABRIC_LIMIT, "fabric exceeds 16 positions"); - t.nodes[t.node_count++] = ends[j]; - } - } - for (i = 0; i < t.node_count; i++) for (j = i + 1; j < t.node_count; j++) - if (t.nodes[j] < t.nodes[i]) { int p = t.nodes[i]; t.nodes[i] = t.nodes[j]; t.nodes[j] = p; } - for (i = 0; i < cable_count; i++) { degree[node_at(&t, cables[i].a)]++; degree[node_at(&t, cables[i].b)]++; } - t.cycle = 1; for (i = 0; i < t.node_count; i++) if (degree[i] != 2) t.cycle = 0; - reached[0] = 1; - for (i = 0; i < t.node_count; i++) for (j = 0; j < cable_count; j++) { - int a = node_at(&t, cables[j].a), b = node_at(&t, cables[j].b); - if (reached[a] || reached[b]) reached[a] = reached[b] = 1; - } - for (i = 0; i < t.node_count; i++) if (!reached[i]) - return fail(e, SIRCL_FABRIC_UNREACHABLE, "fabric contains disconnected position %d", t.nodes[i]); - for (i = 0; i < world; i++) { - if (node_at(&t, positions[i]) < 0) return fail(e, SIRCL_FABRIC_INVALID, "rank %d position %d is not on fabric", i, positions[i]); - for (j = 0; j < i; j++) if (positions[j] == positions[i]) return fail(e, SIRCL_FABRIC_INVALID, "ranks need distinct fabric positions"); - t.positions[i] = positions[i]; - } - *out = t; return 0; -} -static void skip_space(const char **p) { while (isspace((unsigned char)**p)) (*p)++; } -static int number(const char **p, int *out) { - char *end; long value; skip_space(p); if (!isdigit((unsigned char)**p)) return -1; - errno = 0; value = strtol(*p, &end, 10); if (errno || value > INT_MAX) return -1; - *p = end; *out = (int)value; skip_space(p); return 0; -} -static int token(const char **p, const char *text) { - size_t n = strlen(text); skip_space(p); if (strncmp(*p, text, n)) return -1; - *p += n; skip_space(p); return 0; -} -static int parse_cable(const char **p, sircl_cable *c) { - if (number(p, &c->a) || token(p, ".port") || (**p != '0' && **p != '1')) return -1; - c->a_port = *(*p)++ - '0'; - if (token(p, "-") || number(p, &c->b) || token(p, ".port") || (**p != '0' && **p != '1')) return -1; - c->b_port = *(*p)++ - '0'; skip_space(p); - return 0; -} -static int parse_positions(const char **p, int positions[FW], int *count) { - *count = 0; - do { - if (*count == FW || number(p, &positions[(*count)++])) return -1; - if (**p != ',') break; - (*p)++; - } while (1); - return **p ? -1 : 0; -} -int sircl_fabric_layout_parse(const char *text, sircl_fabric_layout *out, sircl_fabric_error *e) { - sircl_cable cables[FW]; int positions[FW], count = 0, world = 0, i, first, last; const char *p = text; - clear_error(e); if (!text || !out) return fail(e, SIRCL_FABRIC_INVALID, "layout is required"); - skip_space(&p); - if (!strncmp(p, "cables=", 7)) { - p += 7; - do { if (count == FW || parse_cable(&p, &cables[count++])) goto malformed; - if (*p != ',') break; - p++; - } while (1); - if (token(&p, ";positions=") || parse_positions(&p, positions, &world)) goto malformed; - } else if (!strncmp(p, "ring:", 5)) { - p += 5; if (number(&p, &count) || count < 2 || count > FW) goto malformed; - for (i = 0; i < count; i++) { cables[i] = (sircl_cable){i, 0, (i + 1) % count, 1}; positions[i] = i; } - world = count; - if (*p == ':') { p++; if (parse_positions(&p, positions, &world)) goto malformed; } - else if (*p) goto malformed; - } else if (!strncmp(p, "path:", 5)) { - p += 5; if (number(&p, &first) || token(&p, "-") || number(&p, &last) || last <= first || last - first >= FW) goto malformed; - count = last - first; world = count + 1; - for (i = 0; i < world; i++) positions[i] = first + i; - for (i = 0; i < count; i++) cables[i] = (sircl_cable){first + i, 0, first + i + 1, 1}; - if (*p == ':') { p++; if (parse_positions(&p, positions, &world)) goto malformed; } - else if (*p) goto malformed; - } else goto malformed; - return sircl_fabric_layout_init(out, cables, count, positions, world, e); -malformed: return fail(e, SIRCL_FABRIC_INVALID, "malformed layout; use ring:, path:, or cables=...;positions=..."); -} -int sircl_fabric_derive(const sircl_fabric_layout *l, int lanes, sircl_fabric_routes *out, sircl_fabric_error *e) { - int rank, peer, lane; clear_error(e); - if (!layout_valid(l) || !out || lanes < 1 || lanes > FL) return fail(e, SIRCL_FABRIC_INVALID, "invalid layout or lane count"); - /* Revalidate public structures, including port uniqueness and connectivity. */ - { sircl_fabric_layout checked; - if (sircl_fabric_layout_init(&checked, l->cables, l->cable_count, l->positions, l->world, e)) return -1; - out->layout = checked; - } - out->lanes = lanes; memset(out->route, 0, sizeof out->route); l = &out->layout; - for (rank = 0; rank < l->world; rank++) for (peer = 0; peer < l->world; peer++) if (rank != peer) { - sircl_fabric_step paths[2][FW]; int n[2], chosen[2]; - n[0] = walk(l, l->positions[rank], 0, l->positions[peer], paths[0]); - n[1] = walk(l, l->positions[rank], 1, l->positions[peer], paths[1]); - if (!n[0] && !n[1]) return fail(e, SIRCL_FABRIC_UNREACHABLE, "rank %d cannot reach rank %d", rank, peer); - if (!n[1] || (n[0] && n[0] < n[1])) chosen[0] = chosen[1] = 0; - else if (!n[0] || n[1] < n[0]) chosen[0] = chosen[1] = 1; - else { - /* Path A leaves the numerically smaller endpoint through port 0. */ - int a = l->positions[rank] < l->positions[peer] ? 0 : (paths[0][n[0]-1].dst_port == 0 ? 0 : 1); - chosen[0] = a; chosen[1] = 1 - a; - } - for (lane = 0; lane < lanes; lane++) { - int which = chosen[lane]; sircl_lane_route *r = &out->route[rank][peer][lane]; - r->hops = n[which]; memcpy(r->steps, paths[which], (size_t)r->hops * sizeof r->steps[0]); - r->local_role = r->steps[0].src_port * 2 + lane; - r->remote_role = r->steps[r->hops - 1].dst_port * 2 + lane; - } - } return 0; -} -int sircl_fabric_map(const sircl_fabric_routes *r, int rank, sircl_route_map *out, sircl_fabric_error *e) { - int peer, lane; clear_error(e); - if (!routes_valid(r) || !out || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid routes or rank"); - memset(out, 0, sizeof *out); - for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) { - out->count[peer] = (uint8_t)r->lanes; - for (lane = 0; lane < r->lanes; lane++) out->role[peer][lane] = (uint8_t)r->route[rank][peer][lane].local_role; - } return 0; -} -int sircl_fabric_map_parse(const char *text, sircl_route_map *out, sircl_fabric_error *e) { - sircl_route_map t; const char *p = text; int seen[FW] = {0}; clear_error(e); - if (!text || !out) return fail(e, SIRCL_FABRIC_INVALID, "route map is required"); - memset(&t, 0, sizeof t); skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "route map is empty"); - while (*p) { - int peer, lane = 0; - if (number(&p, &peer) || peer >= FW || token(&p, "=")) return fail(e, SIRCL_FABRIC_INVALID, "malformed route map entry"); - if (seen[peer]++) return fail(e, SIRCL_FABRIC_INVALID, "route map names rank %d twice", peer); - do { - const char *start; size_t len; char device[64]; int role; - skip_space(&p); start = p; while (*p && *p != '/' && *p != ',' && !isspace((unsigned char)*p)) p++; - len = (size_t)(p - start); skip_space(&p); - if (!len || len >= sizeof device || lane == FL) return fail(e, SIRCL_FABRIC_INVALID, "invalid lane list of rank %d", peer); - memcpy(device, start, len); device[len] = 0; role = sircl_fabric_role_of(device); - if (role < 0) return fail(e, SIRCL_FABRIC_INVALID, "device %s has no known role", device); - t.role[peer][lane++] = (uint8_t)role; - if (*p != '/') break; - p++; - } while (1); - t.count[peer] = (uint8_t)lane; - if (!*p) break; - if (*p != ',') return fail(e, SIRCL_FABRIC_INVALID, "malformed route map separator"); - p++; skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "route map has an empty entry"); - } *out = t; return 0; -} -int sircl_fabric_map_format(const sircl_route_map *map, int world, char *out, size_t cap, sircl_fabric_error *e) { - int peer, lane, entries = 0; size_t used = 0; clear_error(e); - if (!map || !out || !cap || world < 2 || world > FW) return fail(e, SIRCL_FABRIC_INVALID, "invalid route formatter arguments"); - out[0] = 0; - for (peer = 0; peer < world; peer++) if (map->count[peer]) { - int n; if (map->count[peer] > FL) return fail(e, SIRCL_FABRIC_INVALID, "unsupported lane count"); - n = snprintf(out + used, cap - used, "%s%d=", entries++ ? "," : "", peer); - if (n < 0 || (size_t)n >= cap - used) goto too_small; - used += (size_t)n; - for (lane = 0; lane < map->count[peer]; lane++) { - const char *device = sircl_fabric_role_device(map->role[peer][lane]); - if (!device) return fail(e, SIRCL_FABRIC_INVALID, "invalid device role"); - n = snprintf(out + used, cap - used, "%s%s", lane ? "/" : "", device); - if (n < 0 || (size_t)n >= cap - used) goto too_small; - used += (size_t)n; - } - } return 0; -too_small: return fail(e, SIRCL_FABRIC_LIMIT, "route text buffer is too small"); -} -int sircl_fabric_map_validate(const sircl_fabric_layout *l, const sircl_route_map *map, - int rank, int world, int max_relays, sircl_fabric_error *e) { - int peer, lane, lanes = 0; clear_error(e); - if (!map || world < 2 || world > FW || rank < 0 || rank >= world || max_relays < 0 || - (l && (!layout_valid(l) || l->world != world))) return fail(e, SIRCL_FABRIC_INVALID, "invalid route validation arguments"); - if (map->count[rank]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's map names its own rank", rank); - for (peer = 0; peer < FW; peer++) if (peer != rank) { - if (peer >= world) { if (map->count[peer]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d is outside session", peer); continue; } - if (!map->count[peer]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's map has no entry for rank %d", rank, peer); - if (map->count[peer] > FL || (lanes && map->count[peer] != lanes)) return fail(e, SIRCL_FABRIC_INVALID, "rank %d has different or unsupported lane counts", rank); - lanes = map->count[peer]; - if (lanes == 2 && map->role[peer][0] == map->role[peer][1]) return fail(e, SIRCL_FABRIC_INVALID, "rank %d's entry for rank %d names device twice", rank, peer); - for (lane = 0; lane < lanes; lane++) { - int role = map->role[peer][lane]; sircl_fabric_step steps[FW]; int hops; - if (role > 3) return fail(e, SIRCL_FABRIC_INVALID, "rank %d has unknown role", rank); - if (!l) continue; - hops = walk(l, l->positions[rank], role / 2, l->positions[peer], steps); - if (!hops) return fail(e, SIRCL_FABRIC_UNREACHABLE, "rank %d lane %d to rank %d leaves the group's fabric", rank, lane, peer); - if (hops - 1 > max_relays) return fail(e, SIRCL_FABRIC_LIMIT, "rank %d lane %d to rank %d crosses %d relays; limit is %d", rank, lane, peer, hops - 1, max_relays); - } - } return 0; -} -int sircl_fabric_complementary(const sircl_fabric_layout *l, const sircl_route_map *maps, sircl_fabric_error *e) { - int rank, peer, lane; clear_error(e); - if (!layout_valid(l) || !maps) return fail(e, SIRCL_FABRIC_INVALID, "layout and maps are required"); - for (rank = 0; rank < l->world; rank++) if (sircl_fabric_map_validate(l, &maps[rank], rank, l->world, FW, e)) return -1; - for (rank = 0; rank < l->world; rank++) for (peer = 0; peer < l->world; peer++) if (peer != rank) { - if (maps[rank].count[peer] != maps[peer].count[rank]) return fail(e, SIRCL_FABRIC_MISMATCH, "ranks %d and %d disagree on lanes", rank, peer); - for (lane = 0; lane < maps[rank].count[peer]; lane++) { - int mine = maps[rank].role[peer][lane]; sircl_fabric_step steps[FW]; - int hops = walk(l, l->positions[rank], mine / 2, l->positions[peer], steps); - int expected = steps[hops - 1].dst_port * 2 + mine % 2; - if (maps[peer].role[rank][lane] != expected) return fail(e, SIRCL_FABRIC_MISMATCH, - "rank %d lane %d arrives on rank %d port %d (%s); peer lists %s", rank, lane, peer, - steps[hops - 1].dst_port, devices[expected], devices[maps[peer].role[rank][lane]]); - } - } return 0; -} -int sircl_fabric_agree(const sircl_fabric_layout *l, int world, int lanes, - const sircl_fabric_rank_record *records, int max_relays, sircl_fabric_error *e) { - sircl_route_map maps[FW]; int rank, peer, lane; clear_error(e); - if (!records || world < 2 || world > FW || lanes < 1 || lanes > FL || (l && (!layout_valid(l) || l->world != world))) - return fail(e, SIRCL_FABRIC_INVALID, "invalid setup agreement arguments"); - for (rank = 0; rank < world; rank++) if (records[rank].local_error) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d: %s", rank, records[rank].local_error); - for (rank = 0; rank < world; rank++) { - if (records[rank].shared_size && !records[rank].shared_settings) return fail(e, SIRCL_FABRIC_INVALID, "rank %d lacks shared settings", rank); - if (records[rank].shared_size != records[0].shared_size || (records[0].shared_size && - memcmp(records[rank].shared_settings, records[0].shared_settings, records[0].shared_size))) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d shared settings differ from rank 0", rank); - maps[rank] = records[rank].map; - for (peer = 0; peer < world; peer++) if (maps[rank].count[peer] != (peer == rank ? 0 : lanes)) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d has incorrect lane count toward rank %d", rank, peer); - if (sircl_fabric_map_validate(l, &maps[rank], rank, world, max_relays, e)) return -1; - } - if (l) return sircl_fabric_complementary(l, maps, e); - for (rank = 0; rank < world; rank++) for (peer = 0; peer < world; peer++) if (peer != rank) - for (lane = 0; lane < lanes; lane++) if (maps[rank].role[peer][lane] % 2 != maps[peer].role[rank][lane] % 2) - return fail(e, SIRCL_FABRIC_MISMATCH, "rank %d and rank %d lane %d use different function classes", rank, peer, lane); - return 0; -} -int sircl_fabric_post_order(const sircl_fabric_routes *r, int rank, const char *order, int *peers, sircl_fabric_error *e) { - int world, i, n = 0, seen[FW] = {0}; const char *p = order; char text[256]; size_t len; clear_error(e); - if (!routes_valid(r) || !peers || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid posting order arguments"); - world = r->layout.world; - if (!p) p = "rank"; - skip_space(&p); len = strlen(p); while (len && isspace((unsigned char)p[len-1])) len--; - if (len >= sizeof text) return fail(e, SIRCL_FABRIC_INVALID, "posting order is too long"); - memcpy(text, p, len); text[len] = 0; p = text; - if (!len || !strcmp(p, "rank")) { for (i = 0; i < world; i++) if (i != rank) peers[n++] = i; return 0; } - if (!strcmp(p, "ring-farthest")) { - for (i = world / 2; i >= 1; i--) { - int a = (rank + i) % world, b = (rank + world - i) % world; peers[n++] = a; if (a != b) peers[n++] = b; - } return 0; - } - if (!strcmp(p, "farthest")) { - int distances[FW] = {0}, max = 0, d, port; - for (i = 0; i < world; i++) if (i != rank) { int lane; - for (lane = 0; lane < r->lanes; lane++) if (r->route[rank][i][lane].hops - 1 > distances[i]) distances[i] = r->route[rank][i][lane].hops - 1; - if (distances[i] > max) max = distances[i]; - } - for (d = max; d >= 0; d--) { - int next[2] = {0, 0}, queues[2][FW], count[2] = {0, 0}; - for (i = 0; i < world; i++) if (i != rank && distances[i] == d) { port = r->route[rank][i][0].local_role / 2; queues[port][count[port]++] = i; } - while (next[0] < count[0] || next[1] < count[1]) for (port = 0; port < 2; port++) - if (next[port] < count[port]) peers[n++] = queues[port][next[port]++]; - } return 0; - } - while (*p) { int peer; - if (number(&p, &peer) || peer >= world || peer == rank || seen[peer]++ || n == world - 1) - return fail(e, SIRCL_FABRIC_INVALID, "posting order must name every peer exactly once"); - peers[n++] = peer; if (!*p) break; if (*p != ',') return fail(e, SIRCL_FABRIC_INVALID, "malformed posting order"); p++; - skip_space(&p); if (!*p) return fail(e, SIRCL_FABRIC_INVALID, "posting order ends in an empty peer"); - } - return n == world - 1 ? 0 : fail(e, SIRCL_FABRIC_INVALID, "posting order must name every peer exactly once"); -} -static int queue_loads(const sircl_fabric_routes *r, const int *order, int load[FW][2][2]) { - int rank, peer, lane, k; memset(load, 0, sizeof(int) * FW * 2 * 2); - for (rank = 0; rank < r->layout.world; rank++) for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) { - if (order) { int i, enabled = 0; - for (i = 0; i < r->layout.world; i++) { - if (order[i] == rank && order[(i + 1) % r->layout.world] == peer) enabled = 1; - } - if (!enabled) continue; - } - for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; - if (route->hops < 1 || route->hops > r->layout.node_count || route->local_role < 0 || route->local_role > 3) return -1; - for (k = 0; k < route->hops - 1; k++) { - int node = node_at(&r->layout, route->steps[k].dst), port = route->steps[k].dst_port; - if (node < 0 || port < 0 || port > 1) return -1; - load[node][route->local_role % 2][1 - port]++; - } - } - } return 0; -} -int sircl_fabric_relay_load(const sircl_fabric_routes *r, int *busiest, double *factor, sircl_fabric_error *e) { - int load[FW][2][2], i, p, f, max = 0; clear_error(e); - if (!routes_valid(r) || !busiest || !factor || queue_loads(r, NULL, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (i = 0; i < r->layout.node_count; i++) for (p = 0; p < 2; p++) for (f = 0; f < 2; f++) if (load[i][f][p] > max) max = load[i][f][p]; - *busiest = max; *factor = (double)max / r->lanes; return 0; -} -static uint64_t queue_share(uint64_t bytes) { return (bytes / 4) * 3 + (bytes % 4) * 3 / 4; } -int sircl_fabric_forward_windows(const sircl_fabric_routes *r, int rank, uint64_t max_window, - uint64_t chunk, uint64_t queue_bytes, uint64_t out[FW][FL], sircl_fabric_error *e) { - int load[FW][2][2], peer, lane; clear_error(e); - if (!routes_valid(r) || !out || rank < 0 || rank >= r->layout.world) return fail(e, SIRCL_FABRIC_INVALID, "invalid forward window arguments"); - memset(out, 0, sizeof(uint64_t) * FW * FL); if (!max_window) return 0; - if (!chunk || chunk % 16 || max_window < chunk) return fail(e, SIRCL_FABRIC_INVALID, "forward chunk must be a positive multiple of 16 within window"); - if (queue_loads(r, NULL, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (peer = 0; peer < r->layout.world; peer++) if (peer != rank) for (lane = 0; lane < r->lanes; lane++) { - const sircl_lane_route *route = &r->route[rank][peer][lane]; int k, sharing = 0; - for (k = 0; k < route->hops - 1; k++) { int q = load[node_at(&r->layout, route->steps[k].dst)][route->local_role % 2][1 - route->steps[k].dst_port]; if (q > sharing) sharing = q; } - if (sharing) { uint64_t limit = queue_share(queue_bytes) / (uint64_t)sharing; - /* Fail closed if one chunk already exceeds the queue budget. */ - if (limit < chunk) return fail(e, SIRCL_FABRIC_LIMIT, "relay queue budget cannot hold one chunk per lane"); - if (max_window < limit) limit = max_window; - out[peer][lane] = limit / chunk * chunk; - } - } return 0; -} -int sircl_fabric_chain_order(const sircl_fabric_routes *r, int *order, sircl_fabric_error *e) { - const sircl_fabric_layout *l; int nodes[FW], visited[FW] = {0}, i, start, previous = -1; clear_error(e); - if (!routes_valid(r) || !order) return fail(e, SIRCL_FABRIC_INVALID, "invalid chain arguments"); - l = &r->layout; - if (l->world != l->node_count) return fail(e, SIRCL_FABRIC_UNREACHABLE, "chain requires a rank at every fabric position"); - start = l->positions[0]; - if (!l->cycle) for (i = 0; i < l->node_count; i++) { - sircl_fabric_step s; if (!cross(l, l->nodes[i], 0, &s) || !cross(l, l->nodes[i], 1, &s)) { start = l->nodes[i]; break; } - } - nodes[0] = start; visited[node_at(l, start)] = 1; - for (i = 1; i < l->world; i++) { - int port, found = 0; sircl_fabric_step step; - for (port = 0; port < 2; port++) if (cross(l, nodes[i-1], port, &step) && - step.dst != previous && !visited[node_at(l, step.dst)]) { - nodes[i] = step.dst; visited[node_at(l, step.dst)] = 1; found = 1; break; - } - if (!found) return fail(e, SIRCL_FABRIC_UNREACHABLE, "fabric has no complete chain"); - previous = nodes[i-1]; - } - for (i = 0; i < l->world; i++) { int rank; for (rank = 0; rank < l->world && l->positions[rank] != nodes[i]; rank++) { } - order[i] = rank; - } - for (i = 0; i < l->world - 1; i++) { int lane; for (lane = 0; lane < r->lanes; lane++) - if (r->route[order[i]][order[i+1]][lane].hops != 1 || r->route[order[i+1]][order[i]][lane].hops != 1) - return fail(e, SIRCL_FABRIC_UNREACHABLE, "chain edge has a relayed lane"); - } return 0; -} -int sircl_fabric_ring_window(const sircl_fabric_routes *r, const int *order, uint64_t chunk, - uint64_t queue_bytes, uint64_t *window, sircl_fabric_error *e) { - int load[FW][2][2], seen[FW] = {0}, i, f, p, any = 0; clear_error(e); - if (!routes_valid(r) || !order || !window || !chunk || chunk % 16) return fail(e, SIRCL_FABRIC_INVALID, "invalid ring window arguments"); - for (i = 0; i < r->layout.world; i++) if (order[i] < 0 || order[i] >= r->layout.world || seen[order[i]]++) - return fail(e, SIRCL_FABRIC_INVALID, "ring order must name every rank exactly once"); - if (queue_loads(r, order, load)) return fail(e, SIRCL_FABRIC_INVALID, "invalid relay routes"); - for (i = 0; i < r->layout.node_count; i++) for (f = 0; f < 2; f++) for (p = 0; p < 2; p++) { - if (load[i][f][p] > 1) return fail(e, SIRCL_FABRIC_LIMIT, "relay %d function %d port %d carries multiple ring lanes", r->layout.nodes[i], f, p); - if (load[i][f][p]) any = 1; - } - *window = any ? queue_share(queue_bytes) / chunk * chunk : 0; - return any && *window < chunk ? fail(e, SIRCL_FABRIC_LIMIT, "relay queue holds less than one chunk") : 0; -} diff --git a/transport-core/src/shm_verbs.c b/transport-core/src/shm_verbs.c index 7269707..5db479b 100644 --- a/transport-core/src/shm_verbs.c +++ b/transport-core/src/shm_verbs.c @@ -184,6 +184,7 @@ typedef struct { int shared; /* index in F->qp */ int device; /* index in F->dev */ int errored; + uint32_t max_inline; uint32_t generation; uint32_t dest_qp_num; sv_wr *queue; @@ -191,6 +192,9 @@ typedef struct { uint64_t posted, executed, completed; /* diagnostics: writes posted, executed, completions delivered */ } sv_lqp; +/* Strict lock ordering across this translation unit: + * executor_lock -> local -> fab_lock() (F->lock). + * Never acquire `local` while holding `fab_lock()`, and never acquire `executor_lock` inside the worker. */ static pthread_mutex_t local = PTHREAD_MUTEX_INITIALIZER; static sv_cq cqs[SV_LOCAL_CQS]; static sv_lqp *qps[SV_LOCAL_QPS]; @@ -360,7 +364,8 @@ static enum ibv_wc_status resolve_write(const sv_lqp *q, const sv_wr *w, char *s snprintf(reason, reason_len, "the region of rkey 0x%x is not remote-writable", w->rkey); return IBV_WC_REM_ACCESS_ERR; } - if (w->remote_addr < target->addr || w->remote_addr + w->length > target->addr + target->length) { + if (w->remote_addr < target->addr || w->remote_addr - target->addr > target->length || + w->length > target->length - (w->remote_addr - target->addr)) { snprintf(reason, reason_len, "%u bytes at 0x%llx lie outside the region of rkey 0x%x (0x%llx, %llu bytes)", w->length, (unsigned long long)w->remote_addr, w->rkey, (unsigned long long)target->addr, (unsigned long long)target->length); @@ -375,7 +380,8 @@ static enum ibv_wc_status resolve_write(const sv_lqp *q, const sv_wr *w, char *s for (int i = 0; i < SV_MAX_MRS; ++i) { const sv_mr *m = &F->mr[i]; if (m->used && m->pid == (int)getpid() && m->device == q->device && m->lkey == w->lkey && - w->local_addr >= m->addr && w->local_addr + w->length <= m->addr + m->length) { + w->local_addr >= m->addr && w->local_addr - m->addr <= m->length && + w->length <= m->length - (w->local_addr - m->addr)) { *source = (const void *)(uintptr_t)w->local_addr; return IBV_WC_SUCCESS; } @@ -555,8 +561,8 @@ struct ibv_device **ibv_get_device_list(int *num_devices) { return NULL; } int n = 0; - fab_lock(); pthread_mutex_lock(&local); + fab_lock(); for (int i = 0; i < SV_MAX_DEVICES; ++i) { if (F->dev[i].used && F->dev[i].pid == (int)getpid()) { snprintf(devices[i].name, sizeof devices[i].name, "%s", F->dev[i].name); @@ -564,8 +570,8 @@ struct ibv_device **ibv_get_device_list(int *num_devices) { list[n++] = &devices[i]; } } - pthread_mutex_unlock(&local); fab_unlock(); + pthread_mutex_unlock(&local); if (num_devices) *num_devices = n; return list; } @@ -776,6 +782,15 @@ struct ibv_qp *ibv_create_qp(struct ibv_pd *pd, struct ibv_qp_init_attr *attr) { errno = ENOMEM; return NULL; } + uint32_t max_inline = SV_INLINE; + const char *inline_env = getenv("SIRCL_EMU_MAX_INLINE"); + if (inline_env && *inline_env) { + char *end = NULL; + unsigned long v = strtoul(inline_env, &end, 10); + if (!*end && v <= SV_INLINE) max_inline = (uint32_t)v; + } + q->max_inline = attr->cap.max_inline_data < max_inline ? attr->cap.max_inline_data : max_inline; + attr->cap.max_inline_data = q->max_inline; q->shared = shared; q->generation = ++generations; q->qp.context = pd->context; @@ -867,7 +882,7 @@ int ibv_post_send(struct ibv_qp *qp, struct ibv_send_wr *wr, struct ibv_send_wr int rc = 0; if (q->qp.state != IBV_QPS_RTS || w->opcode != IBV_WR_RDMA_WRITE || w->num_sge != 1) rc = EINVAL; - else if ((w->send_flags & IBV_SEND_INLINE) && w->sg_list[0].length > SV_INLINE) + else if ((w->send_flags & IBV_SEND_INLINE) && w->sg_list[0].length > q->max_inline) rc = EINVAL; else if (q->count == q->capacity) rc = ENOMEM; diff --git a/transport-core/src/sysfs.c b/transport-core/src/sysfs.c index cd5e5f7..a956d4a 100644 --- a/transport-core/src/sysfs.c +++ b/transport-core/src/sysfs.c @@ -13,7 +13,9 @@ uint64_t sircl_core_sysfs_guid(const char *root, const char *name) { fclose(f); uint64_t v = 0; for (char *c = text; *c; ++c) { - int n = (*c >= '0' && *c <= '9') ? *c - '0' : (*c >= 'a' && *c <= 'f') ? *c - 'a' + 10 : -1; + int n = (*c >= '0' && *c <= '9') ? *c - '0' + : (*c >= 'a' && *c <= 'f') ? *c - 'a' + 10 + : (*c >= 'A' && *c <= 'F') ? *c - 'A' + 10 : -1; if (n >= 0) v = v << 4 | (uint64_t)n; } return v; @@ -26,14 +28,36 @@ void sircl_core_sysfs_netdev(const char *root, const char *name, char *out, size out[0] = '\0'; DIR *dir = opendir(path); if (!dir) return; - for (struct dirent *e; (e = readdir(dir));) - if (e->d_name[0] != '.' && strlen(e->d_name) < len) { - memcpy(out, e->d_name, strlen(e->d_name) + 1); - break; - } + for (struct dirent *e; (e = readdir(dir));) { + if (e->d_name[0] == '.') continue; + size_t n = strlen(e->d_name); + if (n >= len) continue; + if (!out[0] || strcmp(e->d_name, out) < 0) memcpy(out, e->d_name, n + 1); + } closedir(dir); } +void sircl_core_sysfs_gid_netdev(const char *root, const char *name, unsigned port, + int gid_index, char *out, size_t len) { + if (!out || !len) return; + out[0] = '\0'; + if (gid_index >= 0) { + char path[256], text[128] = {0}; + snprintf(path, sizeof path, "%s/%s/ports/%u/gid_attrs/ndevs/%d", root, name, port, gid_index); + FILE *f = fopen(path, "r"); + if (f) { + if (fgets(text, sizeof text, f)) { + size_t n = strlen(text); + while (n && (text[n - 1] == '\n' || text[n - 1] == '\r' || text[n - 1] == ' ' || text[n - 1] == '\t')) + text[--n] = '\0'; + if (n > 0 && n < len) memcpy(out, text, n + 1); + } + fclose(f); + } + } + if (!out[0]) sircl_core_sysfs_netdev(root, name, out, len); +} + /* The GID index of the function's RoCE v2 IPv4 address: the lowest index whose type is "RoCE v2" and whose * GID is IPv4-mapped (as NCCL's IB transport prefers by default, net_ib/connect.cc:263-291). -1: none. */ int sircl_core_gid_index(const char *root, const char *name, unsigned port) { diff --git a/transport-core/src/topology.c b/transport-core/src/topology.c index a69abb8..aed1d38 100644 --- a/transport-core/src/topology.c +++ b/transport-core/src/topology.c @@ -52,6 +52,22 @@ static int function_name(const char *text) { return 1; } +/* A host name as fabric-tool's guard accepts it: ASCII letters, digits and `_.-`, starting with an + * ASCII letter or digit, at most 63 bytes. */ +static int host_name(const char *text) { + size_t n = strlen(text); + if (!n || n >= FIELD) return 0; + for (size_t i = 0; i < n; ++i) { + char ch = text[i]; + int alnum = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); + if (!alnum && (i == 0 || (ch != '_' && ch != '.' && ch != '-'))) return 0; + } + return 1; +} + +#define RELAY_BUDGET_MIN 65536u +#define RELAY_BUDGET_MAX 393216u + /* Parse a topology file (net_sircl.h "Topology file"). 0 on success; `err` says why not. */ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, char *err, size_t len) { memset(t, 0, sizeof *t); @@ -59,22 +75,15 @@ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, c snprintf(t->fn[0][1], FIELD, "roceP2p1s0f0"); snprintf(t->fn[1][0], FIELD, "rocep1s0f1"); snprintf(t->fn[1][1], FIELD, "roceP2p1s0f1"); - t->budget = 393216; /* 75 % of a ConnectX-7 hairpin queue of 512 KiB (SIRCL's relay budget) */ + t->budget = RELAY_BUDGET_MAX; /* 75 % of a ConnectX-7 hairpin queue of 512 KiB (SIRCL's relay budget) */ FILE *f = fopen(path, "r"); if (!f) return reject(err, len, "cannot open %s: %s", path, strerror(errno)); - char line[1024], cabling[16] = ""; + char *line = NULL; + size_t line_cap = 0; + char cabling[16] = ""; int lineno = 0, rc = 0, port_lanes[2] = {NET_SIRCL_MAX_LANES, NET_SIRCL_MAX_LANES}; - while (!rc && fgets(line, sizeof line, f)) { + while (!rc && getline(&line, &line_cap, f) >= 0) { ++lineno; - size_t got = strlen(line); - if (got == sizeof line - 1 && line[got - 1] != '\n') { - /* The buffer is full without a line end: more of this line follows unless the file ends here. */ - int next = fgetc(f); - if (next != EOF) { - rc = reject(err, len, "%s:%d: the line is longer than %zu characters", path, lineno, sizeof line - 2); - break; - } - } char *hash = strchr(line, '#'); if (hash) *hash = '\0'; char *save = NULL, *key = strtok_r(line, BLANK, &save); @@ -85,6 +94,8 @@ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, c rc = reject(err, len, "%s:%d: more than %d hosts", path, lineno, MAX_POSITIONS); else if (strlen(h) >= FIELD) rc = reject(err, len, "%s:%d: a host name is longer than %d characters", path, lineno, FIELD - 1); + else if (!host_name(h)) + rc = reject(err, len, "%s:%d: invalid host name %s", path, lineno, h); else snprintf(t->host[t->nhosts++], FIELD, "%s", h); } @@ -131,10 +142,13 @@ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, c int ok = v && *v && !strtok_r(NULL, BLANK, &save); for (const char *p = v; ok && *p; ++p) { if (*p < '0' || *p > '9') ok = 0; - else if ((b = b * 10 + (unsigned)(*p - '0')) > UINT32_MAX) ok = 0; + else if ((b = b * 10 + (unsigned)(*p - '0')) > RELAY_BUDGET_MAX) ok = 0; } - if (!ok || b == 0) rc = reject(err, len, "%s:%d: relay_budget is a positive byte count", path, lineno); - else t->budget = (uint32_t)b; + if (!ok || b < RELAY_BUDGET_MIN || b > RELAY_BUDGET_MAX) + rc = reject(err, len, "%s:%d: relay_budget is a positive byte count in %u..%u", + path, lineno, RELAY_BUDGET_MIN, RELAY_BUDGET_MAX); + else + t->budget = (uint32_t)b; } else if (!strcmp(key, "net-sircl-topology")) { if (strtok_r(NULL, BLANK, &save)) rc = reject(err, len, "%s:%d: unknown words after net-sircl-topology", path, lineno); @@ -143,6 +157,7 @@ int sircl_core_topology_parse(const char *path, struct sircl_core_topology *t, c } } if (!rc && ferror(f)) rc = reject(err, len, "cannot read %s", path); + free(line); fclose(f); if (rc) return rc; if (port_lanes[0] != port_lanes[1]) diff --git a/transport-core/tests/test_emulator_lifetime.c b/transport-core/tests/test_emulator_lifetime.c index 5755c21..5a8a650 100644 --- a/transport-core/tests/test_emulator_lifetime.c +++ b/transport-core/tests/test_emulator_lifetime.c @@ -212,13 +212,50 @@ static void registration_envelope(void) { cleanup(&e); } +static void *device_enum_worker(void *arg) { + int *stop = arg; + while (!__atomic_load_n(stop, __ATOMIC_ACQUIRE)) { + int n = 0; + struct ibv_device **list = ibv_get_device_list(&n); + assert(list && n >= 1); + ibv_free_device_list(list); + } + return NULL; +} + +/* Regression test for P0-5: concurrent ibv_get_device_list() and active RDMA execution + + * ibv_modify_qp() must share one strict lock order (local -> fab_lock) and never deadlock. */ +static void lock_order_stress(void) { + struct endpoint e = endpoint(5); + connect_qp(&e, e.qp->qp_num, e.gid); + char error[256]; + uint32_t *mem = sccl_emu_segment_alloc(4096, error, sizeof error); assert(mem); + struct ibv_mr *mr = sircl_core_reg_mr(e.pd, mem, 4096, IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE); assert(mr); + int stop = 0; + pthread_t lister; + assert(!pthread_create(&lister, NULL, device_enum_worker, &stop)); + for (unsigned i = 0; i < 500; ++i) { + mem[0] = i + 1; + assert(!sircl_core_post_write(e.qp, (uintptr_t)mem, mr->lkey, 4, (uintptr_t)(mem + 1), mr->rkey, + IBV_SEND_SIGNALED, i + 1)); + completion(&e); + assert(mem[1] == i + 1); + } + __atomic_store_n(&stop, 1, __ATOMIC_RELEASE); + assert(!pthread_join(lister, NULL)); + assert(!sircl_core_dereg_mr(mr)); + sccl_emu_segment_free(mem); + cleanup(&e); +} + int main(void) { char fabric[80]; snprintf(fabric, sizeof fabric, "/sircl-lifetime-%d", (int)getpid()); assert(!setenv("SIRCL_EMU_FABRIC", fabric, 1)); mapping_lifetimes(); worker_lifetime(); registration_envelope(); + lock_order_stress(); assert(!shm_unlink(fabric)); - puts("emulator: 530 remote lifetimes, serialized retirement, 1536 registrations and 300 CQs exact"); + puts("emulator: 530 remote lifetimes, serialized retirement, 1536 registrations, 300 CQs and lock-order stress exact"); return 0; } diff --git a/transport-core/tests/test_planning.py b/transport-core/tests/test_planning.py index 47c8b05..e8dfd02 100644 --- a/transport-core/tests/test_planning.py +++ b/transport-core/tests/test_planning.py @@ -22,6 +22,8 @@ def setUpClass(cls): cls.lib.sircl_core_sysfs_guid.argtypes = [ctypes.c_char_p, ctypes.c_char_p] cls.lib.sircl_core_sysfs_guid.restype = ctypes.c_uint64 cls.lib.sircl_core_sysfs_netdev.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t] + cls.lib.sircl_core_sysfs_gid_netdev.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint, + ctypes.c_int, ctypes.c_char_p, ctypes.c_size_t] cls.lib.sircl_core_topology_parse.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] @classmethod @@ -46,13 +48,20 @@ def test_missing_gid_is_explicit(self): def test_guid_and_netdev(self): base = self.root / "devices/mlx1" - (base / "device/net/eth-test").mkdir(parents=True) - (base / "sys_image_guid").write_text("0123:4567:89ab:cdef\n") + (base / "device/net/eth-zeta").mkdir(parents=True) + (base / "device/net/eth-alpha").mkdir(parents=True) + (base / "ports/1/gid_attrs/ndevs").mkdir(parents=True) + (base / "ports/1/gid_attrs/ndevs/3").write_text("eth-gid3\n") + (base / "sys_image_guid").write_text("0123:4567:89AB:CDEF\n") root = str(self.root / "devices").encode() self.assertEqual(self.lib.sircl_core_sysfs_guid(root, b"mlx1"), 0x0123456789ABCDEF) out = ctypes.create_string_buffer(64) self.lib.sircl_core_sysfs_netdev(root, b"mlx1", out, len(out)) - self.assertEqual(out.value, b"eth-test") + self.assertEqual(out.value, b"eth-alpha") + self.lib.sircl_core_sysfs_gid_netdev(root, b"mlx1", 1, 3, out, len(out)) + self.assertEqual(out.value, b"eth-gid3") + self.lib.sircl_core_sysfs_gid_netdev(root, b"mlx1", 1, 9, out, len(out)) + self.assertEqual(out.value, b"eth-alpha") def test_topology_rejects_cable_capacity_overflow(self): f = self.root / "overflow.topo" @@ -108,9 +117,13 @@ def test_topology_refuses_what_it_would_have_guessed(self): ("hosts a b\ncabling path\nrelay_budget 65536 extra\n", "positive byte count"), ("hosts a b\ncabling path\nrelay_budget -65536\n", "positive byte count"), ("hosts a b\ncabling path\nrelay_budget 0x10000\n", "positive byte count"), + ("hosts a b\ncabling path\nrelay_budget 1\n", "65536..393216"), + ("hosts a b\ncabling path\nrelay_budget 393217\n", "65536..393216"), ("hosts a b\ncabling path\nrelay_budget 99999999999\n", "positive byte count"), - ("hosts a b\ncabling path\nnet-sircl-topology 2\n", "unknown words"), - ("hosts a b\ncabling path\n# " + "x" * 1100 + "\n", "longer than 1022 characters")): + ("hosts a bad/host\ncabling path\n", "invalid host name"), + ("hosts a bad;host\ncabling path\n", "invalid host name"), + ("hosts a $bad\ncabling path\n", "invalid host name"), + ("hosts a b\ncabling path\nnet-sircl-topology 2\n", "unknown words")): with self.subTest(text=text[:60]): rc, error = self.parse(text) self.assertEqual(rc, -1, text[:80]) @@ -119,6 +132,7 @@ def test_topology_refuses_what_it_would_have_guessed(self): def test_topology_accepts_the_documented_forms(self): sixty_three = "h" * 63 many = " ".join(f"h{i}" for i in range(64)) + many_long = " ".join(f"node-longname-host-{i:02d}" for i in range(64)) for text in ( "hosts a b\ncabling path\n", "hosts a b\ncabling ring\n", # a pair: one cable, as path @@ -132,7 +146,8 @@ def test_topology_accepts_the_documented_forms(self): "hosts a b c\ncabling path\nport0 emu0\nport1 emu0\n", f"hosts a {sixty_three}\ncabling path\n", f"hosts {many}\ncabling ring\n", - "hosts a b\ncabling path\n# " + "x" * 1019, # a full last line without a line end + f"hosts {many_long}\ncabling ring\n", # > 1022 byte single line + "hosts a b\ncabling path\n# " + "x" * 2048, # long trailing comment without newline ): with self.subTest(text=text[:60]): rc, error = self.parse(text) diff --git a/transport-core/tests/test_verbs.c b/transport-core/tests/test_verbs.c index a0b74ba..28c06f2 100644 --- a/transport-core/tests/test_verbs.c +++ b/transport-core/tests/test_verbs.c @@ -35,6 +35,48 @@ int main(void) { for (int i = 0; i < 10000 && !(n = sircl_core_poll_cq(cq, 1, &wc)); ++i) usleep(100); CHECK(n == 1 && wc.status == IBV_WC_SUCCESS && wc.wr_id == 42); CHECK(!memcmp(mem, mem + 4097, 4095)); + + /* Granted max_inline_data reporting (sircl_core_create_rc_qp_ex). */ + unsigned granted = 999; + struct ibv_qp *c = sircl_core_create_rc_qp_ex(pd, cq, 32, 64, &granted); + CHECK(c && granted == 16); + CHECK(!sircl_core_destroy_qp(c)); + CHECK(!setenv("SIRCL_EMU_MAX_INLINE", "0", 1)); + granted = 999; + c = sircl_core_create_rc_qp_ex(pd, cq, 32, 16, &granted); + CHECK(c && granted == 0); + CHECK(!sircl_core_qp_init(c, 1, IBV_ACCESS_REMOTE_WRITE)); + peer.qpn = c->qp_num; + CHECK(!sircl_core_qp_rtr(c, &peer)); CHECK(!sircl_core_qp_rts(c, 14, 7)); + uint32_t word = 0x12345678u; + CHECK(sircl_core_post_write(c, (uintptr_t)&word, 0, 4, (uintptr_t)mem, mr->rkey, + IBV_SEND_INLINE | IBV_SEND_SIGNALED, 43) == EINVAL); + CHECK(!sircl_core_destroy_qp(c)); + CHECK(!unsetenv("SIRCL_EMU_MAX_INLINE")); + + /* Unsigned address-range wraparound checks in resolve_write (remote and local). */ + struct ibv_qp *ov = sircl_core_create_rc_qp(pd, cq, 32, 16); CHECK(ov); + CHECK(!sircl_core_qp_init(ov, 1, IBV_ACCESS_REMOTE_WRITE)); + peer.qpn = ov->qp_num; + CHECK(!sircl_core_qp_rtr(ov, &peer)); CHECK(!sircl_core_qp_rts(ov, 14, 7)); + CHECK(!sircl_core_post_write(ov, (uintptr_t)mem, mr->lkey, 4096, UINT64_MAX - 16, mr->rkey, + IBV_SEND_SIGNALED, 44)); + n = 0; + for (int i = 0; i < 10000 && !(n = sircl_core_poll_cq(cq, 1, &wc)); ++i) usleep(100); + CHECK(n == 1 && wc.wr_id == 44 && wc.status == IBV_WC_REM_ACCESS_ERR); + CHECK(!sircl_core_destroy_qp(ov)); + + ov = sircl_core_create_rc_qp(pd, cq, 32, 16); CHECK(ov); + CHECK(!sircl_core_qp_init(ov, 1, IBV_ACCESS_REMOTE_WRITE)); + peer.qpn = ov->qp_num; + CHECK(!sircl_core_qp_rtr(ov, &peer)); CHECK(!sircl_core_qp_rts(ov, 14, 7)); + CHECK(!sircl_core_post_write(ov, UINT64_MAX - 16, mr->lkey, 4096, (uintptr_t)mem, mr->rkey, + IBV_SEND_SIGNALED, 45)); + n = 0; + for (int i = 0; i < 10000 && !(n = sircl_core_poll_cq(cq, 1, &wc)); ++i) usleep(100); + CHECK(n == 1 && wc.wr_id == 45 && wc.status == IBV_WC_LOC_PROT_ERR); + CHECK(!sircl_core_destroy_qp(ov)); + CHECK(!sircl_core_destroy_qp(a)); CHECK(!sircl_core_destroy_qp(b)); CHECK(!sircl_core_destroy_cq(cq)); CHECK(!sircl_core_dereg_mr(mr)); sccl_emu_segment_free(mem); CHECK(!sircl_core_dealloc_pd(pd)); CHECK(!sircl_core_close_device(ctx)); From 6b259384c612e48bf4b103b092031d993c988231 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:32:08 -0600 Subject: [PATCH 2/4] net-sircl: fix accept HoL DoS, relay poisoning & finalize refcount, DSO hardening, data-path edge cases (P0-3, P0-4, P1-1..P1-4, P1-8) --- net-sircl/Makefile | 14 +- net-sircl/net_sircl.c | 222 +++++++++++++++---- net-sircl/net_sircl.map | 15 ++ net-sircl/net_sircl_admission.h | 64 +++++- net-sircl/net_sircl_compat.h | 16 +- net-sircl/net_sircl_config.h | 12 +- net-sircl/net_sircl_connection.h | 276 +++++++++++++++--------- net-sircl/net_sircl_plan.c | 67 +++++- net-sircl/net_sircl_profile.h | 37 +++- net-sircl/tests/layer_test.c | 6 +- net-sircl/tests/relay_test.c | 8 +- net-sircl/tests/request_contract_test.c | 14 ++ net-sircl/tests/settings_test.c | 51 ++++- net-sircl/tests/test_net_sircl.py | 73 ++++++- 14 files changed, 689 insertions(+), 186 deletions(-) create mode 100644 net-sircl/net_sircl.map diff --git a/net-sircl/Makefile b/net-sircl/Makefile index 55ebb4b..a3bbddc 100644 --- a/net-sircl/Makefile +++ b/net-sircl/Makefile @@ -14,6 +14,8 @@ CC ?= cc PYTHON ?= python3 PREFIX ?= /usr/local CFLAGS ?= -std=gnu11 -O2 -g -Wall -Wextra -Werror -pthread +VISIBILITY_FLAGS := -fvisibility=hidden +HARDEN_LDFLAGS := -Wl,-z,relro,-z,now STANDIN := tests/standin # The bundled core beside this directory comes first: a directory that merely happens to be called # transport-core next to the checkout must not be compiled in instead. CORE= selects another. @@ -24,14 +26,16 @@ CPPFLAGS += -I$(CORE)/include -include .core-build/core_identity.h all: libnccl-net-sircl.so -libnccl-net-sircl.so: net_sircl.c net_sircl.h net_sircl_profile.h $(wildcard nccl/*.h) VERSION $(CORE_SOURCES) $(CORE_HEADERS) - $(CC) $(CPPFLAGS) $(CFLAGS) -fPIC -shared -DNET_SIRCL_RELEASE='"$(VERSION)"' -I. net_sircl.c $(CORE_SOURCES) -o $@ -libverbs +libnccl-net-sircl.so: net_sircl.c net_sircl.h net_sircl.map net_sircl_profile.h $(wildcard nccl/*.h) VERSION $(CORE_SOURCES) $(CORE_HEADERS) + $(CC) $(CPPFLAGS) $(CFLAGS) $(VISIBILITY_FLAGS) -fPIC -shared -DNET_SIRCL_RELEASE='"$(VERSION)"' -I. net_sircl.c $(CORE_SOURCES) \ + -Wl,-soname,libnccl-net-sircl.so -Wl,--version-script=net_sircl.map $(HARDEN_LDFLAGS) -o $@ -libverbs emu: libnccl-net-sircl-emu.so libnccl-net-sircl-emu.so: net_sircl.c net_sircl.h net_sircl_profile.h $(wildcard nccl/*.h) $(STANDIN)/shm_verbs.c VERSION $(CORE_SOURCES) $(CORE_HEADERS) $(CORE)/src/shm_verbs.c $(CORE)/src/shm_memory.c $(CORE)/src/shm_memory.h - $(CC) $(CPPFLAGS) $(CFLAGS) -fPIC -shared -DNET_SIRCL_RELEASE='"$(VERSION)"' -DNET_SIRCL_STANDIN -I. \ - -I$(STANDIN)/fake_verbs -I$(STANDIN) net_sircl.c $(STANDIN)/shm_verbs.c $(CORE_SOURCES) -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) $(VISIBILITY_FLAGS) -fPIC -shared -DNET_SIRCL_RELEASE='"$(VERSION)"' -DNET_SIRCL_STANDIN -I. \ + -I$(STANDIN)/fake_verbs -I$(STANDIN) net_sircl.c $(STANDIN)/shm_verbs.c $(CORE_SOURCES) \ + -Wl,-soname,libnccl-net-sircl-emu.so $(HARDEN_LDFLAGS) -o $@ check: @test -n "$(CORE)" || { echo "transport-core is required beside net-sircl"; exit 1; } @@ -49,7 +53,7 @@ install: libnccl-net-sircl.so install -D -m 0644 nccl/LICENSE.txt $(DESTDIR)$(PREFIX)/share/doc/net-sircl/NCCL-LICENSE.txt clean: - rm -f libnccl-net-sircl.so libnccl-net-sircl-emu.so + rm -rf libnccl-net-sircl.so libnccl-net-sircl-emu.so .core-build .PHONY: all emu check install clean diff --git a/net-sircl/net_sircl.c b/net-sircl/net_sircl.c index 966a6f7..1df46d2 100644 --- a/net-sircl/net_sircl.c +++ b/net-sircl/net_sircl.c @@ -82,7 +82,10 @@ enum { WR_DATA = 1, WR_FINAL = 2, WR_CTS = 3 }; static ncclDebugLogger_t logger; #define LOG(level, ...) \ - do { if (logger) logger(level, NCCL_NET, __FILE__, __LINE__, __VA_ARGS__); } while (0) + do { \ + ncclDebugLogger_t log_fn_ = __atomic_load_n(&logger, __ATOMIC_ACQUIRE); \ + if (log_fn_) log_fn_(level, NCCL_NET, __FILE__, __LINE__, __VA_ARGS__); \ + } while (0) #define WARN(...) LOG(NCCL_LOG_WARN, __VA_ARGS__) #define INFO(...) LOG(NCCL_LOG_INFO, __VA_ARGS__) @@ -131,9 +134,16 @@ struct window { ncclResult_t error; }; +struct sircl_ctx { + struct sircl_ctx *next; +}; + static struct { pthread_mutex_t lock; int refs; + int initialized; + int active_comms; + struct sircl_ctx *ctxs; int ndevs; struct dev devs[NET_SIRCL_MAX_DEVS]; int position; @@ -184,6 +194,7 @@ struct comm { struct profile_comm *profile; struct ibv_cq *cq; struct ibv_qp *qp; + unsigned max_inline; struct net_sircl_ctrl *ctrl; struct ibv_mr *ctrl_mr; uint64_t rctrl_addr; @@ -206,9 +217,11 @@ struct comm { #include "net_sircl_profile.h" +#define LISTEN_PENDING_MAX 32 struct listen_comm { int fd, dev; - struct pending *accepting; + int naccepting; + struct pending *accepting[LISTEN_PENDING_MAX]; }; /* A connection in progress, on either side. */ @@ -216,11 +229,11 @@ struct pending { int fd, state, dev; struct comm *c; struct net_sircl_meta mine, theirs; - size_t got, ready_got; + size_t got, sent, ready_got, ready_sent; uint8_t ready; int64_t deadline_ms; }; -enum { P_CONNECTING = 0, P_WAIT_META, P_WAIT_READY }; +enum { P_CONNECTING = 0, P_SEND_META, P_WAIT_META, P_SEND_READY, P_WAIT_READY }; static int64_t now_ms(void) { struct timespec t; @@ -372,7 +385,7 @@ static ncclResult_t open_devices(void) { snprintf(path, sizeof path, "/sys/class/infiniband/%s/device", name); if (realpath(path, real)) d->pci_path = strdup(real); d->guid = sircl_core_sysfs_guid("/sys/class/infiniband", name); - sircl_core_sysfs_netdev("/sys/class/infiniband", name, d->netdev, sizeof d->netdev); + sircl_core_sysfs_gid_netdev("/sys/class/infiniband", name, d->port, d->gid_index, d->netdev, sizeof d->netdev); #endif if (sircl_core_query_gid(ctx, d->port, d->gid_index, &d->gid)) { WARN("net-sircl: %s has no GID at index %d", name, d->gid_index); @@ -395,16 +408,55 @@ static ncclResult_t open_devices(void) { return ncclSuccess; } +static void windows_recover_drained_locked(void); + +static void teardown_global_locked(void) { + for (int d = 0; d < g.ndevs; ++d) { + if (g.devs[d].pd && sircl_core_dealloc_pd(g.devs[d].pd)) + WARN("net-sircl: deallocating PD on %s failed during finalize", g.devs[d].name); + if (g.devs[d].ctx && sircl_core_close_device(g.devs[d].ctx)) + WARN("net-sircl: closing device %s failed during finalize", g.devs[d].name); + free(g.devs[d].pci_path); + g.devs[d].pd = NULL; + g.devs[d].ctx = NULL; + g.devs[d].pci_path = NULL; + } + if (profile_is_enabled()) { profile_flush(); profile_reset(); } + g.ndevs = 0; + for (int i = 0; i < g.nwindows; ++i) pthread_mutex_destroy(&g.windows[i].lock); + for (int d = 0; d < NET_SIRCL_MAX_DEVS; ++d) pthread_mutex_destroy(&g.relay_windows[d].lock); + if (g.owner_fd >= 0) close(g.owner_fd); + g.owner_fd = -1; + g.nwindows = 0; + g.initialized = 0; +} + +static void active_comm_enter(void) { + pthread_mutex_lock(&g.lock); + g.active_comms++; + pthread_mutex_unlock(&g.lock); +} + +static void active_comm_leave(void) { + pthread_mutex_lock(&g.lock); + if (g.active_comms > 0 && --g.active_comms == 0 && g.refs == 0 && g.initialized) + teardown_global_locked(); + pthread_mutex_unlock(&g.lock); +} + /* NCCL owns communicator geometry. Its net ABI cannot set a collective channel cap; * changing process environment here would also affect unrelated communicators. */ static ncclResult_t sircl_init(void **ctx, uint64_t commId, ncclNetCommConfig_v12_t *config, ncclDebugLogger_t logFunction, ncclProfilerCallback_t profFunction) { (void)commId; (void)config; (void)profFunction; - logger = logFunction; + if (!ctx) return ncclInvalidArgument; + *ctx = NULL; + struct sircl_ctx *handle = calloc(1, sizeof *handle); + if (!handle) return ncclSystemError; pthread_mutex_lock(&g.lock); + if (logFunction) __atomic_store_n(&logger, logFunction, __ATOMIC_RELEASE); ncclResult_t r = ncclSuccess; - if (g.refs++ == 0) { - profile_init(); + if (!g.initialized) { /* Defaults follow NVIDIA NCCL v2.32.3-1, src/transport/net_ib/connect.cc (see NOTICE). * Plugin settings are independent of NCCL_IB_*; all peers use this local QP policy. * Every setting is validated before a device is opened: a malformed value fails initialization @@ -454,6 +506,13 @@ static ncclResult_t sircl_init(void **ctx, uint64_t commId, ncclNetCommConfig_v1 if (r == ncclSuccess && claim_host()) r = ncclSystemError; } if (r == ncclSuccess) { + profile_init(); + g.initialized = 1; + double ib_ms = 0.004096 * (double)(UINT64_C(1) << g.ib_timeout) * (double)(g.ib_retry_cnt + 1); + if (ib_ms > (double)g.request_timeout_ms) + WARN("net-sircl: NET_SIRCL_IB_TIMEOUT=%d with retry=%d (~%.0f ms) exceeds " + "NET_SIRCL_REQUEST_TIMEOUT_MS=%d ms; request timeout may trip first", + g.ib_timeout, g.ib_retry_cnt, ib_ms, g.request_timeout_ms); INFO("net-sircl: directional relay budget %d, hosts %d, model %s", g.relay_budget, g.nhosts, g.route_derived ? "routes" : "aggregate"); for (int d = 0; d < g.ndevs; ++d) @@ -476,31 +535,45 @@ static ncclResult_t sircl_init(void **ctx, uint64_t commId, ncclNetCommConfig_v1 if (g.owner_fd >= 0) close(g.owner_fd); g.owner_fd = -1; for (int d = 0; d < NET_SIRCL_MAX_DEVS; ++d) pthread_mutex_destroy(&g.relay_windows[d].lock); + profile_reset(); } init_done: - if (r != ncclSuccess) g.refs = 0; + ; + } else { + /* Fresh communicator initialization: recover any drained windows whose previous comms all closed. */ + windows_recover_drained_locked(); + } + if (r == ncclSuccess) { + handle->next = g.ctxs; + g.ctxs = handle; + g.refs++; + *ctx = handle; + } else { + free(handle); } pthread_mutex_unlock(&g.lock); - if (r == ncclSuccess) *ctx = &g; return r; } static ncclResult_t sircl_finalize(void *ctx) { - (void)ctx; + if (!ctx) return ncclInvalidArgument; pthread_mutex_lock(&g.lock); + struct sircl_ctx **link = &g.ctxs; + while (*link && *link != ctx) link = &(*link)->next; + if (!*link) { + pthread_mutex_unlock(&g.lock); + WARN("net-sircl: finalize called with unknown or already finalized context"); + return ncclInvalidArgument; + } + struct sircl_ctx *found = *link; + *link = found->next; + free(found); if (g.refs > 0 && --g.refs == 0) { - for (int d = 0; d < g.ndevs; ++d) { - sircl_core_dealloc_pd(g.devs[d].pd); - sircl_core_close_device(g.devs[d].ctx); - free(g.devs[d].pci_path); + if (g.active_comms == 0) { + teardown_global_locked(); + } else { + WARN("net-sircl: finalize called with %d active comm/listener(s); deferring resource teardown", g.active_comms); } - if (profile_enabled) { profile_flush(); profile_reset(); } - g.ndevs = 0; - for (int i = 0; i < g.nwindows; ++i) pthread_mutex_destroy(&g.windows[i].lock); - for (int d = 0; d < NET_SIRCL_MAX_DEVS; ++d) pthread_mutex_destroy(&g.relay_windows[d].lock); - if (g.owner_fd >= 0) close(g.owner_fd); - g.owner_fd = -1; - g.nwindows = 0; } pthread_mutex_unlock(&g.lock); return ncclSuccess; @@ -565,6 +638,13 @@ static ncclResult_t sircl_reg_mr(void *comm, void *data, size_t size, int type, void *target = data; #endif m->ib = target ? sircl_core_reg_mr(g.devs[c->dev].pd, target, size, access) : NULL; +#ifndef NET_SIRCL_STANDIN + if (!m->ib && target && (access & IBV_ACCESS_RELAXED_ORDERING) && + (errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTSUP)) { + access &= ~IBV_ACCESS_RELAXED_ORDERING; + m->ib = sircl_core_reg_mr(g.devs[c->dev].pd, target, size, access); + } +#endif if (!m->ib) { WARN("net-sircl: registering %zu bytes: %s", size, strerror(errno)); shared_free(m->shadow); @@ -595,17 +675,28 @@ static ncclResult_t sircl_dereg_mr(void *comm, void *mhandle) { return ncclSuccess; } -/* The NIC's address for `p` inside registration `m` (the shadow's under the stand-in). */ -static uint64_t nic_addr(const struct mr *m, const void *p) { - if (!m) return (uint64_t)(uintptr_t)p; - size_t off = (size_t)((const uint8_t *)p - m->base); - return (uint64_t)(uintptr_t)((m->shadow ? m->shadow : m->base) + off); +/* The NIC's address for `p` inside registration `m` (the shadow's under the stand-in), + * verifying that [p, p + size) lies within [m->base, m->base + m->size). */ +static int nic_addr_checked(const struct mr *m, const void *p, size_t size, uint64_t *out) { + if (!m) { + *out = (uint64_t)(uintptr_t)p; + return 1; + } + uintptr_t ptr = (uintptr_t)p, base = (uintptr_t)m->base; + if (ptr < base || ptr - base > m->size || size > m->size - (ptr - base)) { + WARN("net-sircl: buffer range (%p, %zu bytes) lies outside registration (%p, %zu bytes)", + p, size, (const void *)m->base, m->size); + return 0; + } + size_t off = (size_t)(ptr - base); + *out = (uint64_t)(uintptr_t)((m->shadow ? m->shadow : m->base) + off); + return 1; } /* -- data path -- */ static int post_write(struct comm *c, uint64_t laddr, uint32_t lkey, uint32_t len, uint64_t raddr, uint32_t rkey, int inline_data, int signaled, uint64_t wr_id) { - if (profile_enabled) + if (profile_is_enabled()) return profile_post(c, laddr, lkey, len, raddr, rkey, (signaled ? IBV_SEND_SIGNALED : 0) | (inline_data ? IBV_SEND_INLINE : 0), wr_id); return sircl_core_post_write(c->qp, laddr, lkey, len, raddr, rkey, @@ -617,7 +708,7 @@ static ncclResult_t send_progress(struct comm *c, struct req *q) { while (q->posted < q->total) { uint32_t left = q->total - q->posted; uint32_t piece = !c->win ? left : c->data_out < DATA_WR_LIMIT ? chunk_bytes(c, left) : 0; - if (profile_enabled) profile_wait(c, q, !piece); + if (profile_is_enabled()) profile_wait(c, q, !piece); if (!piece) return ncclSuccess; uint64_t charge = write_charge(c, piece); uint64_t ack = ack_charge(c, piece); @@ -636,14 +727,29 @@ static ncclResult_t send_progress(struct comm *c, struct req *q) { uint64_t charge = c->win && c->win->relay ? 2 * write_charge(c, 4) : 0; uint64_t ack = 2 * ack_charge(c, 4); int blocked = !admission_reserve(c, charge, ack); - if (profile_enabled) profile_wait(c, q, blocked); + if (profile_is_enabled()) profile_wait(c, q, blocked); if (blocked) return c->win->error; uint32_t size = q->total, seq = q->seq + 1; uint64_t base = c->rctrl_addr; - if (post_write(c, (uint64_t)(uintptr_t)&size, 0, 4, base + offsetof(struct net_sircl_ctrl, done_size) + 4 * q->slot, - c->rctrl_rkey, 1, 0, 0) || - post_write(c, (uint64_t)(uintptr_t)&seq, 0, 4, base + offsetof(struct net_sircl_ctrl, done_seq) + 4 * q->slot, - c->rctrl_rkey, 1, 1, WR_ACK_ID(WR_FINAL, charge, q->slot, ack))) { + int use_inline = c->max_inline >= 4; + uint64_t size_src, seq_src; + uint32_t ctrl_lkey; + if (use_inline) { + size_src = (uint64_t)(uintptr_t)&size; + seq_src = (uint64_t)(uintptr_t)&seq; + ctrl_lkey = 0; + } else { + /* Provider did not grant 4-byte inline writes: stage outgoing completion words in our registered ctrl block. */ + c->ctrl->done_size[q->slot] = size; + c->ctrl->done_seq[q->slot] = seq; + size_src = (uint64_t)(uintptr_t)&c->ctrl->done_size[q->slot]; + seq_src = (uint64_t)(uintptr_t)&c->ctrl->done_seq[q->slot]; + ctrl_lkey = c->ctrl_mr->lkey; + } + if (post_write(c, size_src, ctrl_lkey, 4, base + offsetof(struct net_sircl_ctrl, done_size) + 4 * q->slot, + c->rctrl_rkey, use_inline, 0, 0) || + post_write(c, seq_src, ctrl_lkey, 4, base + offsetof(struct net_sircl_ctrl, done_seq) + 4 * q->slot, + c->rctrl_rkey, use_inline, 1, WR_ACK_ID(WR_FINAL, charge, q->slot, ack))) { if (c->win) c->win->error = ncclSystemError; /* a partial pair cannot return credit */ WARN("net-sircl: posting a completion word: %s", strerror(errno)); return ncclSystemError; @@ -721,6 +827,8 @@ static ncclResult_t isend_locked(void *sendComm, void *data, size_t size, int ta return ncclInternalError; } struct mr *m = mhandle; + uint64_t laddr = 0; + if (!nic_addr_checked(m, data, size, &laddr)) return ncclInvalidArgument; memset(q, 0, sizeof *q); q->started_ms = now_ms(); q->used = q->is_send = 1; @@ -728,7 +836,7 @@ static ncclResult_t isend_locked(void *sendComm, void *data, size_t size, int ta q->seq = c->seq++; q->slot = slot; q->total = (uint32_t)size; - q->laddr = nic_addr(m, data); + q->laddr = laddr; q->lkey = m ? m->ib->lkey : 0; q->raddr = e.addr; q->rkey = e.rkey; @@ -743,8 +851,10 @@ static ncclResult_t poll_cq(struct comm *c); static ncclResult_t sircl_isend(void *sendComm, void *data, size_t size, int tag, void *mhandle, void *phandle, void **request) { + if (!request) return ncclInvalidArgument; *request = NULL; struct comm *c = sendComm; + if (!c) return ncclInvalidArgument; if (c->win) pthread_mutex_lock(&c->win->lock); /* Submission retries must make progress even before NCCL owns a request * to test. No CUDA operation or stream wait participates in credit return. */ @@ -764,10 +874,21 @@ static ncclResult_t recv_progress(struct comm *c, struct req *q) { struct net_sircl_cts *e = &c->ctrl->cts[q->slot]; uint32_t seq = q->seq + 1; uint64_t base = c->rctrl_addr; + int use_inline = c->max_inline >= 4; + uint64_t seq_src; + uint32_t seq_lkey; + if (use_inline) { + seq_src = (uint64_t)(uintptr_t)&seq; + seq_lkey = 0; + } else { + c->ctrl->cts_seq[q->slot] = seq; + seq_src = (uint64_t)(uintptr_t)&c->ctrl->cts_seq[q->slot]; + seq_lkey = c->ctrl_mr->lkey; + } if (post_write(c, (uint64_t)(uintptr_t)e, c->ctrl_mr->lkey, sizeof *e, base + offsetof(struct net_sircl_ctrl, cts) + sizeof *e * q->slot, c->rctrl_rkey, 0, 0, 0) || - post_write(c, (uint64_t)(uintptr_t)&seq, 0, 4, base + offsetof(struct net_sircl_ctrl, cts_seq) + 4 * q->slot, - c->rctrl_rkey, 1, 1, WR_ACK_ID(WR_CTS, charge, q->slot, ack))) { + post_write(c, seq_src, seq_lkey, 4, base + offsetof(struct net_sircl_ctrl, cts_seq) + 4 * q->slot, + c->rctrl_rkey, use_inline, 1, WR_ACK_ID(WR_CTS, charge, q->slot, ack))) { if (c->win) c->win->error = ncclSystemError; WARN("net-sircl: posting a clear-to-send entry: %s", strerror(errno)); return ncclSystemError; @@ -785,14 +906,21 @@ static ncclResult_t irecv_locked(void *recvComm, int n, void **data, size_t *siz WARN("net-sircl: grouped receives (%d) are not offered (maxRecvs 1)", n); return ncclInternalError; } + if (!c || !data || !sizes || !tags) return ncclInvalidArgument; + if (sizes[0] > MAX_NET_BYTES) { + WARN("net-sircl: receive size %zu exceeds maximum %u", sizes[0], MAX_NET_BYTES); + return ncclInvalidArgument; + } uint32_t slot = c->seq % NET_SIRCL_SLOTS; struct req *q = &c->reqs[slot]; if (q->used) return ncclSuccess; struct mr *m = mhandles ? mhandles[0] : NULL; + uint64_t raddr = 0; + if (!nic_addr_checked(m, data[0], sizes[0], &raddr)) return ncclInvalidArgument; struct net_sircl_cts *e = &c->ctrl->cts[slot]; - e->addr = nic_addr(m, data[0]); + e->addr = raddr; e->rkey = m ? m->ib->rkey : 0; - e->size = sizes[0] > MAX_NET_BYTES ? MAX_NET_BYTES : (uint32_t)sizes[0]; + e->size = (uint32_t)sizes[0]; e->tag = (uint32_t)tags[0]; memset(q, 0, sizeof *q); q->started_ms = now_ms(); @@ -834,7 +962,7 @@ static ncclResult_t sircl_iflush(void *recvComm, int n, void **data, int *sizes, static ncclResult_t drain(struct comm *c) { struct ibv_wc wc[32]; int n; - if ((n = profile_enabled ? profile_poll(c, wc) : sircl_core_poll_cq(c->cq, 32, wc)) > 0) { + if ((n = profile_is_enabled() ? profile_poll(c, wc) : sircl_core_poll_cq(c->cq, 32, wc)) > 0) { for (int i = 0; i < n; ++i) { if (wc[i].status != IBV_WC_SUCCESS) { WARN("net-sircl: completion error %d (%s) on %s toward position %d%s", (int)wc[i].status, @@ -842,6 +970,8 @@ static ncclResult_t drain(struct comm *c) { wc[i].status == IBV_WC_RETRY_EXC_ERR ? "; ACK retry budget exhausted: raise NET_SIRCL_IB_TIMEOUT (maximum 31); check peer and path health" : ""); + c->error = ncclRemoteError; + comm_hang_up(c); if (c->win) c->win->error = ncclRemoteError; return ncclRemoteError; } @@ -849,7 +979,7 @@ static ncclResult_t drain(struct comm *c) { int kind = (int)(id >> 56); uint32_t slot = (uint32_t)(id & 0xff); admission_complete(c, id); - if (profile_enabled) profile_complete(c, id); + if (profile_is_enabled()) profile_complete(c, id); if (kind == WR_DATA && c->data_out) c->data_out--; if (kind == WR_FINAL && slot < NET_SIRCL_SLOTS) c->reqs[slot].done = 1; if (kind == WR_CTS && slot < NET_SIRCL_SLOTS) c->reqs[slot].cts_done = 1; @@ -912,9 +1042,11 @@ static ncclResult_t sircl_close_recv(void *recvComm) { static ncclResult_t sircl_close_listen(void *listenComm) { struct listen_comm *l = listenComm; if (!l) return ncclSuccess; - pending_drop(l->accepting); + for (int i = 0; i < l->naccepting; ++i) pending_drop(l->accepting[i]); + l->naccepting = 0; close(l->fd); free(l); + active_comm_leave(); return ncclSuccess; } @@ -923,12 +1055,18 @@ static ncclResult_t sircl_set_net_attr(void *ctx, ncclNetAttr_v12_t *attr) { return ncclSuccess; } +#ifdef NET_SIRCL_STANDIN +__attribute__((visibility("default"))) +#endif void net_sircl_stats(void *send_comm, uint64_t *max_inflight, uint64_t *chunks) { struct comm *c = send_comm; *max_inflight = c->win ? __atomic_load_n(&c->win->max_inflight, __ATOMIC_RELAXED) : 0; *chunks = c->chunks; } +#ifdef NET_SIRCL_STANDIN +__attribute__((visibility("default"))) +#endif int net_sircl_comm_device(void *comm, char *name, size_t len) { struct comm *c = comm; snprintf(name, len, "%s", g.devs[c->dev].name); diff --git a/net-sircl/net_sircl.map b/net-sircl/net_sircl.map new file mode 100644 index 0000000..7e1b38b --- /dev/null +++ b/net-sircl/net_sircl.map @@ -0,0 +1,15 @@ +{ + global: + ncclNetPlugin_v7; + ncclNetPlugin_v8; + ncclNetPlugin_v9; + ncclNetPlugin_v10; + ncclNetPlugin_v11; + ncclNetPlugin_v12; + ncclTunerPlugin_v4; + net_sircl_release; + net_sircl_core_release; + net_sircl_core_source; + local: + *; +}; diff --git a/net-sircl/net_sircl_admission.h b/net-sircl/net_sircl_admission.h index 2feb145..3a6282a 100644 --- a/net-sircl/net_sircl_admission.h +++ b/net-sircl/net_sircl_admission.h @@ -4,6 +4,7 @@ static ncclResult_t send_progress(struct comm *, struct req *); static ncclResult_t recv_progress(struct comm *, struct req *); static ncclResult_t drain(struct comm *); +static void comm_hang_up(struct comm *); static struct window *window_for(int d, int position, uint32_t cap) { if (!cap) return NULL; @@ -16,11 +17,42 @@ static struct window *window_for(int d, int position, uint32_t cap) { memset(w, 0, sizeof *w); w->dev = d, w->position = position, w->cap = cap; pthread_mutex_init(&w->lock, NULL); + } else if (!w) { + WARN("net-sircl: direct window table full (%d entries, MAX_WINDOWS=%d); cannot allocate window for dev %d peer %d", + g.nwindows, MAX_WINDOWS, d, position); } pthread_mutex_unlock(&g.lock); return w; } +/* Clear any error and abandoned accounting on drained windows (members == NULL) + * when a fresh communicator initializes, so one failed communicator cannot + * permanently brick subsequent communicators in the same process. */ +static void windows_recover_drained_locked(void) { + for (int d = 0; d < g.ndevs; ++d) { + struct window *w = &g.relay_windows[d]; + pthread_mutex_lock(&w->lock); + if (w->error != ncclSuccess && !w->members) { + w->error = ncclSuccess; + __atomic_store_n(&w->inflight, 0, __ATOMIC_RELEASE); + w->ack_inflight = 0; + w->pending_head = w->pending_tail = NULL; + } + pthread_mutex_unlock(&w->lock); + } + for (int i = 0; i < g.nwindows; ++i) { + struct window *w = &g.windows[i]; + pthread_mutex_lock(&w->lock); + if (w->error != ncclSuccess && !w->members) { + w->error = ncclSuccess; + __atomic_store_n(&w->inflight, 0, __ATOMIC_RELEASE); + w->ack_inflight = 0; + w->pending_head = w->pending_tail = NULL; + } + pthread_mutex_unlock(&w->lock); + } +} + static void window_join(struct window *w, struct comm *c) { pthread_mutex_lock(&w->lock); c->next = w->members; @@ -151,19 +183,11 @@ static ncclResult_t advance_pending(struct window *w) { w->pending_head = q->pending_next; if (!w->pending_head) w->pending_tail = NULL; q->pending_next = NULL; - if (profile_enabled) profile_wait(q->c, q, 0); + if (profile_is_enabled()) profile_wait(q->c, q, 0); } return ncclSuccess; } -static ncclResult_t submit_progress(struct comm *c, struct req *q) { - if (!c->win || !c->win->relay) - return q->is_send ? send_progress(c, q) : recv_progress(c, q); - pending_append(c->win, q); - if (profile_enabled && q->is_send && c->win->pending_head != q) profile_wait(c, q, 1); - return advance_pending(c->win); -} - /* Post a windowed comm's waiting payload or CTS writes, oldest request first. */ static ncclResult_t advance(struct comm *c) { for (uint32_t s = c->head; s != c->seq; ++s) { @@ -176,6 +200,16 @@ static ncclResult_t advance(struct comm *c) { return ncclSuccess; } +static ncclResult_t submit_progress(struct comm *c, struct req *q) { + if (!c->win) + return q->is_send ? send_progress(c, q) : recv_progress(c, q); + if (!c->win->relay) + return advance(c); + pending_append(c->win, q); + if (profile_is_enabled() && q->is_send && c->win->pending_head != q) profile_wait(c, q, 1); + return advance_pending(c->win); +} + /* Caller holds the shared window lock across progress and request retirement. */ static ncclResult_t poll_cq(struct comm *c) { if (c->error) return c->error; @@ -189,11 +223,19 @@ static ncclResult_t poll_cq(struct comm *c) { * final CQEs and must retain unconditional polling. */ ncclResult_t r = ncclSuccess; if (!w->relay || m->inflight) r = drain(m); - if (r != ncclSuccess) return w->error = r; + if (r != ncclSuccess) { + if (!m->error) m->error = r; + comm_hang_up(m); + return w->error = r; + } /* Reuse completed credit before polling unrelated CQs, granting it to * the oldest waiting request rather than preferentially to the CQ owner. */ r = w->relay ? advance_pending(w) : advance(m); - if (r != ncclSuccess) return w->error = r; + if (r != ncclSuccess) { + if (!m->error) m->error = r; + comm_hang_up(m); + return w->error = r; + } } /* Rotate CQ visits; relay admission has its own FIFO order. */ if (w->members && w->members->next) { diff --git a/net-sircl/net_sircl_compat.h b/net-sircl/net_sircl_compat.h index 716a0ee..e473712 100644 --- a/net-sircl/net_sircl_compat.h +++ b/net-sircl/net_sircl_compat.h @@ -9,7 +9,15 @@ static void *compat_ctx; static ncclResult_t compat_init(int version, ncclDebugLogger_t log, ncclProfilerCallback_t prof) { pthread_mutex_lock(&compat_lock); - ncclResult_t r = compat_ctx ? ncclSuccess : sircl_init(&compat_ctx, 0, NULL, log, prof); + ncclResult_t r = ncclSuccess; + if (compat_ctx) { + if (log) __atomic_store_n(&logger, log, __ATOMIC_RELEASE); + pthread_mutex_lock(&g.lock); + windows_recover_drained_locked(); + pthread_mutex_unlock(&g.lock); + } else { + r = sircl_init(&compat_ctx, 0, NULL, log, prof); + } if (r == ncclSuccess && log) log(NCCL_LOG_INFO, NCCL_INIT, __FILE__, __LINE__, "net-sircl %s: ext-net v%d", NET_SIRCL_RELEASE, version); pthread_mutex_unlock(&compat_lock); @@ -17,7 +25,11 @@ static ncclResult_t compat_init(int version, ncclDebugLogger_t log, ncclProfiler } __attribute__((destructor)) static void compat_finalize(void) { - if (compat_ctx) sircl_finalize(compat_ctx); + pthread_mutex_lock(&compat_lock); + void *c = compat_ctx; + compat_ctx = NULL; + pthread_mutex_unlock(&compat_lock); + if (c) sircl_finalize(c); } #define COMPAT_INIT(V) \ diff --git a/net-sircl/net_sircl_config.h b/net-sircl/net_sircl_config.h index 568fdc4..aae2d8e 100644 --- a/net-sircl/net_sircl_config.h +++ b/net-sircl/net_sircl_config.h @@ -124,7 +124,14 @@ static ncclResult_t route_overrides(void) { if (r->relays) { if (!cap) goto invalid; for (int d = 0; d < g.ndevs; ++d) - if (cap < g.relay_windows[d].cap) g.relay_windows[d].cap = (uint32_t)cap; + if (cap < g.relay_windows[d].cap) { + g.relay_windows[d].cap = (uint32_t)cap; + if (g.relay_windows[d].ack_cap) { + uint32_t scaled_ack = (uint32_t)(cap / 6u / 128u * 128u); + if (scaled_ack < 256u) scaled_ack = 0; + if (scaled_ack < g.relay_windows[d].ack_cap) g.relay_windows[d].ack_cap = scaled_ack; + } + } } else r->window = (uint32_t)cap; } } @@ -202,6 +209,9 @@ static int routes_from_topology(const char *path) { } /* Test hook: the routes a topology file gives `position`, as "=/::;...". */ +#ifdef NET_SIRCL_STANDIN +__attribute__((visibility("default"))) +#endif int net_sircl_topology_routes(const char *path, int position, char *out, size_t len) { if (!out || !len) return -1; struct sircl_route_plan plan; diff --git a/net-sircl/net_sircl_connection.h b/net-sircl/net_sircl_connection.h index 4e4d461..9b69773 100644 --- a/net-sircl/net_sircl_connection.h +++ b/net-sircl/net_sircl_connection.h @@ -1,25 +1,35 @@ /* Private connection lifecycle: nonblocking metadata exchange, QP ownership and retryable teardown. */ +_Static_assert(sizeof(struct net_sircl_handle) <= NCCL_NET_HANDLE_MAXSIZE, + "net_sircl_handle exceeds NCCL_NET_HANDLE_MAXSIZE"); +_Static_assert(sizeof(struct net_sircl_meta) == 56, "net_sircl_meta wire size changed"); + static int set_nonblocking(int fd) { int flags = fcntl(fd, F_GETFL, 0); return flags < 0 ? -1 : fcntl(fd, F_SETFL, flags | O_NONBLOCK); } -static int send_all(int fd, const void *buf, size_t len) { - const char *p = buf; - int64_t deadline = now_ms() + 10000; - while (len) { - ssize_t n = send(fd, p, len, MSG_NOSIGNAL); - if (n < 0 && (errno == EAGAIN || errno == EINTR)) { - if (now_ms() > deadline) return -1; - struct pollfd pf = {fd, POLLOUT, 0}; - poll(&pf, 1, 100); - continue; - } +static void configure_tcp_socket(int fd) { + int one = 1; + (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one); + (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one); +#ifdef TCP_KEEPIDLE + int idle = 15, intvl = 5, cnt = 3; + (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof idle); + (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof intvl); + (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof cnt); +#endif +} + +/* Progress a nonblocking send of `len` bytes; 1 when complete, 0 when more is due, -1 on failure. */ +static int send_some(int fd, const void *buf, size_t len, size_t *sent) { + while (*sent < len) { + ssize_t n = send(fd, (const char *)buf + *sent, len - *sent, MSG_NOSIGNAL); + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0; + if (n < 0 && errno == EINTR) continue; if (n <= 0) return -1; - p += n; - len -= (size_t)n; + *sent += (size_t)n; } - return 0; + return 1; } /* Progress a receive of `len` bytes; 1 when complete, 0 when more is due, -1 on failure or end of stream. */ @@ -77,23 +87,25 @@ static ncclResult_t comm_destroy(struct comm *c) { } c->cq = NULL; } - if (profile_enabled) profile_close(c); + if (profile_is_enabled()) profile_close(c); shared_free(c->ctrl); if (c->fd >= 0) close(c->fd); free(c); + active_comm_leave(); return ncclSuccess; } static struct comm *comm_create(int d, int is_send) { struct comm *c = calloc(1, sizeof *c); if (!c) return NULL; + active_comm_enter(); c->dev = d; c->is_send = is_send; c->fd = -1; c->lane = -1; struct dev *dv = &g.devs[d]; c->cq = sircl_core_create_cq(dv->ctx, CQ_DEPTH); - c->qp = c->cq ? sircl_core_create_rc_qp(dv->pd, c->cq, SEND_DEPTH, 16) : NULL; + c->qp = c->cq ? sircl_core_create_rc_qp_ex(dv->pd, c->cq, SEND_DEPTH, 16, &c->max_inline) : NULL; c->ctrl = shared_alloc(sizeof *c->ctrl); c->ctrl_mr = c->ctrl ? sircl_core_reg_mr(dv->pd, c->ctrl, sizeof *c->ctrl, IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE) : NULL; @@ -147,9 +159,14 @@ static ncclResult_t route_check(struct comm *c, const struct net_sircl_meta *r) char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &sa.sin_addr, ip, sizeof ip); WARN("net-sircl: no route from %s (%s) to %s, the peer at position %d: a peer beyond a cable needs a relay " - "table on the hosts between (README, Peers beyond a cable)", dv->name, dv->netdev, ip, r->position); + "table on the hosts between (README, More Sparks: rings, sections and chains)", + dv->name, dv->netdev, ip, r->position); result = ncclSystemError; } + } else { + int err = errno; + WARN("net-sircl: SO_BINDTODEVICE(%s) for route check on %s failed: %s", dv->netdev, dv->name, strerror(err)); + if (err == ENODEV) result = ncclSystemError; } close(fd); return result; @@ -234,8 +251,7 @@ static int accept_dev(int position, int lane, int listen_dev) { /* -- listen / connect / accept -- */ static ncclResult_t sircl_listen(void *ctx, int d, void *handle, void **listenComm) { (void)ctx; - if (d < 0 || d >= g.ndevs) return ncclInvalidArgument; - struct net_sircl_handle *h = handle; + if (!handle || !listenComm || d < 0 || d >= g.ndevs) return ncclInvalidArgument; memset(handle, 0, NCCL_NET_HANDLE_MAXSIZE); int fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) return ncclSystemError; @@ -256,19 +272,23 @@ static ncclResult_t sircl_listen(void *ctx, int d, void *handle, void **listenCo close(fd); return ncclSystemError; } - h->magic = NET_SIRCL_MAGIC; - h->version = NET_SIRCL_VERSION; - h->port = sa.sin_port; - h->addr = g.oob_addr; - h->position = g.position; - h->pending = 0; + struct net_sircl_handle h; + memset(&h, 0, sizeof h); + h.magic = NET_SIRCL_MAGIC; + h.version = NET_SIRCL_VERSION; + h.port = sa.sin_port; + h.addr = g.oob_addr; + h.position = g.position; + h.pending = 0; struct listen_comm *l = calloc(1, sizeof *l); if (!l) { close(fd); return ncclSystemError; } + active_comm_enter(); l->fd = fd; l->dev = d; + memcpy(handle, &h, sizeof h); *listenComm = l; return ncclSuccess; } @@ -280,8 +300,9 @@ static void pending_drop(struct pending *p) { free(p); } -static ncclResult_t connect_fail(struct net_sircl_handle *h, struct pending *p, ncclResult_t r) { +static ncclResult_t connect_fail(void *raw_handle, struct net_sircl_handle *h, struct pending *p, ncclResult_t r) { h->pending = 0; + memcpy(raw_handle, h, sizeof *h); pending_drop(p); return r; } @@ -289,47 +310,51 @@ static ncclResult_t connect_fail(struct net_sircl_handle *h, struct pending *p, static ncclResult_t sircl_connect(void *ctx, int d, void *handle, void **sendComm, ncclNetDeviceHandle_v12_t **sendDevComm) { (void)ctx; - (void)sendDevComm; + if (sendDevComm) *sendDevComm = NULL; + if (!sendComm) return ncclInvalidArgument; *sendComm = NULL; - struct net_sircl_handle *h = handle; - if (h->magic != NET_SIRCL_MAGIC || h->version != NET_SIRCL_VERSION) { - WARN("net-sircl: handle magic %08x version %u", h->magic, h->version); + if (!handle || d < 0 || d >= g.ndevs) return ncclInvalidArgument; + struct net_sircl_handle h; + memcpy(&h, handle, sizeof h); + if (h.magic != NET_SIRCL_MAGIC || h.version != NET_SIRCL_VERSION) { + WARN("net-sircl: handle magic %08x version %u", h.magic, h.version); return ncclInvalidArgument; } - if (!route_of(h->position)) { - WARN("net-sircl: NET_SIRCL_TOPOLOGY gives position %d no route to position %d", g.position, h->position); + if (!route_of(h.position)) { + WARN("net-sircl: NET_SIRCL_TOPOLOGY gives position %d no route to position %d", g.position, h.position); return ncclInvalidArgument; } - struct pending *p = (struct pending *)(uintptr_t)h->pending; + struct pending *p = (struct pending *)(uintptr_t)h.pending; if (!p) { p = calloc(1, sizeof *p); if (!p) return ncclSystemError; + p->fd = -1; p->deadline_ms = now_ms() + g.connect_timeout_ms; int lane = -1; - p->dev = connect_dev(h->position, d, &lane); + p->dev = connect_dev(h.position, d, &lane); p->fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); - if (p->fd < 0 || set_nonblocking(p->fd)) return connect_fail(h, p, ncclSystemError); - int one = 1; - setsockopt(p->fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one); + if (p->fd < 0 || set_nonblocking(p->fd)) return connect_fail(handle, &h, p, ncclSystemError); + configure_tcp_socket(p->fd); struct sockaddr_in sa; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; - sa.sin_port = h->port; - sa.sin_addr.s_addr = h->addr; + sa.sin_port = h.port; + sa.sin_addr.s_addr = h.addr; if (connect(p->fd, (struct sockaddr *)&sa, sizeof sa) && errno != EINPROGRESS) { WARN("net-sircl: connecting to the listener: %s", strerror(errno)); - return connect_fail(h, p, ncclSystemError); + return connect_fail(handle, &h, p, ncclSystemError); } p->c = comm_create(p->dev, 1); - if (!p->c) return connect_fail(h, p, ncclSystemError); + if (!p->c) return connect_fail(handle, &h, p, ncclSystemError); p->c->lane = lane; p->state = P_CONNECTING; - h->pending = (uint64_t)(uintptr_t)p; + h.pending = (uint64_t)(uintptr_t)p; + memcpy(handle, &h, sizeof h); } if (now_ms() > p->deadline_ms) { - WARN("net-sircl: connecting to position %d timed out after %d ms (NET_SIRCL_CONNECT_TIMEOUT_MS)", h->position, + WARN("net-sircl: connecting to position %d timed out after %d ms (NET_SIRCL_CONNECT_TIMEOUT_MS)", h.position, g.connect_timeout_ms); - return connect_fail(h, p, ncclSystemError); + return connect_fail(handle, &h, p, ncclSystemError); } if (p->state == P_CONNECTING) { struct pollfd pf = {p->fd, POLLOUT, 0}; @@ -339,103 +364,158 @@ static ncclResult_t sircl_connect(void *ctx, int d, void *handle, void **sendCom getsockopt(p->fd, SOL_SOCKET, SO_ERROR, &err, &len); if (err) { WARN("net-sircl: connecting to the listener: %s", strerror(err)); - return connect_fail(h, p, ncclSystemError); + return connect_fail(handle, &h, p, ncclSystemError); } meta_fill(p->c, &p->mine); - if (send_all(p->fd, &p->mine, sizeof p->mine)) return connect_fail(h, p, ncclSystemError); + p->sent = 0; + p->state = P_SEND_META; + } + if (p->state == P_SEND_META) { + int r = send_some(p->fd, &p->mine, sizeof p->mine, &p->sent); + if (r < 0) return connect_fail(handle, &h, p, ncclSystemError); + if (r == 0) return ncclSuccess; p->state = P_WAIT_META; } if (p->state == P_WAIT_META) { int r = recv_some(p->fd, &p->theirs, sizeof p->theirs, &p->got); - if (r < 0) return connect_fail(h, p, ncclRemoteError); + if (r < 0) return connect_fail(handle, &h, p, ncclRemoteError); if (r == 0) return ncclSuccess; ncclResult_t rr = comm_ready(p->c, &p->theirs); - if (rr != ncclSuccess) return connect_fail(h, p, rr); + if (rr != ncclSuccess) return connect_fail(handle, &h, p, rr); /* Ready: this queue pair is at RTS, so the acceptor may let its side write (as NCCL's IB transport * finishes its connect). */ - uint8_t ready = 1; - if (send_all(p->fd, &ready, 1)) return connect_fail(h, p, ncclSystemError); + p->ready = 1; + p->ready_sent = 0; + p->state = P_SEND_READY; + } + if (p->state == P_SEND_READY) { + int r = send_some(p->fd, &p->ready, 1, &p->ready_sent); + if (r < 0) return connect_fail(handle, &h, p, ncclSystemError); + if (r == 0) return ncclSuccess; p->c->fd = p->fd; p->fd = -1; *sendComm = p->c; INFO("net-sircl: send comm on %s (lane %d) to position %d, window %u", g.devs[p->c->dev].name, p->c->lane, p->c->peer_position, p->c->win ? p->c->win->cap : 0u); p->c = NULL; - h->pending = 0; + h.pending = 0; + memcpy(handle, &h, sizeof h); free(p); } return ncclSuccess; } -static ncclResult_t accept_fail(struct listen_comm *l, ncclResult_t r) { - pending_drop(l->accepting); - l->accepting = NULL; +static struct pending *accept_take_slot(struct listen_comm *l, int index) { + struct pending *p = l->accepting[index]; + for (int j = index + 1; j < l->naccepting; ++j) + l->accepting[j - 1] = l->accepting[j]; + l->accepting[--l->naccepting] = NULL; + return p; +} + +static ncclResult_t accept_fail_slot(struct listen_comm *l, int index, ncclResult_t r) { + pending_drop(accept_take_slot(l, index)); return r; } /* A connection that never identifies itself as a net-sircl peer (a port scan, a health probe, a * connector that ended before its metadata) is dropped and the listener keeps accepting. Only a peer * that sent valid metadata can fail the accept; a connector that gave up reports its own error. */ -static ncclResult_t accept_drop(struct listen_comm *l, const char *why) { +static void accept_drop_slot(struct listen_comm *l, int index, const char *why) { WARN("net-sircl: dropped a connection to the listener of %s: %s", g.devs[l->dev].name, why); - pending_drop(l->accepting); - l->accepting = NULL; - return ncclSuccess; + pending_drop(accept_take_slot(l, index)); } static ncclResult_t sircl_accept(void *listenComm, void **recvComm, ncclNetDeviceHandle_v12_t **recvDevComm) { - (void)recvDevComm; + if (recvDevComm) *recvDevComm = NULL; + if (!recvComm) return ncclInvalidArgument; *recvComm = NULL; + if (!listenComm) return ncclInvalidArgument; struct listen_comm *l = listenComm; - struct pending *p = l->accepting; - if (!p) { + /* Drain incoming TCP connections into the bounded pending pool so one silent probe cannot + * head-of-line block legitimate peers waiting in the listen backlog. */ + while (l->naccepting < LISTEN_PENDING_MAX) { int fd = accept4(l->fd, NULL, NULL, SOCK_CLOEXEC); if (fd < 0) { - /* The connection ended while it was queued: not this listener's failure. */ - return (errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR) ? ncclSuccess - : ncclSystemError; + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR) break; + if (l->naccepting == 0) return ncclSystemError; + break; } - p = calloc(1, sizeof *p); + if (set_nonblocking(fd) < 0) { + WARN("net-sircl: setting accepted socket nonblocking on %s failed: %s", g.devs[l->dev].name, strerror(errno)); + close(fd); + continue; + } + configure_tcp_socket(fd); + struct pending *p = calloc(1, sizeof *p); if (!p) { close(fd); - return ncclSystemError; + if (l->naccepting == 0) return ncclSystemError; + break; } p->fd = fd; - set_nonblocking(fd); p->state = P_WAIT_META; - p->deadline_ms = now_ms() + g.connect_timeout_ms; - l->accepting = p; + /* Short deadline for unidentified sockets so stray probes clear promptly; once valid + * net-sircl metadata arrives the full connect_timeout_ms applies. */ + int64_t meta_timeout = g.connect_timeout_ms < 5000 ? g.connect_timeout_ms : 5000; + p->deadline_ms = now_ms() + meta_timeout; + l->accepting[l->naccepting++] = p; } - if (now_ms() > p->deadline_ms) { - if (p->state == P_WAIT_META) return accept_drop(l, "no metadata before the connect deadline"); - WARN("net-sircl: accepting a connection timed out after %d ms (NET_SIRCL_CONNECT_TIMEOUT_MS)", - g.connect_timeout_ms); - return accept_fail(l, ncclSystemError); - } - if (p->state == P_WAIT_META) { - int r = recv_some(p->fd, &p->theirs, sizeof p->theirs, &p->got); - if (r < 0) return accept_drop(l, "closed before sending its metadata"); - if (r == 0) return ncclSuccess; - /* Checked before any queue pair is created for it. */ - if (p->theirs.magic != NET_SIRCL_MAGIC) return accept_drop(l, "not a net-sircl peer"); - p->c = comm_create(accept_dev(p->theirs.position, p->theirs.lane, l->dev), 0); - if (!p->c) return accept_fail(l, ncclSystemError); - p->c->lane = p->theirs.lane; - meta_fill(p->c, &p->mine); - if (send_all(p->fd, &p->mine, sizeof p->mine)) return accept_fail(l, ncclSystemError); - ncclResult_t rr = comm_ready(p->c, &p->theirs); - if (rr != ncclSuccess) return accept_fail(l, rr); - p->state = P_WAIT_READY; + int64_t now = now_ms(); + int i = 0; + while (i < l->naccepting) { + struct pending *p = l->accepting[i]; + if (now > p->deadline_ms) { + if (p->state == P_WAIT_META) { + accept_drop_slot(l, i, "no metadata before the connect deadline"); + continue; + } + WARN("net-sircl: accepting a connection timed out after %d ms (NET_SIRCL_CONNECT_TIMEOUT_MS)", + g.connect_timeout_ms); + return accept_fail_slot(l, i, ncclSystemError); + } + if (p->state == P_WAIT_META) { + int r = recv_some(p->fd, &p->theirs, sizeof p->theirs, &p->got); + if (r < 0) { + accept_drop_slot(l, i, "closed before sending its metadata"); + continue; + } + if (r == 0) { ++i; continue; } + /* Checked before any queue pair is created for it. */ + if (p->theirs.magic != NET_SIRCL_MAGIC) { + accept_drop_slot(l, i, "not a net-sircl peer"); + continue; + } + p->c = comm_create(accept_dev(p->theirs.position, p->theirs.lane, l->dev), 0); + if (!p->c) return accept_fail_slot(l, i, ncclSystemError); + p->c->lane = p->theirs.lane; + meta_fill(p->c, &p->mine); + p->sent = 0; + p->deadline_ms = now + g.connect_timeout_ms; + ncclResult_t rr = comm_ready(p->c, &p->theirs); + if (rr != ncclSuccess) return accept_fail_slot(l, i, rr); + p->state = P_SEND_META; + } + if (p->state == P_SEND_META) { + int r = send_some(p->fd, &p->mine, sizeof p->mine, &p->sent); + if (r < 0) return accept_fail_slot(l, i, ncclSystemError); + if (r == 0) { ++i; continue; } + p->state = P_WAIT_READY; + } + if (p->state == P_WAIT_READY) { + int r = recv_some(p->fd, &p->ready, 1, &p->ready_got); + if (r < 0) return accept_fail_slot(l, i, ncclRemoteError); + if (r == 0) { ++i; continue; } + accept_take_slot(l, i); + p->c->fd = p->fd; + p->fd = -1; + *recvComm = p->c; + p->c = NULL; + free(p); + return ncclSuccess; + } + ++i; } - int r = recv_some(p->fd, &p->ready, 1, &p->ready_got); - if (r < 0) return accept_fail(l, ncclRemoteError); - if (r == 0) return ncclSuccess; - p->c->fd = p->fd; - p->fd = -1; - *recvComm = p->c; - p->c = NULL; - l->accepting = NULL; - free(p); return ncclSuccess; } diff --git a/net-sircl/net_sircl_plan.c b/net-sircl/net_sircl_plan.c index 398df1a..24ea844 100644 --- a/net-sircl/net_sircl_plan.c +++ b/net-sircl/net_sircl_plan.c @@ -1,9 +1,71 @@ /* Relay admission uses the complete validated topology, independent of device discovery. */ #include "net_sircl_plan.h" #include +#include #include #define ROUTE_MODEL_HOSTS 8 +struct canon_cable { + int a, pa, b, pb; +}; + +static int cmp_canon_cable(const void *lhs, const void *rhs) { + const struct canon_cable *x = lhs, *y = rhs; + if (x->a != y->a) return x->a < y->a ? -1 : 1; + if (x->pa != y->pa) return x->pa < y->pa ? -1 : 1; + if (x->b != y->b) return x->b < y->b ? -1 : 1; + if (x->pb != y->pb) return x->pb < y->pb ? -1 : 1; + return 0; +} + +static uint64_t fnv_u32(uint64_t h, uint32_t v) { + for (int i = 0; i < 4; ++i) + h = (h ^ ((v >> (i * 8)) & 0xffu)) * UINT64_C(1099511628211); + return h; +} + +static uint64_t fnv_str(uint64_t h, const char *s) { + for (const unsigned char *p = (const unsigned char *)s; ; ++p) { + h = (h ^ *p) * UINT64_C(1099511628211); + if (!*p) break; + } + return h; +} + +/* Hash canonical topology semantics (host order, sorted/oriented cables, port functions, + * effective relay budget, and wire version) rather than raw struct bytes or padding. */ +static uint64_t canonical_policy_hash(const struct sircl_core_topology *t, uint32_t budget, unsigned wire) { + uint64_t h = UINT64_C(14695981039346656037); + h = fnv_u32(h, (uint32_t)t->nhosts); + for (int i = 0; i < t->nhosts; ++i) h = fnv_str(h, t->host[i]); + struct canon_cable cables[2 * MAX_POSITIONS]; + int nc = t->ncables; + if (nc < 0) nc = 0; + if (nc > 2 * MAX_POSITIONS) nc = 2 * MAX_POSITIONS; + for (int i = 0; i < nc; ++i) { + int a = t->cable[i].a, pa = t->cable[i].pa, b = t->cable[i].b, pb = t->cable[i].pb; + if (b < a || (b == a && pb < pa)) { + int ta = a, tpa = pa; + a = b; pa = pb; b = ta; pb = tpa; + } + cables[i] = (struct canon_cable){a, pa, b, pb}; + } + qsort(cables, (size_t)nc, sizeof cables[0], cmp_canon_cable); + h = fnv_u32(h, (uint32_t)nc); + for (int i = 0; i < nc; ++i) { + h = fnv_u32(h, (uint32_t)cables[i].a); + h = fnv_u32(h, (uint32_t)cables[i].pa); + h = fnv_u32(h, (uint32_t)cables[i].b); + h = fnv_u32(h, (uint32_t)cables[i].pb); + } + for (int p = 0; p < 2; ++p) + for (int l = 0; l < SIRCL_CORE_MAX_LANES; ++l) + h = fnv_str(h, t->fn[p][l]); + h = fnv_u32(h, budget); + h = fnv_u32(h, (uint32_t)wire); + return h; +} + int sircl_route_function(const struct sircl_core_topology *t, const char *name) { if (!name || !*name) return -1; for (int f = 0; f < ROUTE_FUNCTIONS; ++f) @@ -119,9 +181,6 @@ int sircl_route_plan_load(const char *path, uint32_t budget, unsigned wire, t->budget = plan->budget; plan->derived = sircl_route_allowances(t, plan->budget, plan->caps); sircl_split_allowances(t, plan->derived, plan->caps, plan->acks); - plan->policy = UINT64_C(14695981039346656037); - for (size_t i = 0; i < sizeof *t; ++i) - plan->policy = (plan->policy ^ ((const unsigned char *)t)[i]) * UINT64_C(1099511628211); - plan->policy = (plan->policy ^ wire) * UINT64_C(1099511628211); + plan->policy = canonical_policy_hash(t, plan->budget, wire); return 0; } diff --git a/net-sircl/net_sircl_profile.h b/net-sircl/net_sircl_profile.h index b4038c7..20ccfc1 100644 --- a/net-sircl/net_sircl_profile.h +++ b/net-sircl/net_sircl_profile.h @@ -32,10 +32,13 @@ struct profile_comm { static struct { pthread_mutex_t lock; char *prefix; - uint64_t epoch, next_comm, lost; + uint64_t epoch, next_comm, lost, flush_seq; struct profile_thread *threads; } profiler = {.lock = PTHREAD_MUTEX_INITIALIZER}; static int profile_enabled; +static inline int profile_is_enabled(void) { + return __atomic_load_n(&profile_enabled, __ATOMIC_ACQUIRE); +} static uint64_t profile_clock(clockid_t clock) { struct timespec ts; @@ -185,6 +188,10 @@ static void profile_hist_json(FILE *f, const char *name, const struct profile_hi * replaces earlier snapshots. No file IO or formatting occurs during progress. */ static void profile_flush(void) { pthread_mutex_lock(&profiler.lock); + if (!profiler.prefix) { + pthread_mutex_unlock(&profiler.lock); + return; + } char host[256] = "unknown"; (void)gethostname(host, sizeof host - 1); for (char *s = host; *s; s++) if (*s == '/' || *s == '\\') *s = '_'; @@ -192,9 +199,14 @@ static void profile_flush(void) { char *path = NULL, *tmp = NULL; if (asprintf(&path, "%s.%s.%ld.%" PRIu64 ".%ld.json", profiler.prefix, host, (long)getpid(), profiler.epoch, t->tid) < 0) continue; - if (asprintf(&tmp, "%s.tmp", path) < 0) { free(path); continue; } - FILE *f = fopen(tmp, "w"); - if (!f) { WARN("net-sircl: profile output %s: %s", tmp, strerror(errno)); goto next; } + if (asprintf(&tmp, "%s.%" PRIu64 ".tmp", path, ++profiler.flush_seq) < 0) { free(path); continue; } + int fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644); + FILE *f = fd >= 0 ? fdopen(fd, "w") : NULL; + if (!f) { + if (fd >= 0) { close(fd); unlink(tmp); } + WARN("net-sircl: profile output %s: %s", tmp, strerror(errno)); + goto next; + } fprintf(f, "{\"schema\":1,\"rank\":%d,\"pid\":%ld,\"tid\":%ld,\"host\":", g.position, (long)getpid(), t->tid); profile_string(f, host); @@ -223,7 +235,10 @@ static void profile_flush(void) { fputs("]}\n", f); int failed = ferror(f); if (fclose(f)) failed = 1; - if (failed || rename(tmp, path)) WARN("net-sircl: cannot finish profile %s", path); + if (failed || rename(tmp, path)) { + unlink(tmp); + WARN("net-sircl: cannot finish profile %s", path); + } next: free(tmp); free(path); } @@ -255,7 +270,8 @@ static void profile_close(struct comm *c) { profile_flush(); } static void profile_reset(void) { - /* Initialization/finalization occurs while transport global lock is held. */ + pthread_mutex_lock(&profiler.lock); + __atomic_store_n(&profile_enabled, 0, __ATOMIC_RELEASE); while (profiler.threads) { struct profile_thread *t = profiler.threads; profiler.threads = t->next; @@ -263,13 +279,16 @@ static void profile_reset(void) { free(t); } free(profiler.prefix); profiler.prefix = NULL; - profile_enabled = 0; profiler.lost = profiler.next_comm = 0; + pthread_mutex_unlock(&profiler.lock); } static void profile_init(void) { profile_reset(); + pthread_mutex_lock(&profiler.lock); const char *prefix = getenv("NET_SIRCL_PROFILE"); if (prefix && *prefix) profiler.prefix = strdup(prefix); - profile_enabled = profiler.prefix != NULL; - if (profile_enabled) profiler.epoch = profile_clock(CLOCK_REALTIME); + int enabled = profiler.prefix != NULL; + if (enabled) profiler.epoch = profile_clock(CLOCK_REALTIME); + __atomic_store_n(&profile_enabled, enabled, __ATOMIC_RELEASE); + pthread_mutex_unlock(&profiler.lock); } diff --git a/net-sircl/tests/layer_test.c b/net-sircl/tests/layer_test.c index cba5293..e28f296 100644 --- a/net-sircl/tests/layer_test.c +++ b/net-sircl/tests/layer_test.c @@ -352,7 +352,7 @@ static int receiver(int to_child, int from_child) { setenv("NET_SIRCL_ROUTES", "5=emu0/emu1", 1); } if (!strcmp(mode, "directlanes")) setenv("NET_SIRCL_STANDIN_DEVICES", "3", 1); - if (!strcmp(mode, "stray")) setenv("NET_SIRCL_CONNECT_TIMEOUT_MS", "1000", 1); /* the silent stray's wait */ + if (!strcmp(mode, "stray")) setenv("NET_SIRCL_CONNECT_TIMEOUT_MS", "60000", 1); /* silent stray must not HoL-block */ void *ctx = init(); char handles[3][H]; void *listen[3], *comms[3] = {NULL, NULL, NULL}; @@ -391,7 +391,10 @@ static int receiver(int to_child, int from_child) { NET.finalize(ctx); return WIFEXITED(status) ? WEXITSTATUS(status) : 1; } + double accept_started = now_s(); for (int i = 0; i < listens; ++i) comms[i] = accept_one(listen[i]); + if (!strcmp(mode, "stray") && now_s() - accept_started > 3.0) + die("silent stray head-of-line blocked a legitimate peer"); if (!strcmp(mode, "plain")) { plain_recv(comms[0]); } else if (!strcmp(mode, "windowed")) { @@ -447,6 +450,7 @@ static int receiver(int to_child, int from_child) { if (r != ncclRemoteError) die("a receive from a vanished peer did not fail with ncclRemoteError within 5 s"); printf("net-sircl layer test peerloss: the waiting receive failed with ncclRemoteError %.3f s after the " "peer ended\n", took); + NET.deregMr(comms[0], mr); NET.closeRecv(comms[0]); NET.closeListen(listen[0]); NET.finalize(ctx); diff --git a/net-sircl/tests/relay_test.c b/net-sircl/tests/relay_test.c index 82d827c..a8810ed 100644 --- a/net-sircl/tests/relay_test.c +++ b/net-sircl/tests/relay_test.c @@ -120,7 +120,9 @@ int main(int argc, char **argv) { void *pipeline_mr = NULL, *pipeline_request = NULL; assert(sircl_reg_mr(pipeline, payload, 1u << 20, NCCL_PTR_HOST, &pipeline_mr) == ncclSuccess); struct mr *pm = pipeline_mr; - pipeline->ctrl->cts[0] = (struct net_sircl_cts){.addr = nic_addr(pm, payload), .rkey = pm->ib->rkey, + uint64_t paddr = 0; + assert(nic_addr_checked(pm, payload, 1u << 20, &paddr)); + pipeline->ctrl->cts[0] = (struct net_sircl_cts){.addr = paddr, .rkey = pm->ib->rkey, .size = 1u << 20, .tag = 9}; pipeline->ctrl->cts_seq[0] = 1; hold = 1; @@ -185,7 +187,9 @@ int main(int argc, char **argv) { void *mr = NULL; assert(sircl_reg_mr(c, input, sizeof input, NCCL_PTR_HOST, &mr) == ncclSuccess); struct mr *m = mr; - c->ctrl->cts[0] = (struct net_sircl_cts){.addr = nic_addr(m, input), .rkey = m->ib->rkey, + uint64_t iaddr = 0; + assert(nic_addr_checked(m, input, sizeof input, &iaddr)); + c->ctrl->cts[0] = (struct net_sircl_cts){.addr = iaddr, .rkey = m->ib->rkey, .size = sizeof input, .tag = 7}; c->ctrl->cts_seq[0] = 1; hold = 1; diff --git a/net-sircl/tests/request_contract_test.c b/net-sircl/tests/request_contract_test.c index 0dde7b9..78557a5 100644 --- a/net-sircl/tests/request_contract_test.c +++ b/net-sircl/tests/request_contract_test.c @@ -18,6 +18,20 @@ int main(int argc, char **argv) { assert(sircl_dereg_mr(c, registration) == ncclSystemError); assert(mr->ib && mr->shadow && mr->size == sizeof data); assert(!unsetenv("SIRCL_EMU_FAIL_DEREG")); + + /* P1-2: oversized irecv fails closed (ncclInvalidArgument) and out-of-bounds buffer is rejected. */ + void *buf_ptr = data, *req = (void *)1; + size_t huge = (size_t)MAX_NET_BYTES + 1; + int tag = 0; + assert(sircl_irecv(c, 1, &buf_ptr, &huge, &tag, ®istration, NULL, &req) == ncclInvalidArgument && !req); + size_t too_wide = sizeof data + 1; + assert(sircl_irecv(c, 1, &buf_ptr, &too_wide, &tag, ®istration, NULL, &req) == ncclInvalidArgument && !req); + unsigned char outside[4] = {0}; + void *bad_ptr = outside; + size_t one = 1; + assert(sircl_irecv(c, 1, &bad_ptr, &one, &tag, ®istration, NULL, &req) == ncclInvalidArgument && !req); + assert(sircl_isend(NULL, data, 1, 0, NULL, NULL, &req) == ncclInvalidArgument && !req); + assert(sircl_dereg_mr(c, registration) == ncclSuccess); struct req *q = &c->reqs[0]; diff --git a/net-sircl/tests/settings_test.c b/net-sircl/tests/settings_test.c index 40f3912..77ad356 100644 --- a/net-sircl/tests/settings_test.c +++ b/net-sircl/tests/settings_test.c @@ -83,9 +83,11 @@ static void valid(const char *timeout, const char *retry, int want_timeout, int /* Live communicators share a snapshot; later environment edits cannot alter their QPs. */ setting("NET_SIRCL_IB_TIMEOUT", "invalid"); assert(sircl_init(&other, 0, NULL, capture, NULL) == ncclSuccess); - assert(ctx == other); + assert(ctx && other && ctx != other); check_qps(want_timeout, want_retry); assert(sircl_finalize(other) == ncclSuccess); + assert(sircl_finalize(other) == ncclInvalidArgument); /* duplicate finalize rejected */ + assert(sircl_finalize(NULL) == ncclInvalidArgument); /* NULL finalize rejected */ assert(g.refs == 1); assert(sircl_finalize(ctx) == ncclSuccess); assert(!g.refs && !g.ndevs); @@ -299,6 +301,53 @@ int main(void) { assert(comm_ready(c, &peer) == ncclRemoteError); comm_destroy(c); assert(sircl_finalize(ctx) == ncclSuccess); + + /* P0-4: poisoned relay window recovers cleanly on fresh sircl_init once drained; + * active comm defers resource teardown until closed. */ + setting("NET_SIRCL_WINDOWS", NULL); + void *ctx_a = NULL, *ctx_b = NULL; + assert(sircl_init(&ctx_a, 0, NULL, capture, NULL) == ncclSuccess); + struct comm *rc = comm_create(0, 1); + assert(rc); + meta_fill(rc, &peer); + peer.position = 3; + assert(comm_ready(rc, &peer) == ncclSuccess); + g.relay_windows[0].error = ncclRemoteError; + /* Finalizing while comm is open defers teardown until comm_destroy. */ + assert(sircl_finalize(ctx_a) == ncclSuccess); + assert(g.refs == 0 && g.initialized == 1 && g.active_comms == 1); + comm_destroy(rc); + assert(g.initialized == 0 && g.ndevs == 0 && g.active_comms == 0); + /* Fresh init under another active ref recovers drained relay window error. */ + assert(sircl_init(&ctx_a, 0, NULL, capture, NULL) == ncclSuccess); + g.relay_windows[0].error = ncclRemoteError; + assert(sircl_init(&ctx_b, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.relay_windows[0].error == ncclSuccess); + assert(sircl_finalize(ctx_b) == ncclSuccess); + assert(sircl_finalize(ctx_a) == ncclSuccess); + + /* P1-1: failed sircl_init must not leak profile_enabled or profiler.prefix. */ + setting("NET_SIRCL_PROFILE", "/tmp/sircl-should-not-leak"); + setting("NET_SIRCL_IB_TIMEOUT", "invalid"); + assert(sircl_init(&ctx, 0, NULL, capture, NULL) == ncclInvalidArgument); + assert(!profile_is_enabled() && profiler.prefix == NULL); + setting("NET_SIRCL_PROFILE", NULL); + setting("NET_SIRCL_IB_TIMEOUT", NULL); + + /* P1-2: sircl_connect validates device bounds and zeroes sendDevComm. */ + assert(sircl_init(&ctx, 0, NULL, capture, NULL) == ncclSuccess); + ncclNetDeviceHandle_v12_t *dev_handle = (ncclNetDeviceHandle_v12_t *)1; + assert(sircl_connect(ctx, -1, &old, &old_comm, &dev_handle) == ncclInvalidArgument && dev_handle == NULL); + dev_handle = (ncclNetDeviceHandle_v12_t *)1; + assert(sircl_connect(ctx, g.ndevs, &old, &old_comm, &dev_handle) == ncclInvalidArgument && dev_handle == NULL); + /* P1-8: lowering relay window cap via NET_SIRCL_WINDOWS proportionally lowers ack_cap. */ + assert(sircl_finalize(ctx) == ncclSuccess); + setting("NET_SIRCL_WINDOWS", "3=12288"); + assert(sircl_init(&ctx, 0, NULL, capture, NULL) == ncclSuccess); + assert(g.relay_windows[0].cap <= 12288u); + assert(g.relay_windows[0].ack_cap <= g.relay_windows[0].cap / 6u); + assert(sircl_finalize(ctx) == ncclSuccess); + setting("NET_SIRCL_WINDOWS", NULL); setting("NET_SIRCL_ROUTES", "3=emu1/emu0"); assert(sircl_init(&ctx, 0, NULL, capture, NULL) == ncclInvalidArgument); diff --git a/net-sircl/tests/test_net_sircl.py b/net-sircl/tests/test_net_sircl.py index 81b79aa..0d373be 100644 --- a/net-sircl/tests/test_net_sircl.py +++ b/net-sircl/tests/test_net_sircl.py @@ -11,6 +11,7 @@ import json import ctypes import os +import shlex import shutil import subprocess import sys @@ -24,7 +25,8 @@ CORE = next(p for p in (HERE.parent / "transport-core", HERE.parents[1] / "transport-core") if (p / "VERSION").is_file()) CORE_SOURCES = [str(CORE / "src" / f) for f in ("core.c", "topology.c", "sysfs.c")] CORE_SOURCES += [str(HERE / "net_sircl_plan.c")] -FLAGS = ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread"] +BASE_FLAGS = ["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-pthread"] +FLAGS = [*BASE_FLAGS, *shlex.split(os.environ.get("NET_SIRCL_TEST_EXTRA_CFLAGS", ""))] STANDIN_FLAGS = ["-I", str(CORE / "include"), "-DNET_SIRCL_STANDIN", "-I", str(HERE), "-I", str(STANDIN / "fake_verbs"), "-I", str(STANDIN)] @@ -39,7 +41,8 @@ def setUpClass(cls): cc = os.environ.get("CC", "cc") subprocess.run([cc, *FLAGS, *STANDIN_FLAGS, str(HERE / "tests" / "layer_test.c"), str(HERE / "net_sircl.c"), str(STANDIN / "shm_verbs.c"), *CORE_SOURCES, "-o", str(cls.layer)], check=True) - subprocess.run([cc, *FLAGS, *STANDIN_FLAGS, "-fPIC", "-shared", str(HERE / "net_sircl.c"), + # Keep the ctypes-loaded DSO free of sanitizer runtimes when Python itself is not preloaded with ASan. + subprocess.run([cc, *BASE_FLAGS, *STANDIN_FLAGS, "-fPIC", "-shared", str(HERE / "net_sircl.c"), str(STANDIN / "shm_verbs.c"), *CORE_SOURCES, "-o", str(cls.emu)], check=True) cls.lib = ctypes.CDLL(str(cls.emu)) cls.lib.net_sircl_topology_routes.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_size_t] @@ -247,10 +250,11 @@ def test_aggregate_relay_admission(self): finally: (Path("/dev/shm") / fabric.lstrip("/")).unlink(missing_ok=True) - def run_layer(self, mode): + def run_layer(self, mode, **extra_env): fabric = f"/sircl-emu-net-sircl-{os.getpid()}-{mode}" env = {k: v for k, v in os.environ.items() if not k.startswith("NET_SIRCL_")} env.update(SIRCL_EMU_FABRIC=fabric, NET_SIRCL_TOPOLOGY=str(self.topology), LAYER_QUIET="1") + env.update(extra_env) try: result = subprocess.run([str(self.layer), mode], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=180) @@ -460,7 +464,7 @@ def test_route_allowances_all_queues_and_reverse_acks(self): # Bounding the complete all-pairs set also bounds EVERY subset of ring, # tree and P2P routes and every multiplicity of channels on those routes. libpath = Path(self.build.name) / "route_model.so" - subprocess.run([os.environ.get("CC", "cc"), *FLAGS, *STANDIN_FLAGS, "-shared", "-fPIC", + subprocess.run([os.environ.get("CC", "cc"), *BASE_FLAGS, *STANDIN_FLAGS, "-shared", "-fPIC", str(HERE / "tests" / "route_model.c"), str(HERE / "net_sircl_plan.c"), str(CORE / "src/topology.c"), "-o", str(libpath)], check=True) lib = ctypes.CDLL(str(libpath)) @@ -599,15 +603,64 @@ def paths(path, target): def test_plugin_library_exports_the_v12_symbol(self): cc = os.environ.get("CC", "cc") lib = Path(self.build.name) / "libnccl-net-sircl.so" - subprocess.run([cc, *FLAGS, "-fPIC", "-shared", "-I", str(HERE), "-I", str(CORE / "include"), str(HERE / "net_sircl.c"), *CORE_SOURCES, "-o", str(lib), - "-libverbs"], check=True) + subprocess.run([cc, *BASE_FLAGS, "-fvisibility=hidden", "-fPIC", "-shared", "-I", str(HERE), + "-I", str(CORE / "include"), str(HERE / "net_sircl.c"), *CORE_SOURCES, + "-Wl,-soname,libnccl-net-sircl.so", + f"-Wl,--version-script={HERE / 'net_sircl.map'}", + "-Wl,-z,relro,-z,now", "-o", str(lib), "-libverbs"], check=True) nm = shutil.which("nm") if nm is None: self.skipTest("nm not installed") - symbols = subprocess.run([nm, "-D", "--defined-only", str(lib)], stdout=subprocess.PIPE, text=True, - check=True).stdout - for version in range(7, 13): - self.assertIn(f"ncclNetPlugin_v{version}", symbols) + output = subprocess.run([nm, "-D", "--defined-only", str(lib)], stdout=subprocess.PIPE, text=True, + check=True).stdout + exported = {line.split()[-1] for line in output.splitlines() if line.strip()} + expected = {f"ncclNetPlugin_v{v}" for v in range(7, 13)} | { + "ncclTunerPlugin_v4", "net_sircl_release", "net_sircl_core_release", "net_sircl_core_source" + } + self.assertEqual(exported, expected) + for hidden in ("net_sircl_stats", "net_sircl_comm_device", "net_sircl_topology_routes"): + self.assertNotIn(hidden, exported) + readelf = shutil.which("readelf") + if readelf is not None: + dyn = subprocess.run([readelf, "-d", str(lib)], stdout=subprocess.PIPE, text=True, check=True).stdout + self.assertIn("libnccl-net-sircl.so", dyn) + self.assertIn("BIND_NOW", dyn) + phdrs = subprocess.run([readelf, "-l", str(lib)], stdout=subprocess.PIPE, text=True, check=True).stdout + self.assertIn("GNU_RELRO", phdrs) + + def test_non_inline_fallback_transfers_exact(self): + # P1-4: when a provider grants max_inline_data=0, control words stage in ctrl_mr and transfers succeed. + self.assertIn("7 sizes and 32 pipelined messages exact", self.run_layer("plain", SIRCL_EMU_MAX_INLINE="0")) + self.assertIn("2 comms x 8 MiB exact", self.run_layer("windowed", SIRCL_EMU_MAX_INLINE="0")) + + def test_canonical_policy_hash_ignores_cable_order_and_direction(self): + # P1-2: equivalent topologies with reordered/reversed cable lines produce the same plan->policy. + exe = Path(self.build.name) / "policy_hash_test" + src = Path(self.build.name) / "policy_hash_test.c" + src.write_text( + '#include "net_sircl_plan.h"\n' + '#include \n' + 'int main(int argc, char **argv) {\n' + ' assert(argc == 3);\n' + ' struct sircl_route_plan a, b;\n' + ' char err[256];\n' + ' assert(!sircl_route_plan_load(argv[1], 327680, 6, &a, err, sizeof err));\n' + ' assert(!sircl_route_plan_load(argv[2], 327680, 6, &b, err, sizeof err));\n' + ' assert(a.policy == b.policy);\n' + ' return 0;\n' + '}\n' + ) + subprocess.run([os.environ.get("CC", "cc"), *FLAGS, "-I", str(HERE), "-I", str(CORE / "include"), + str(src), str(HERE / "net_sircl_plan.c"), str(CORE / "src/topology.c"), + "-o", str(exe)], check=True) + t1 = Path(self.build.name) / "p1.topology" + t2 = Path(self.build.name) / "p2.topology" + t1.write_text("hosts a b c d\ncabling ring\n") + t2.write_text("hosts a b c d\ncabling explicit\n" + "cable 3.port0 0.port1\ncable 2.port1 1.port0\n" + "cable 1.port1 0.port0\ncable 2.port0 3.port1\n") + res = subprocess.run([str(exe), str(t1), str(t2)], capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) def test_exported_abis_call_through_with_exact_layouts(self): for version in range(7, 13): From 9bf06a79033ef52079aabb0ca72b830e5d6c1726 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:32:08 -0600 Subject: [PATCH 3/4] fabric-tool: fix mesh_marker alignment UB & async events, harden install-boot & shell scripts, align topology parser (P0-1, P0-2, P1-5, P1-6) --- fabric-tool/Makefile | 7 +- fabric-tool/fabric-tool | 0 fabric-tool/fabric_tool/boot.py | 145 +++++++++++++++++- fabric-tool/fabric_tool/cli.py | 23 ++- fabric-tool/fabric_tool/commands.py | 22 ++- fabric-tool/fabric_tool/ops.py | 44 +++++- fabric-tool/fabric_tool/state.py | 34 ++-- fabric-tool/fabric_tool/topology.py | 19 ++- fabric-tool/mesh_marker.c | 63 +++++++- fabric-tool/tests/test_boot.py | 54 +++++++ fabric-tool/tests/test_commands.py | 35 ++++- fabric-tool/tests/test_marker_security.py | 2 +- fabric-tool/tests/test_operation_contracts.py | 4 +- fabric-tool/tests/test_review_fixes.py | 26 ++-- fabric-tool/tests/test_topology.py | 12 +- fabric-tool/tests/test_verify_loss.py | 33 ++++ tests/test_topology_conformance.py | 11 ++ 17 files changed, 464 insertions(+), 70 deletions(-) mode change 100644 => 100755 fabric-tool/fabric-tool diff --git a/fabric-tool/Makefile b/fabric-tool/Makefile index e14a3d8..4be54ce 100644 --- a/fabric-tool/Makefile +++ b/fabric-tool/Makefile @@ -1,6 +1,6 @@ PYTHON ?= python3 CC ?= cc -CFLAGS ?= -O2 -Wall -Wextra +CFLAGS ?= -std=c11 -O2 -Wall -Wextra -Werror PREFIX ?= /usr/local .PHONY: all check install clean @@ -13,11 +13,12 @@ build/fabric-tool-marker: mesh_marker.c check: $(PYTHON) -m pytest tests/ -q -rs -install: - install -d $(DESTDIR)$(PREFIX)/lib/fabric-tool/fabric_tool $(DESTDIR)$(PREFIX)/bin +install: all + install -d $(DESTDIR)$(PREFIX)/lib/fabric-tool/fabric_tool $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/libexec/fabric-tool install -m 0644 fabric_tool/*.py $(DESTDIR)$(PREFIX)/lib/fabric-tool/fabric_tool/ install -m 0644 mesh_marker.c README.md DESIGN.md HARDWARE-TEST-PLAN.md LICENSE NOTICE VERSION $(DESTDIR)$(PREFIX)/lib/fabric-tool/ install -m 0755 fabric-tool $(DESTDIR)$(PREFIX)/bin/fabric-tool + install -m 0755 build/fabric-tool-marker $(DESTDIR)$(PREFIX)/libexec/fabric-tool/fabric-tool-marker clean: rm -rf build diff --git a/fabric-tool/fabric-tool b/fabric-tool/fabric-tool old mode 100644 new mode 100755 diff --git a/fabric-tool/fabric_tool/boot.py b/fabric-tool/fabric_tool/boot.py index 050b3c7..3134800 100644 --- a/fabric-tool/fabric_tool/boot.py +++ b/fabric-tool/fabric_tool/boot.py @@ -15,12 +15,18 @@ from __future__ import annotations import dataclasses +import os +import posixpath +import secrets import shutil +import stat import subprocess +import tempfile import time from pathlib import Path from . import commands, model +from .model import FabricError UNIT_NAME = "fabric-table.service" RECOVERY_SERVICE = "fabric-table-reconcile.service" @@ -33,6 +39,131 @@ DEFAULT_TOOL = BIN_PATH +def validate_tool_path(tool: str) -> str: + """Apply the same normalized, non-shared-writable path policy to ``--tool`` as to markers.""" + if not commands._PATH.fullmatch(tool) or "/../" in f"{tool}/": + raise FabricError(f"tool path {tool!r} must be an absolute path of letters, digits and _./+-") + if tool != posixpath.normpath(tool) or tool.startswith("//"): + raise FabricError(f"tool path {tool!r} must be a normalized absolute path") + for directory in commands.SHARED_WRITABLE_DIRS: + if tool == directory or tool.startswith(directory + "/"): + raise FabricError(f"tool path {tool!r} is under {directory}, which every local user can " + "write; the boot unit runs as root, so --tool must be a root-owned " + f"location such as the default {DEFAULT_TOOL}") + return tool + + +def check_root_owned_path(path: str, *, existing_only: bool = False) -> None: + """Verify ``path`` and every parent directory up to ``/`` are root-owned and not group/other writable.""" + checked: list[str] = [] + current = posixpath.normpath(path) + while current != "/": + checked.append(current) + current = posixpath.dirname(current) + checked.append("/") + for entry in checked: + try: + info = os.lstat(entry) + except FileNotFoundError: + if existing_only: + continue + raise FabricError(f"refusing to install boot unit: {entry} must exist, be owned by root " + "and not be writable by group or others") from None + if stat.S_ISLNK(info.st_mode): + raise FabricError(f"refusing to install boot unit: {entry} must not be a symbolic link") + if info.st_uid != 0 or (info.st_mode & 0o022): + raise FabricError(f"refusing to install boot unit: {entry} must be owned by root " + "and not be writable by group or others") + + +def _atomic_write(path: Path, content: str, *, mode: int = 0o644) -> None: + """Write ``content`` to ``path`` atomically with ``O_NOFOLLOW``, explicit mode and ``root:root``.""" + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_symlink(): + raise FabricError(f"refusing to write {path}: target is a symbolic link") + tmp = path.parent / f".{path.name}.tmp.{secrets.token_hex(8)}" + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(str(tmp), flags, mode) + try: + data = content.encode("utf-8") + view = memoryview(data) + while view: + written = os.write(fd, view) + view = view[written:] + os.fchmod(fd, mode) + if hasattr(os, "geteuid") and os.geteuid() == 0: + os.fchown(fd, 0, 0) + os.fsync(fd) + except BaseException: + os.close(fd) + try: + os.unlink(str(tmp)) + except OSError: + pass + raise + os.close(fd) + os.replace(str(tmp), str(path)) + + +def install_package(source: Path, *, root: str = "/") -> tuple[Path, Path]: + """Stage only ``fabric_tool/*.py`` and ``mesh_marker.c`` into ``LIB_DIR`` atomically with 0755/0644 and root:root.""" + target = Path(root) / LIB_DIR.lstrip("/") + wrapper = Path(root) / BIN_PATH.lstrip("/") + pkg_src = source / "fabric_tool" + marker_src = source / "mesh_marker.c" + if not pkg_src.is_dir() or not marker_src.is_file() or marker_src.is_symlink(): + raise FabricError(f"cannot install fabric-tool from {source}: missing fabric_tool/ package or mesh_marker.c") + if root == "/": + check_root_owned_path(LIB_DIR, existing_only=True) + check_root_owned_path(BIN_PATH, existing_only=True) + if target.is_symlink(): + raise FabricError(f"refusing to install to {target}: target is a symbolic link") + target.parent.mkdir(parents=True, exist_ok=True) + is_root = hasattr(os, "geteuid") and os.geteuid() == 0 + if target.resolve() != source.resolve(): + staging = Path(tempfile.mkdtemp(prefix=".fabric-tool.stage.", dir=str(target.parent))) + backup: Path | None = None + try: + os.chmod(staging, 0o755) + pkg_dst = staging / "fabric_tool" + pkg_dst.mkdir(mode=0o755) + os.chmod(pkg_dst, 0o755) + py_files = sorted(p for p in pkg_src.iterdir() + if p.suffix == ".py" and p.is_file() and not p.is_symlink()) + if not py_files: + raise FabricError(f"cannot install fabric-tool from {source}: no Python modules in {pkg_src}") + for py_file in py_files: + dst = pkg_dst / py_file.name + _atomic_write(dst, py_file.read_text(encoding="utf-8"), mode=0o644) + _atomic_write(staging / "mesh_marker.c", marker_src.read_text(encoding="utf-8"), mode=0o644) + for optional in ("README.md", "VERSION", "LICENSE", "NOTICE"): + opt_src = source / optional + if opt_src.is_file() and not opt_src.is_symlink(): + _atomic_write(staging / optional, opt_src.read_text(encoding="utf-8"), mode=0o644) + if is_root: + os.chown(staging, 0, 0) + os.chown(pkg_dst, 0, 0) + if target.exists(): + backup = target.parent / f".fabric-tool.old.{secrets.token_hex(8)}" + os.replace(str(target), str(backup)) + try: + os.replace(str(staging), str(target)) + except BaseException: + if backup is not None and backup.exists() and not target.exists(): + os.replace(str(backup), str(target)) + raise + if backup is not None and backup.exists(): + shutil.rmtree(backup) + except BaseException: + if staging.exists(): + shutil.rmtree(staging, ignore_errors=True) + raise + _atomic_write(wrapper, wrapper_text(), mode=0o755) + return target, wrapper + + @dataclasses.dataclass(frozen=True) class RestoreInvocation: """Behavior persisted by the boot unit and used by immediate restoration.""" @@ -43,6 +174,10 @@ class RestoreInvocation: host: str | None = None skip_hostname_check: bool = False + def __post_init__(self) -> None: + validate_tool_path(self.tool) + commands.MarkerConfig(self.marker) + def argv(self) -> tuple[str, ...]: args = (self.tool, "apply", "--boot", "--execute", "--topology", TOPOLOGY_INPUT, "--facts", FACTS_INPUT, "--marker", self.marker, "--max-relays", str(self.max_relays)) @@ -135,12 +270,11 @@ def plan(topology_path: str, facts_path: str, tool: str = DEFAULT_TOOL, *, def install(spec: BootPlan, *, root: str = "/", execute: bool) -> list[str]: - """Write the unit and inputs; with ``root`` (tests) under that directory, else enable the unit.""" + """Write the unit and inputs atomically; with ``root`` (tests) under that directory, else enable the unit.""" written = [] for destination, content in spec.files: path = Path(root) / destination.lstrip("/") - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(content, encoding="utf-8") + _atomic_write(path, content, mode=0o644) written.append(str(path)) if root != "/": return written @@ -202,12 +336,11 @@ def _rmdir_if_empty(directory: Path) -> None: def copy_inputs(topology_path: str, facts_path: str, *, root: str = "/") -> list[str]: - """Copy validated inputs to ``/etc/fabric-table/`` (used by ``install-boot`` before the unit runs).""" + """Copy validated inputs to ``/etc/fabric-table/`` atomically (used by ``install-boot`` before the unit runs).""" written = [] for source, destination in ((topology_path, TOPOLOGY_INPUT), (facts_path, FACTS_INPUT)): target = Path(root) / destination.lstrip("/") - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(source, target) + _atomic_write(target, Path(source).read_text(encoding="utf-8"), mode=0o644) written.append(str(target)) return written diff --git a/fabric-tool/fabric_tool/cli.py b/fabric-tool/fabric_tool/cli.py index c2e673b..677e6ba 100644 --- a/fabric-tool/fabric_tool/cli.py +++ b/fabric-tool/fabric_tool/cli.py @@ -32,7 +32,6 @@ import argparse import json -import shutil import socket import subprocess import sys @@ -241,7 +240,9 @@ def _command_status(args: argparse.Namespace, topology: topology_mod.Topology, executor: ops.Executor) -> int: hosts = _resolve_hosts(topology, args) marker = commands.MarkerConfig(args.marker) - states = ops.gather(hosts, sorted(hosts), executor, marker, bindings=topology.bindings) + file_facts = _file_facts(args, topology) + bindings = file_facts.bindings if file_facts else topology.bindings + states = ops.gather(hosts, sorted(hosts), executor, marker, bindings=bindings) print(report.render_show(states, marker)) return 0 if all(state.reachable for state in states.values()) else 1 @@ -250,7 +251,9 @@ def _command_marker(args: argparse.Namespace, topology: topology_mod.Topology, executor: ops.Executor) -> int: hosts = _resolve_hosts(topology, args) marker = commands.MarkerConfig(args.marker) - states = ops.gather(hosts, sorted(hosts), executor, marker, bindings=topology.bindings) + file_facts = _file_facts(args, topology) + bindings = file_facts.bindings if file_facts else topology.bindings + states = ops.gather(hosts, sorted(hosts), executor, marker, bindings=bindings) print(_marker_status(states, marker)) # A missing executable, or one without the digest its install recorded, is (re)built. targets = [p for p in sorted(hosts) if states[p].reachable @@ -339,14 +342,9 @@ def _command_install_boot(args: argparse.Namespace, topology: topology_mod.Topol if Path(f"/etc/systemd/system/{boot.RECOVERY_TIMER}").exists(): boot.stop_reconciliation() source = Path(__file__).resolve().parents[1] - target = Path(boot.LIB_DIR) - if target.resolve() != source.resolve(): - shutil.copytree(source, target, dirs_exist_ok=True) - print(f"copied {source} to {target}") - wrapper = Path(boot.BIN_PATH) - wrapper.write_text(boot.wrapper_text(), encoding="utf-8") - wrapper.chmod(0o755) - print(f"wrote {wrapper}") + target, wrapper = boot.install_package(source, root=args.root) + boot.check_root_owned_path(args.tool, existing_only=False) + print(f"installed package to {target} and wrote {wrapper}") boot.install(spec, root=args.root, execute=True) print(f"enabled {boot.UNIT_NAME} and {boot.RECOVERY_TIMER}") # The units are installed: the timer runs whatever the apply below returns, so a failed check is retried. @@ -424,8 +422,9 @@ def relay_options(sub: argparse.ArgumentParser) -> None: "--execute)")): sub = commands_parser.add_parser(name, help=text) common(sub) - if name in ("apply", "verify", "remove"): + if name in ("apply", "verify", "remove", "status", "install-marker"): plan_facts(sub) + if name in ("apply", "verify", "remove"): relay_options(sub) sub.add_argument("--verbose", action="store_true", help="also list unchanged objects") if name in ("apply", "remove"): diff --git a/fabric-tool/fabric_tool/commands.py b/fabric-tool/fabric_tool/commands.py index edb1df7..af6c013 100644 --- a/fabric-tool/fabric_tool/commands.py +++ b/fabric-tool/fabric_tool/commands.py @@ -383,13 +383,18 @@ def marker_start(marker: MarkerConfig, device: str, def marker_stop(marker: MarkerConfig, pid: int) -> tuple[str, str]: - """Signal one marker process (only while it still is one) and wait up to 5 s for it to exit. + """Signal one root-owned marker process (only while it still is one) and wait up to 5 s, escalating to SIGKILL. The marker removes its RDMA-TX rules when it exits. """ pid = int(pid) - return (f'[ "$(cat /proc/{pid}/comm 2>/dev/null)" != {q(marker.comm)} ] || sudo -n kill {pid}', - f"for i in $(seq 1 50); do [ -e /proc/{pid} ] || break; sleep 0.1; done; [ ! -e /proc/{pid} ]") + match = (f'[ "$(stat -c %u /proc/{pid} 2>/dev/null)" = 0 ] && ' + f'[ "$(cat /proc/{pid}/comm 2>/dev/null)" = {q(marker.comm)} ]') + return (f'! ( {match} ) || sudo -n kill {pid}', + f'for i in $(seq 1 50); do [ -e /proc/{pid} ] || break; sleep 0.1; done; ' + f'if {match}; then sudo -n kill -KILL {pid} 2>/dev/null || true; ' + f'for i in $(seq 1 10); do [ -e /proc/{pid} ] || break; sleep 0.1; done; fi; ' + f'[ ! -e /proc/{pid} ] || ! ( {match} )') def record_text(record: Mapping[str, object]) -> str: @@ -397,8 +402,10 @@ def record_text(record: Mapping[str, object]) -> str: def record_write(record: Mapping[str, object]) -> tuple[str, str]: - return (f"sudo -n mkdir -p {STATE_DIR}", - f"printf '%s\\n' {q(record_text(record))} | sudo -n tee {RECORD_PATH} >/dev/null") + return (f"sudo -n install -d -o root -g root -m 0755 {STATE_DIR}", + f"printf '%s\\n' {q(record_text(record))} | sudo -n bash -c " + f"'tmp=$(mktemp {STATE_DIR}/.relay-state.XXXXXX) && trap \"rm -f \\\"$tmp\\\"\" ERR && " + f"cat > \"$tmp\" && chmod 0644 \"$tmp\" && mv -f \"$tmp\" {RECORD_PATH}'") def record_remove() -> str: @@ -428,11 +435,12 @@ def marker_build_script(hostname: str, marker: MarkerConfig, source: str) -> str f"cat > \"$work/mesh_marker.c\" <<'{MARKER_SOURCE_END}'", source.rstrip("\n"), MARKER_SOURCE_END, - "cc -O2 -Wall -Wextra \"$work/mesh_marker.c\" -o \"$work/marker\" -libverbs -lmlx5", + "cc -std=c11 -O2 -Wall -Wextra -Werror \"$work/mesh_marker.c\" -o \"$work/marker\" -libverbs -lmlx5", _owner_check(marker.checked_paths[2:], "install the marker", existing_only=True), f"sudo -n install -d -o root -g root -m 0755 {q(marker.directory)}", f"sudo -n install -o root -g root -m 0755 \"$work/marker\" {q(marker.path)}", - f"sha256sum {q(marker.path)} | sudo -n tee {q(marker.record)} >/dev/null", + f"sha256sum {q(marker.path)} > \"$work/marker.sha256\"", + f"sudo -n install -o root -g root -m 0644 \"$work/marker.sha256\" {q(marker.record)}", *marker_checks(marker, "install the marker"), f"sha256sum {q(marker.path)}", ]) + "\n" diff --git a/fabric-tool/fabric_tool/ops.py b/fabric-tool/fabric_tool/ops.py index 2a4ce83..b3a3c42 100644 --- a/fabric-tool/fabric_tool/ops.py +++ b/fabric-tool/fabric_tool/ops.py @@ -282,13 +282,45 @@ def lane_route_checks(outcome: Outcome, *, installed_only: bool) -> dict[int, di return checks +def _lane_route_sources(outcome: Outcome, *, installed_only: bool) -> dict[int, dict[str, str]]: + """Expected local source IPv4 address for every lane route check.""" + sources: dict[int, dict[str, str]] = {} + plan = outcome.plan + if plan is None: + return sources + layout = plan.layout + compared = {d.position for d in outcome.diffs} + pending = {(d.position, change.key.split("/")[0]) for d in outcome.diffs + for change in d.changes if change.kind == "route" and change.action in ("add", "replace")} + for host in plan.hosts: + if host.position not in compared: + continue + for route in host.routes: + if not (installed_only and (host.position, route.destination) in pending): + sources.setdefault(host.position, {})[route.destination] = route.source + facts = outcome.facts + for rank, peers in enumerate(plan.sircl.ranks): + origin = layout.positions[rank] + if origin not in compared: + continue + for peer, lanes in peers.items(): + for lane in lanes: + if lane.hops == 1 and facts is not None and facts.has(layout.positions[peer]) and facts.has(origin): + destination = facts.port(layout.positions[peer], lane.remote.netdev).address + source = facts.port(origin, lane.local.netdev).address + sources.setdefault(origin, {})[destination] = source + return sources + + def check_lane_routes(hosts: dict[int, HostTarget], outcome: Outcome, executor: Executor, *, installed_only: bool, timeout: float = READ_TIMEOUT) -> dict[int, list[str]]: """Resolve every lane destination on its origin host (READ-ONLY REMOTE); problems per host.""" checks = lane_route_checks(outcome, installed_only=installed_only) + expected_sources = _lane_route_sources(outcome, installed_only=installed_only) def resolve(position: int) -> list[str]: wanted = checks[position] + sources = expected_sources.get(position, {}) result = executor(hosts[position].ssh or "", commands.route_get_script(wanted), timeout) answers = state_mod.parse_sections(result.stdout) problems = [] @@ -296,9 +328,19 @@ def resolve(position: int) -> list[str]: answer = answers.get(f"route:{destination}", "").strip() words = answer.split() device = words[words.index("dev") + 1] if "dev" in words[:-1] else None + gateway = words[words.index("via") + 1] if "via" in words[:-1] else None + source = words[words.index("src") + 1] if "src" in words[:-1] else None + expected_src = sources.get(destination) + first_line = answer.splitlines()[0] if answer else "no answer" if device != netdev: problems.append(f"ip route get {destination} uses {device or 'no device'}, the lane needs {netdev} " - f"({answer.splitlines()[0] if answer else 'no answer'})") + f"({first_line})") + elif gateway is not None: + problems.append(f"ip route get {destination} routes via gateway {gateway}, the lane must be on-link " + f"({first_line})") + elif expected_src is not None and source is not None and source != expected_src: + problems.append(f"ip route get {destination} uses src {source}, the lane needs {expected_src} " + f"({first_line})") return problems return {position: problems for position, problems in _parallel(sorted(checks), resolve).items() if problems} diff --git a/fabric-tool/fabric_tool/state.py b/fabric-tool/fabric_tool/state.py index f5b9547..9bbbed0 100644 --- a/fabric-tool/fabric_tool/state.py +++ b/fabric-tool/fabric_tool/state.py @@ -559,14 +559,15 @@ def _exit_status(raw: Mapping[str, str], section: str) -> int | None: return int(words[0]) if len(words) == 1 and words[0].isascii() and words[0].isdigit() else None -def read_failures(raw: Mapping[str, str], bindings: model.FabricBindings) -> list[str]: +def read_failures(raw: Mapping[str, str], bindings: model.FabricBindings, *, + ingress_qdisc: Mapping[str, str | None] | None = None) -> list[str]: """Reads whose empty output must not be taken for a host that holds nothing. A tool the read account cannot run; a failed read of the addresses, the - routes or the permanent neighbours; a ``tc`` that could not be executed - (exit 126 or 127; any other failure of ``tc`` is how a device without an - ingress qdisc may answer, so it is not judged); and a ``pgrep`` that - failed (exit 1 only says that no process matched). + routes, the permanent neighbours, or ``tc -j qdisc show``; a ``tc -j filter + show ... ingress`` failure when an ingress qdisc is present (or exit 126/127 + when ``tc`` could not be executed); and a ``pgrep`` that failed (exit 1 + only says that no process matched). """ found = [f"the read account cannot run {tool}: it is not on its PATH, so nothing {tool} reports was read" for tool in commands.READ_TOOLS if tool in raw.get("tools", "").split()] @@ -577,11 +578,22 @@ def read_failures(raw: Mapping[str, str], bindings: model.FabricBindings) -> lis found.append(f"{command} " + (f"failed with exit status {status}" if status is not None else "reported no exit status") + "; its output was not read") for netdev in bindings.netdevs: - for section, command in ((f"qdisc:{netdev}", f"tc -j qdisc show dev {netdev}"), - (f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress")): - status = _exit_status(raw, section) - if status in (126, 127): - found.append(f"{command} could not be executed (exit status {status}); its output was not read") + qdisc_section = f"qdisc:{netdev}" + qdisc_cmd = f"tc -j qdisc show dev {netdev}" + qdisc_status = _exit_status(raw, qdisc_section) + if qdisc_status in (126, 127): + found.append(f"{qdisc_cmd} could not be executed (exit status {qdisc_status}); its output was not read") + elif qdisc_status != 0: + found.append(f"{qdisc_cmd} " + (f"failed with exit status {qdisc_status}" if qdisc_status is not None + else "reported no exit status") + "; its output was not read") + filter_section = f"filters:{netdev}" + filter_cmd = f"tc -j filter show dev {netdev} ingress" + filter_status = _exit_status(raw, filter_section) + if filter_status in (126, 127): + found.append(f"{filter_cmd} could not be executed (exit status {filter_status}); its output was not read") + elif filter_status != 0 and (ingress_qdisc is not None and ingress_qdisc.get(netdev) is not None): + found.append(f"{filter_cmd} " + (f"failed with exit status {filter_status}" if filter_status is not None + else "reported no exit status") + "; its output was not read") status = _exit_status(raw, "markers") if status not in (0, 1): found.append("pgrep " + (f"failed with exit status {status}" if status is not None @@ -621,7 +633,6 @@ def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, s # No read prints a section header twice: a repeated one is output that imitates the script. problems.extend(f"the read printed the section {section!r} more than once; only the first was used" for section in repeated) - problems.extend(read_failures(raw, bindings)) state.hostname = raw.get("hostname", "").strip() state.versions = " | ".join(line.strip() for line in raw.get("versions", "").splitlines() if line.strip()) state.links = parse_links(raw.get("links", ""), problems) @@ -633,6 +644,7 @@ def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, s for netdev in bindings.netdevs: state.ingress_qdisc[netdev] = parse_ingress_qdisc(raw.get(f"qdisc:{netdev}", ""), problems, netdev) state.filters[netdev] = parse_filters(raw.get(f"filters:{netdev}", ""), problems, netdev) + problems.extend(read_failures(raw, bindings, ingress_qdisc=state.ingress_qdisc)) state.markers = parse_markers(raw.get("markers", "")) binary = raw.get("marker-binary", "").split() state.marker_binary = binary[0] if binary and len(binary[0]) == 64 else None diff --git a/fabric-tool/fabric_tool/topology.py b/fabric-tool/fabric_tool/topology.py index ada473a..278e906 100644 --- a/fabric-tool/fabric_tool/topology.py +++ b/fabric-tool/fabric_tool/topology.py @@ -44,12 +44,15 @@ from .model import Cable, Fabric, FabricError, Layout, Role DEFAULT_BUDGET = 393216 # 75 % of a ConnectX-7 hairpin queue of 512 KiB +MIN_BUDGET = 65536 +MAX_BUDGET = 393216 DEFAULT_FUNCTIONS = ("rocep1s0f0", "roceP2p1s0f0", "rocep1s0f1", "roceP2p1s0f1") DEFAULT_NETDEVS = ("enp1s0f0np0", "enP2p1s0f0np0", "enp1s0f1np1", "enP2p1s0f1np1") CABLING_KINDS = ("ring", "path", "explicit") MAX_HOSTS = 64 # the plugin's position limit MAX_HOST_NAME_BYTES = 63 # the plugin stores a host name in 64 bytes _DECIMAL = re.compile(r"[0-9]+") +_HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$") @dataclasses.dataclass(frozen=True) @@ -221,12 +224,20 @@ def parse(text: str, *, path: str = "") -> Topology: elif key in ("port0", "port1"): if len(rest) not in (1, 2): raise FabricError(f"{path}:{lineno}: {key} requires one or two device identifiers") + for identifier in rest: + try: + model.device_name(identifier) + except FabricError: + raise FabricError(f"{path}:{lineno}: invalid device identifier {identifier}") from None port = int(key[-1]) port_functions[port] = list(rest) elif key == "relay_budget": - if len(rest) != 1 or not _DECIMAL.fullmatch(rest[0]) or int(rest[0]) == 0: - raise FabricError(f"{path}:{lineno}: relay_budget is a positive byte count") - budget = int(rest[0]) + if len(rest) != 1 or not _DECIMAL.fullmatch(rest[0]): + raise FabricError(f"{path}:{lineno}: relay_budget is a positive byte count in {MIN_BUDGET}..{MAX_BUDGET}") + value = int(rest[0]) + if not MIN_BUDGET <= value <= MAX_BUDGET: + raise FabricError(f"{path}:{lineno}: relay_budget is a positive byte count in {MIN_BUDGET}..{MAX_BUDGET}") + budget = value elif key == "net-sircl-topology": if rest: raise FabricError(f"{path}:{lineno}: unknown words after net-sircl-topology") @@ -239,6 +250,8 @@ def parse(text: str, *, path: str = "") -> Topology: for name in hosts: if len(name.encode("utf-8")) > MAX_HOST_NAME_BYTES: raise FabricError(f"{path}: host name {name!r} is longer than {MAX_HOST_NAME_BYTES} bytes") + if not _HOSTNAME.fullmatch(name): + raise FabricError(f"{path}: invalid host name {name!r}") if len(set(hosts)) != len(hosts): raise FabricError(f"{path}: `hosts` names a host twice") if cabling not in CABLING_KINDS: diff --git a/fabric-tool/mesh_marker.c b/fabric-tool/mesh_marker.c index eb21e00..2a761dd 100644 --- a/fabric-tool/mesh_marker.c +++ b/fabric-tool/mesh_marker.c @@ -13,15 +13,17 @@ * on the tag. The rules stay installed until SIGINT/SIGTERM (--managed) or * for --run-seconds; process exit removes them. * - * Build: cc -O2 -Wall -Wextra mesh_marker.c -o ring8-mesh-marker -libverbs -lmlx5 + * Build: cc -std=c11 -O2 -Wall -Wextra -Werror mesh_marker.c -o fabric-tool-marker -libverbs -lmlx5 */ #include #include +#include #include #include #include #include +#include #include #include #include @@ -195,17 +197,35 @@ static struct ibv_context *open_context(const char *name) return context; } -static int wait_for_stop(const struct options *options) +static void print_json_string(FILE *stream, const char *text) +{ + fputc('"', stream); + for (const unsigned char *p = (const unsigned char *)text; *p != '\0'; ++p) { + if (*p < 0x20U || *p == '"' || *p == '\\') { + fprintf(stream, "\\u%04x", (unsigned int)*p); + } else { + fputc(*p, stream); + } + } + fputc('"', stream); +} + +static int wait_for_stop(struct ibv_context *context, const struct options *options) { struct timespec deadline; + int flags = fcntl(context->async_fd, F_GETFL, 0); + if (flags < 0 || fcntl(context->async_fd, F_SETFL, flags | O_NONBLOCK) != 0) { + return -1; + } if (clock_gettime(CLOCK_MONOTONIC, &deadline) != 0) { return -1; } deadline.tv_sec += (time_t)options->run_seconds; while (!stop_requested) { - const struct timespec interval = {0, STOP_POLL_NANOSECONDS}; + struct pollfd pfd; struct timespec now; + int ready; if (!options->managed) { if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) { @@ -216,9 +236,34 @@ static int wait_for_stop(const struct options *options) return 0; } } - if (nanosleep(&interval, NULL) != 0 && errno != EINTR) { + pfd.fd = context->async_fd; + pfd.events = POLLIN; + pfd.revents = 0; + ready = poll(&pfd, 1, (int)(STOP_POLL_NANOSECONDS / 1000000L)); + if (ready < 0) { + if (errno == EINTR) { + continue; + } return -1; } + if (ready > 0 && (pfd.revents & (POLLIN | POLLERR | POLLHUP))) { + struct ibv_async_event event; + + while (ibv_get_async_event(context, &event) == 0) { + enum ibv_event_type event_type = event.event_type; + + ibv_ack_async_event(&event); + if (event_type == IBV_EVENT_DEVICE_FATAL || event_type == IBV_EVENT_PORT_ERR) { + fprintf(stderr, "RDMA async event %d (%s) on %s; exiting for reconciliation\n", + (int)event_type, ibv_event_type_str(event_type), options->device_name); + errno = EIO; + return -1; + } + } + if (errno != EAGAIN && errno != EWOULDBLOCK) { + return -1; + } + } } return 0; } @@ -277,12 +322,14 @@ int main(int argc, char **argv) struct mlx5dv_flow_action_attr action = {0}; const uint16_t ipv4_ethertype = htons(0x0800U); uint32_t words[2]; + uint64_t action_word; words[0] = htonl((MLX5_MODIFICATION_TYPE_SET << 28) | ((uint32_t)MLX5_MODIFICATION_FIELD_OUTER_ETHERTYPE << 16) | 16U); words[1] = htonl((uint32_t)rule->ethertype); + memcpy(&action_word, words, sizeof(words)); rule->action = mlx5dv_create_flow_action_modify_header( - context, sizeof(words), (uint64_t *)(void *)words, MLX5DV_FLOW_TABLE_TYPE_RDMA_TX); + context, sizeof(action_word), &action_word, MLX5DV_FLOW_TABLE_TYPE_RDMA_TX); if (rule->action == NULL) { fprintf(stderr, "RDMA-TX EtherType rewrite action creation failed: %s\n", strerror(errno)); @@ -301,7 +348,9 @@ int main(int argc, char **argv) } installed++; } - printf("{\"device\":\"%s\",\"rules\":[", options.device_name); + fputs("{\"device\":", stdout); + print_json_string(stdout, options.device_name); + fputs(",\"rules\":[", stdout); for (int i = 0; i < options.rule_count; ++i) { printf("%s{\"dst\":\"%s\",\"ethertype\":\"0x%04x\"}", i ? "," : "", inet_ntoa(options.rules[i].address), options.rules[i].ethertype); @@ -309,7 +358,7 @@ int main(int argc, char **argv) printf("],\"installed\":%d,\"managed\":%s,\"run_seconds\":%u}\n", installed, options.managed ? "true" : "false", options.run_seconds); fflush(stdout); - if (wait_for_stop(&options) != 0) { + if (wait_for_stop(context, &options) != 0) { fprintf(stderr, "wait failed: %s\n", strerror(errno)); goto cleanup; } diff --git a/fabric-tool/tests/test_boot.py b/fabric-tool/tests/test_boot.py index 504b4dd..f237f6b 100644 --- a/fabric-tool/tests/test_boot.py +++ b/fabric-tool/tests/test_boot.py @@ -138,3 +138,57 @@ def systemctl(argv, **kwargs): boot.remove(execute=True) assert len(observations) == 3 assert not any(path.exists() for path in files) + + +def test_install_package_stages_only_python_and_marker_with_explicit_modes(tmp_path): + import os + import stat + from pathlib import Path + import pytest + from fabric_tool.model import FabricError + + source = tmp_path / "src" + (source / "fabric_tool" / "__pycache__").mkdir(parents=True) + (source / "tests").mkdir() + (source / "build").mkdir() + (source / "fabric_tool" / "__init__.py").write_text("", encoding="utf-8") + (source / "fabric_tool" / "cli.py").write_text("# cli\n", encoding="utf-8") + (source / "fabric_tool" / "__pycache__" / "cli.cpython-312.pyc").write_bytes(b"pyc") + (source / "tests" / "test_secret.py").write_text("# test\n", encoding="utf-8") + (source / "build" / "junk.o").write_bytes(b"obj") + (source / "mesh_marker.c").write_text("int main(void){return 0;}\n", encoding="utf-8") + os.chmod(source / "fabric_tool" / "cli.py", 0o666) + os.chmod(source / "mesh_marker.c", 0o777) + + fake_root = tmp_path / "root" + target, wrapper = boot.install_package(source, root=str(fake_root)) + assert (target / "fabric_tool" / "cli.py").is_file() + assert (target / "mesh_marker.c").is_file() + assert not (target / "tests").exists() + assert not (target / "build").exists() + assert not (target / "fabric_tool" / "__pycache__").exists() + assert stat.S_IMODE((target / "fabric_tool" / "cli.py").stat().st_mode) == 0o644 + assert stat.S_IMODE((target / "mesh_marker.c").stat().st_mode) == 0o644 + assert stat.S_IMODE(target.stat().st_mode) == 0o755 + assert stat.S_IMODE((target / "fabric_tool").stat().st_mode) == 0o755 + assert stat.S_IMODE(wrapper.stat().st_mode) == 0o755 + + # Symlink refusal on atomic write + unit_dir = fake_root / "etc/systemd/system" + unit_dir.mkdir(parents=True, exist_ok=True) + victim = tmp_path / "victim" + victim.write_text("untouched", encoding="utf-8") + (unit_dir / boot.UNIT_NAME).symlink_to(victim) + spec = boot.plan("topology", "facts", topology_text="hosts a b\n", facts_text="{}") + with pytest.raises(FabricError, match="symbolic link"): + boot.install(spec, root=str(fake_root), execute=False) + assert victim.read_text(encoding="utf-8") == "untouched" + + +def test_tool_path_validation_refuses_shared_and_relative_paths(): + import pytest + from fabric_tool.model import FabricError + + for bad in ("/tmp/evil", "/var/tmp/evil", "/dev/shm/evil", "relative/tool", "/usr/../tmp/evil", "//usr/bin/tool"): + with pytest.raises(FabricError, match="tool path"): + boot.RestoreInvocation(tool=bad) diff --git a/fabric-tool/tests/test_commands.py b/fabric-tool/tests/test_commands.py index b829459..4a87ce2 100644 --- a/fabric-tool/tests/test_commands.py +++ b/fabric-tool/tests/test_commands.py @@ -40,8 +40,9 @@ def test_command_forms(): "/var/lib/fabric-tool/logs/fabric-tool-marker-rocep1s0f0.log /usr/local/libexec/fabric-tool/fabric-tool-marker " "--device rocep1s0f0 --rule 192.0.2.10=0x88b5 --managed < /dev/null") stop, wait = commands.marker_stop(MARKER, 4100) - assert stop == '[ "$(cat /proc/4100/comm 2>/dev/null)" != fabric-tool-mar ] || sudo -n kill 4100' - assert wait.startswith("for i in $(seq 1 50)") + assert stop == ('! ( [ "$(stat -c %u /proc/4100 2>/dev/null)" = 0 ] && ' + '[ "$(cat /proc/4100/comm 2>/dev/null)" = fabric-tool-mar ] ) || sudo -n kill 4100') + assert wait.startswith("for i in $(seq 1 50)") and "kill -KILL 4100" in wait assert commands.record_remove() == "sudo -n rm -f /run/fabric-table/relay-state.json" @@ -125,14 +126,15 @@ def test_marker_build_script_installs_owned_by_root_and_records_the_digest(): script = commands.marker_build_script("node-0", MARKER, source) assert script.startswith("set -euo pipefail") lines = script.splitlines() - compile_at = lines.index('cc -O2 -Wall -Wextra "$work/mesh_marker.c" -o "$work/marker" -libverbs -lmlx5') - existing, make_dir, install, record, owners, digest, report = lines[compile_at + 1:] + compile_at = lines.index('cc -std=c11 -O2 -Wall -Wextra -Werror "$work/mesh_marker.c" -o "$work/marker" -libverbs -lmlx5') + existing, make_dir, install, hash_file, install_record, owners, digest, report = lines[compile_at + 1:] assert existing.startswith("for f in /usr/local/libexec/fabric-tool /usr/local/libexec /usr/local /usr /; " 'do [ -e "$f" ] || continue; case ') assert "refusing to install the marker" in existing assert make_dir == "sudo -n install -d -o root -g root -m 0755 /usr/local/libexec/fabric-tool" assert install == f'sudo -n install -o root -g root -m 0755 "$work/marker" {MARKER.path}' - assert record == f"sha256sum {MARKER.path} | sudo -n tee {MARKER.record} >/dev/null" + assert hash_file == f'sha256sum {MARKER.path} > "$work/marker.sha256"' + assert install_record == f'sudo -n install -o root -g root -m 0644 "$work/marker.sha256" {MARKER.record}' assert (owners, digest) == commands.marker_checks(MARKER, "install the marker") assert report == f"sha256sum {MARKER.path}" assert not any(line.startswith("install ") for line in lines) @@ -210,3 +212,26 @@ def test_the_marker_start_leaves_no_descriptor_of_the_caller_open(tmp_path): elapsed = time.monotonic() - began assert result.stdout.decode().strip() == "started" and not result.stderr assert elapsed < 3, f"the caller's output stayed open for {elapsed:.1f} s" + + +def test_atomic_record_write_under_bash(tmp_path): + import json + import stat + + bash = shutil.which("bash") + if bash is None: + pytest.skip("no bash on this host") + state_dir = tmp_path / "run-fabric" + record_path = state_dir / "relay-state.json" + mkdir_cmd, write_cmd = commands.record_write({"schema": commands.RECORD_SCHEMA, "qdiscs": ["enp1s0f0np0"]}) + stubs = 'sudo() { [ "$1" = -n ] && shift; "$@"; }\ninstall() { shift; mkdir -p "${@: -1}"; }\n' + script = (stubs + mkdir_cmd.replace(commands.STATE_DIR, str(state_dir)) + "\n" + + write_cmd.replace(commands.STATE_DIR, str(state_dir)).replace(commands.RECORD_PATH, str(record_path)) + + "\n") + res = subprocess.run([bash, "-euo", "pipefail", "-c", script], capture_output=True, text=True, timeout=10) + assert res.returncode == 0, res.stderr + assert json.loads(record_path.read_text(encoding="utf-8")) == { + "schema": commands.RECORD_SCHEMA, "qdiscs": ["enp1s0f0np0"] + } + assert stat.S_IMODE(record_path.stat().st_mode) == 0o644 + assert list(state_dir.iterdir()) == [record_path] diff --git a/fabric-tool/tests/test_marker_security.py b/fabric-tool/tests/test_marker_security.py index 85f1385..5a684a3 100644 --- a/fabric-tool/tests/test_marker_security.py +++ b/fabric-tool/tests/test_marker_security.py @@ -65,7 +65,7 @@ def test_missing_or_changed_digest_blocks_apply_and_selects_reinstall(environmen def install(target, script, timeout): installed.append(target) - assert f'sudo -n tee {MARKER.record}' in script + assert f'sudo -n install -o root -g root -m 0644 "$work/marker.sha256" {MARKER.record}' in script assert all(check in script for check in commands.marker_checks(MARKER, 'install the marker')) return ops.Result(0, '', '') diff --git a/fabric-tool/tests/test_operation_contracts.py b/fabric-tool/tests/test_operation_contracts.py index 799f04a..583927f 100644 --- a/fabric-tool/tests/test_operation_contracts.py +++ b/fabric-tool/tests/test_operation_contracts.py @@ -31,7 +31,7 @@ def test_plans_keep_their_bindings_after_other_configurations_are_resolved(): assert customized.bindings != ordinary.bindings -@pytest.mark.parametrize('operation', ['apply', 'verify']) +@pytest.mark.parametrize('operation', ['apply', 'verify', 'status', 'install-marker']) def test_custom_facts_are_bound_before_the_first_host_read(tmp_path, monkeypatch, operation): path = tmp_path / 'ring.topology' path.write_text(RING4) @@ -58,7 +58,7 @@ def test_boot_preserves_preexisting_qdisc_ownership(): for device in host.filter_netdevs: observed.ingress_qdisc[device] = 'ingress' restored = diff.compare_boot(observed, host, built, layout_name=topo.group.name, marker=marker, adopt=False) - record_line = next(line for line in restored.commands if 'tee ' + commands.RECORD_PATH in line) + record_line = next(line for line in restored.commands if commands.RECORD_PATH in line and "mv -f" in line) observed.record = json.loads(shlex.split(record_line)[2]) assert observed.record['qdiscs'] == [] removed = diff.compare_down(observed, group=topo.group.label, marker=marker, adopt=False) diff --git a/fabric-tool/tests/test_review_fixes.py b/fabric-tool/tests/test_review_fixes.py index 381af81..c21683a 100644 --- a/fabric-tool/tests/test_review_fixes.py +++ b/fabric-tool/tests/test_review_fixes.py @@ -131,7 +131,7 @@ def test_a_record_of_the_old_file_name_layout_converges_in_one_apply(): assert not outcome.blocked and outcome.host_changes == 0 for host_diff in outcome.diffs: assert [(c.kind, c.action) for c in host_diff.pending] == [("record", "write")] - line = next(line for line in host_diff.commands if "tee " + commands.RECORD_PATH in line) + line = next(line for line in host_diff.commands if commands.RECORD_PATH in line and "mv -f" in line) states[host_diff.position].record = json.loads(shlex.split(line)[2]) assert not evaluate(topo, states, bound, "up").pending @@ -254,13 +254,19 @@ def test_a_failed_read_is_a_problem_that_blocks_the_host(sections, expected): @pytest.mark.parametrize("sections", [ {}, {"exit_markers": "0", "markers": f"4100 {MARKER.path} --device rocep1s0f0 --rule 192.0.2.10=0x88b5 --managed"}, - {f"exit_qdisc_{NETDEVS[0]}": "1", f"exit_filters_{NETDEVS[0]}": "2"}, # tc's own failures are not judged - {f"exit_qdisc_{NETDEVS[0]}": "255"}, + {f"exit_filters_{NETDEVS[0]}": "2"}, # filter show may fail only when there is no ingress qdisc ]) def test_reads_that_legitimately_find_nothing_are_not_problems(sections): assert parsed(**sections).parse_problems == [] +def test_tc_qdisc_failure_and_filter_failure_with_ingress_qdisc_are_problems(): + qdisc_err = parsed(**{f"exit_qdisc_{NETDEVS[0]}": "1"}) + assert any(f"tc -j qdisc show dev {NETDEVS[0]} failed with exit status 1" in p for p in qdisc_err.parse_problems) + filter_err = parsed(**{f"qdisc_{NETDEVS[0]}": '[{"kind":"ingress"}]', f"exit_filters_{NETDEVS[0]}": "2"}) + assert any(f"tc -j filter show dev {NETDEVS[0]} ingress failed with exit status 2" in p for p in filter_err.parse_problems) + + @pytest.mark.parametrize("command", ["remove", "verify", "apply"]) def test_cli_refuses_hosts_whose_tc_cannot_run(tmp_path, capsys, command): path = tmp_path / "ring.topology" @@ -314,8 +320,9 @@ def test_the_read_script_under_bash_reports_failed_reads(stub, expected): assert any(text in problem for problem in host.parse_problems), host.parse_problems -def test_the_read_script_under_bash_does_not_judge_other_tc_failures(): - assert run_read_script("tc() { return 2; }\n").parse_problems == [] +def test_the_read_script_under_bash_propagates_tc_qdisc_failures(): + problems = run_read_script("tc() { return 2; }\n").parse_problems + assert any("tc -j qdisc show dev" in p and "failed with exit status 2" in p for p in problems) # -- 5. restore keeps marker processes the plan does not name ------------------------------------------ @@ -421,7 +428,8 @@ def boot_install(environment, tmp_path, monkeypatch): # noqa: F811 facts.write_text(json.dumps(_document())) calls = [] monkeypatch.setattr(cli.subprocess, "run", lambda argv, **kwargs: calls.append((argv, kwargs))) - monkeypatch.setattr(cli.shutil, "copytree", lambda *args, **kwargs: None) + monkeypatch.setattr(boot, "install_package", lambda source, root="/": (Path(boot.LIB_DIR), Path(boot.BIN_PATH))) + monkeypatch.setattr(boot, "check_root_owned_path", lambda path, existing_only=False: None) monkeypatch.setattr(boot, "install", lambda spec, root, execute: []) monkeypatch.setattr(boot, "stop_reconciliation", lambda: None) monkeypatch.setattr(boot, "LIB_DIR", str(Path(cli.__file__).resolve().parents[1])) @@ -490,7 +498,7 @@ def systemctl(argv, **kwargs): def record_writes(lines): return [(index, json.loads(shlex.split(line)[2])) for index, line in enumerate(lines) - if "tee " + commands.RECORD_PATH in line] + if commands.RECORD_PATH in line and "mv -f" in line] def test_a_failed_apply_keeps_the_ownership_of_the_qdiscs_it_added(): @@ -504,7 +512,7 @@ def test_a_failed_apply_keeps_the_ownership_of_the_qdiscs_it_added(): assert len(adds) == 4 and len(writes) == 1 assert writes[0][0] < min(adds), "the record must be written before the first qdisc is added" assert writes[0][1]["qdiscs"] == sorted(host.filter_netdevs) - assert first.commands[writes[0][0] - 1].startswith("sudo -n mkdir -p ") + assert first.commands[writes[0][0] - 1].startswith("sudo -n install -d ") assert first.commands[1] == commands.guard(host.name) # The script stopped after the qdiscs: the rerun still owns them, and so does a removal. stopped = state.HostState(1, host.name, "", True, hostname=host.name, record=writes[0][1]) @@ -550,7 +558,7 @@ def test_a_recorded_qdisc_outside_the_bindings_is_noted_not_a_crash(): for mode in ("up", "down"): result = evaluate(topo, states, bound, mode).diffs[0] assert any("ingress qdisc on fabric0" in note for note in result.notes) - assert not any("fabric0" in line and "qdisc" in line and "tee" not in line for line in result.commands) + assert not any("fabric0" in line and "qdisc" in line and commands.RECORD_PATH not in line for line in result.commands) def test_remove_without_facts_refuses_hosts_with_other_interface_names(tmp_path, monkeypatch, capsys): diff --git a/fabric-tool/tests/test_topology.py b/fabric-tool/tests/test_topology.py index 13aa989..c65dafe 100644 --- a/fabric-tool/tests/test_topology.py +++ b/fabric-tool/tests/test_topology.py @@ -72,10 +72,16 @@ def test_host_count_name_length_and_budget_limits_match_the_plugin(): topology.parse(f"hosts {'a' * 64} b\ncabling path\n") with pytest.raises(FabricError, match="longer than 63 bytes"): topology.parse(f"hosts {'é' * 32} b\ncabling path\n") # 32 characters, 64 bytes - assert topology.parse("hosts a b\ncabling path\nrelay_budget 0123\n").budget == 123 - for budget in ("١٢٣", "²", "+5", "1_0", "0x10"): # digits to Python, not to the plugin + for bad_host in ("bad/host", "bad;host", "$bad", "-lead"): + with pytest.raises(FabricError, match="invalid host name"): + topology.parse(f"hosts a {bad_host}\ncabling path\n") + assert topology.parse("hosts a b\ncabling path\nrelay_budget 065536\n").budget == 65536 + for budget in ("١٢٣", "²", "+65536", "65_536", "0x10000", "1", "65535", "393217", "999999999999"): with pytest.raises(FabricError, match="positive byte count"): topology.parse(f"hosts a b\ncabling path\nrelay_budget {budget}\n") + # Overwritten invalid port0 line must still be rejected immediately on parse. + with pytest.raises(FabricError, match="invalid device identifier"): + topology.parse("hosts a b\ncabling path\nport0 bad/name ok\nport0 mlx5_0 mlx5_1\n") def test_layout_name_follows_the_content_not_the_file(): @@ -85,7 +91,7 @@ def test_layout_name_follows_the_content_not_the_file(): assert topology.parse(RING4, path="/etc/fabric-table/topology").layout_name == ring.layout_name spelled = topology.parse("hosts node-0 node-1 node-2 node-3\ncabling explicit\n# the same cables\n" "cable 0.port1 3.port0\ncable 2.port0 3.port1\n" - "cable 1.port0 2.port1\ncable 0.port0 1.port1\nrelay_budget 4096\n") + "cable 1.port0 2.port1\ncable 0.port0 1.port1\nrelay_budget 65536\n") assert spelled.layout_name == ring.layout_name assert topology.parse(PATH4).layout_name != topology.parse(RING4.replace("node-3", "node-9")).layout_name assert topology.parse(RING4 + "port0 mlx5_0 mlx5_2\n").layout_name != ring.layout_name diff --git a/fabric-tool/tests/test_verify_loss.py b/fabric-tool/tests/test_verify_loss.py index e795fcc..27a8ec7 100644 --- a/fabric-tool/tests/test_verify_loss.py +++ b/fabric-tool/tests/test_verify_loss.py @@ -93,3 +93,36 @@ def test_unreachable_relay_fails_verify(installed): states[1].reachable = False states[1].error = "synthetic read timeout" assert verify() == 3 + + +def test_check_lane_routes_rejects_gateway_via_and_wrong_src(tmp_path): + text = "hosts node-0 node-1 node-2 node-3\ncabling path\n" + topo = topology.parse(text) + bound = facts.bind(_document(), topo) + built = plan.build_plan(topo.group, bound) + marker = commands.MarkerConfig() + observed = {} + for host in built.hosts: + s = state.HostState(host.position, host.name, host.name, True, hostname=host.name) + for device, fn in _document()["hosts"][host.position]["functions"].items(): + addr = ipaddress.ip_interface(fn["address"]) + s.rdma[device] = fn["netdev"] + s.links[fn["netdev"]] = state.Link(fn["netdev"], fn["mac"], ((str(addr.ip), addr.network.prefixlen),), "UP") + observed[host.position] = s + outcome = ops.evaluate(topo, observed, bound, mode="up", marker=marker, adopt=False) + checks = ops.lane_route_checks(outcome, installed_only=False) + hosts = {p: ops.HostTarget(topo.hosts[p], topo.hosts[p]) for p in checks} + # Gateway via on same netdev must be flagged + def via_exec(target, script, timeout): + pos = int(target.split("-")[-1]) + return ops.Result(0, "".join(f"@@route:{dst}\n{dst} via 192.0.2.254 dev {dev}\n" + for dst, dev in checks[pos].items()), "") + problems = ops.check_lane_routes(hosts, outcome, via_exec, installed_only=False) + assert problems and all("via gateway" in msg for msgs in problems.values() for msg in msgs) + # Wrong src IP on same netdev must be flagged + def src_exec(target, script, timeout): + pos = int(target.split("-")[-1]) + return ops.Result(0, "".join(f"@@route:{dst}\n{dst} dev {dev} src 198.51.100.250\n" + for dst, dev in checks[pos].items()), "") + problems = ops.check_lane_routes(hosts, outcome, src_exec, installed_only=False) + assert problems and all("uses src 198.51.100.250" in msg for msgs in problems.values() for msg in msgs) diff --git a/tests/test_topology_conformance.py b/tests/test_topology_conformance.py index 357330f..637411c 100644 --- a/tests/test_topology_conformance.py +++ b/tests/test_topology_conformance.py @@ -101,6 +101,9 @@ def valid_corpus(): yield "explicit cables in any order", explicit(4, [(2, 0, 3, 1), (0, 0, 1, 1), (1, 0, 2, 1)]) yield "longest host name", f"hosts a {'h' * 63}\ncabling path\n" yield "sixteen hosts", f"hosts {' '.join(f'h{i}' for i in range(16))}\ncabling ring\n" + yield "sixty-four long host names on one line (>1022 bytes)", ( + f"hosts {' '.join(f'node-longname-host-{i:02d}' for i in range(64))}\ncabling ring\n" + ) def invalid_corpus(): @@ -134,7 +137,15 @@ def invalid_corpus(): yield "budget with a sign", "hosts a b\ncabling path\nrelay_budget +65536\n" yield "budget in hexadecimal", "hosts a b\ncabling path\nrelay_budget 0x10000\n" yield "budget of zero", "hosts a b\ncabling path\nrelay_budget 0\n" + yield "budget below minimum", "hosts a b\ncabling path\nrelay_budget 65535\n" + yield "budget above maximum", "hosts a b\ncabling path\nrelay_budget 393217\n" + yield "budget huge overflow", "hosts a b\ncabling path\nrelay_budget 999999999999\n" yield "budget with two words", "hosts a b\ncabling path\nrelay_budget 65536 65536\n" + yield "overwritten invalid port0", "hosts a b\ncabling path\nport0 bad/name ok\nport0 mlx5_0 mlx5_1\n" + yield "host name with slash", "hosts a bad/host\ncabling path\n" + yield "host name with semicolon", "hosts a bad;host\ncabling path\n" + yield "host name with dollar", "hosts a $bad\ncabling path\n" + yield "host name leading dash", "hosts a -bad\ncabling path\n" yield "words after the header key", "hosts a b\ncabling path\nnet-sircl-topology 2\n" yield "host name too long", f"hosts a {'h' * 64}\ncabling path\n" yield "too many hosts", f"hosts {' '.join(f'h{i}' for i in range(65))}\ncabling ring\n" From 0c3985338ad9fd62aaf55d1d209604418d8dd4ca Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:32:08 -0600 Subject: [PATCH 4/4] ci/packaging: add ASan+UBSan lane, preserve +x & versioned root dir in archive, update SOURCE.json (P1-7) --- .github/workflows/ci.yml | 30 ++++++++++++++++++++----- Makefile | 4 ++-- SOURCE.json | 40 ++++++++++++++++----------------- examples/ring4-two-hca.topology | 2 +- tests/test_release.py | 23 ++++++++++++++----- transport-core/tools/package.py | 33 +++++++++++++++++++-------- 6 files changed, 88 insertions(+), 44 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c73e476..c37d61d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,12 +28,32 @@ jobs: run: make package - name: Build and test extracted source archive run: | - mkdir "$RUNNER_TEMP/net-sircl-source" - tar -xzf dist/net-sircl-0.1.3.tar.gz -C "$RUNNER_TEMP/net-sircl-source" - python3 scripts/check_release_safety.py --tree "$RUNNER_TEMP/net-sircl-source" - make -C "$RUNNER_TEMP/net-sircl-source" -j2 all emu - make -C "$RUNNER_TEMP/net-sircl-source" check + VERSION="$(cat net-sircl/VERSION)" + tar -xzf "dist/net-sircl-${VERSION}.tar.gz" -C "$RUNNER_TEMP" + SRC="$RUNNER_TEMP/net-sircl-${VERSION}" + test -x "$SRC/fabric-tool/fabric-tool" + python3 scripts/check_release_safety.py --tree "$SRC" + make -C "$SRC" -j2 all emu + make -C "$SRC" check - name: Check installed fabric entry point run: | make install DESTDIR="$RUNNER_TEMP/net-sircl-stage" PREFIX=/opt/net-sircl + test -x "$RUNNER_TEMP/net-sircl-stage/opt/net-sircl/libexec/fabric-tool/fabric-tool-marker" "$RUNNER_TEMP/net-sircl-stage/opt/net-sircl/bin/fabric-tool" --topology examples/path4.topology --json + sanitizers: + name: ASan + UBSan (ubuntu-24.04) + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - name: Install build dependencies + run: sudo apt-get update && sudo apt-get install -y build-essential python3 python3-pytest libibverbs-dev + - name: Run transport-core checks with ASan + UBSan + run: | + make -C transport-core clean check CFLAGS='-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer' + - name: Run net-sircl checks with ASan + UBSan + run: | + NET_SIRCL_TEST_EXTRA_CFLAGS='-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer' make -C net-sircl check + - name: Build fabric-tool marker with ASan + UBSan + run: | + make -C fabric-tool clean all CFLAGS='-std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-omit-frame-pointer' diff --git a/Makefile b/Makefile index fd70129..9a680ad 100644 --- a/Makefile +++ b/Makefile @@ -25,11 +25,11 @@ check-teardown: emu install: $(MAKE) -C net-sircl install PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) $(MAKE) -C fabric-tool install PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) + install -d $(DESTDIR)$(PREFIX)/share/doc/net-sircl/net-sircl + install -m 0644 net-sircl/README.md $(DESTDIR)$(PREFIX)/share/doc/net-sircl/net-sircl/README.md install -m 0644 README.md $(DESTDIR)$(PREFIX)/share/doc/net-sircl/README.md install -m 0644 NOTICE $(DESTDIR)$(PREFIX)/share/doc/net-sircl/NOTICE install -m 0644 RELEASE_NOTES-*.md $(DESTDIR)$(PREFIX)/share/doc/net-sircl/ - install -d $(DESTDIR)$(PREFIX)/share/doc/net-sircl/net-sircl - install -m 0644 net-sircl/ROUTE-ALLOWANCE.md net-sircl/PROFILING.md $(DESTDIR)$(PREFIX)/share/doc/net-sircl/net-sircl/ install -m 0644 SOURCE.json $(DESTDIR)$(PREFIX)/share/doc/net-sircl/SOURCE.json install -d $(DESTDIR)$(PREFIX)/share/doc/net-sircl/docs $(DESTDIR)$(PREFIX)/share/net-sircl/examples install -m 0644 docs/*.md $(DESTDIR)$(PREFIX)/share/doc/net-sircl/docs/ diff --git a/SOURCE.json b/SOURCE.json index a3626fe..36c9d97 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -120,7 +120,7 @@ "0.1.3 separates transport deadlines from waits for the peer application, validates every setting, parses topology files strictly, supports single-function-per-port topologies and shares that grammar with fabric-tool; wire remains 6; CPU-tested only." ], "source_sha256": { - "fabric-tool/mesh_marker.c": "5f330fba6e4c6c2e49d158b84fd76ef0c2ed710354753742503c09262b9c6d4a", + "fabric-tool/mesh_marker.c": "253761b88bccd9f96c38995b61eb21c4ad9268387087815c69496bb136b89426", "net-sircl/nccl/common.h": "60d138a9f2eb836161b2d0040901d38de5d28f7257b32f8b2d8b7f4e3935b0d1", "net-sircl/nccl/err.h": "aefbbb8f53d56b67c87bf84b8ea5a80ea0e8950d950eb6d66bb128975c90fb6b", "net-sircl/nccl/gin_v11.h": "77b7aae7fc0bdfb6eb1f87d339c11bd82a484b188ef249ebf32b87e5a2fa38cb", @@ -140,52 +140,50 @@ "net-sircl/nccl/tuner.h": "8450583204696fe008b01ab92cfc86d5e8e5bfe1b722b02360be58d599f00148", "net-sircl/nccl/tuner_v4.h": "1164e13f7096c21c3c02fda1ddcb13d52a9d74e89a42cbf287ac74710861c9cd", "net-sircl/nccl/types.h": "204015ef7865117da6d643307d81df8f16736ccde3762e5110de516b34983890", - "net-sircl/net_sircl.c": "831c257c6f029e0fbfae31988d3230969d5fd732fb5ef4f3f0c4f6fccc723135", + "net-sircl/net_sircl.c": "7c09afb446107da38647de0bb0503393432bb9d7f752037524a72f56be4909a8", "net-sircl/net_sircl.h": "de03b0ae808c101c2a3acc1dc7361b78eaf3d6baefa94f21af97723cb4a978d1", - "net-sircl/net_sircl_admission.h": "6e92a7e07863fc7667f1db549ac89761a34a4a372388497915fb6c362fea1409", - "net-sircl/net_sircl_compat.h": "0053800750c2f061a1254d1db95e65e4317de000c1b52873c0fe2cec9afafdf9", - "net-sircl/net_sircl_config.h": "5e4f8396caf08e3ebcc1a32e9a0d5d6952715407fdf301c0a1dde48ccea80243", - "net-sircl/net_sircl_connection.h": "901f799e6964445294f2a5fbca0413419d601f8a0cd5bde59f948a8650cff067", - "net-sircl/net_sircl_plan.c": "27a9eac56ad81695b3f17fcebd63208997094516eadf1d40c69d77345b6e5011", + "net-sircl/net_sircl_admission.h": "fad9491e0dea9cb20161a1c73a57a55ab26941f3e315a5b77ac579b5e9ab4238", + "net-sircl/net_sircl_compat.h": "e4b9acc9d65847106c8ee0095a5a7e3dd0d61184a0b143ce6bc84741176dc532", + "net-sircl/net_sircl_config.h": "b1db7bcbedd845edab2bab464e3b6a6a6ea9ca346aaee1f82bc6a49dca489b4a", + "net-sircl/net_sircl_connection.h": "3e7bbb047632a39fd5e4886b4b3056a2574365cf141a165b6352e7a3b4603b0b", + "net-sircl/net_sircl_plan.c": "98821052079dd5a938c07d4460de7031af85935b8b6b4a011e2e0fab92cbe359", "net-sircl/net_sircl_plan.h": "dcb857dce8247ff61756e216e90cfd40c6ce3a2b24f5e990b39ec561d2169526", - "net-sircl/net_sircl_profile.h": "58b2d994f86fbc88fba4b4d90f332142c52610fcb069dbb2990356734ac076fe", + "net-sircl/net_sircl_profile.h": "4d0e2562c56ccd1df354b2bab6978723a9095599e2fb5152f00288c4c0a3eb27", "net-sircl/net_sircl_tuner.h": "30190717119d61bf1f25b184b1b1ad8f661ac8915c888e55ae013bff2a344bf1", "net-sircl/tests/abi_test.c": "6bc4f44a4cec8f95253ccdf3e3980ced419f01b6be5e41f7e7d1718714e4d91a", "net-sircl/tests/ack_test.c": "ba53451731662b8398c7e4dfd6ccab2008004e0343b1fd25f5fa8884599c6430", "net-sircl/tests/emulation/nccl_compat_e2e.cc": "87217f46e6b83c65e9630b1df1b8f54ac4595e27cb3086e95c12ddc1765568d5", "net-sircl/tests/failure_test.c": "040d98cb2803723a56b3f2534d5a228e3b51fdc19f59e4f526a75829d7208a82", - "net-sircl/tests/layer_test.c": "1d31ac5e27aaddbaeffab39d057665474c8e875f167c3ffe2752edbaa315c5c7", + "net-sircl/tests/layer_test.c": "942f9d275f3fd50b039322a47dc8965e00d401fc1b82e5c5dee45ff9964e56de", "net-sircl/tests/progress_cost_test.c": "b3d26360da2c4df8a5d63ad4e62672462c6ebff15b06d1c79e7887cc128f5fa0", - "net-sircl/tests/relay_test.c": "651da26961b317e7189c27204f99c06cd7319b4d051cbe4677d69d95dfc7c13a", - "net-sircl/tests/request_contract_test.c": "3881b1f0ca107b600fb29a2b43478b687571a20b0495255cc3c635233d69c500", + "net-sircl/tests/relay_test.c": "23a282892ae39c99055f4471956608bfeac3c68473a9b632cb16955a3d1237d5", + "net-sircl/tests/request_contract_test.c": "6b2ffa13da3bb5f5fca053946100b0e8bf315e9403e9e1efa53c398f820b0972", "net-sircl/tests/route_model.c": "b365917435b11477b0e722e6df1bdcc2ddba427a847b02073b91eaa3f3bd76d2", - "net-sircl/tests/settings_test.c": "07b5ff68bc0919c456d56281c49af18c4f2bacf974846b77ca18c7044c1159a2", + "net-sircl/tests/settings_test.c": "90218e3427d78a73fd420bccfe6e6890be76f2e03de3176300e1bad3f2dd7632", "net-sircl/tests/standin/fake_verbs/infiniband/verbs.h": "8c2173547a2169bb455d103b7842463168e75d4350f4434d92ab5dabc353c64c", "net-sircl/tests/standin/proxy_names.h": "962f0623b88648d1f8bc683168d0befd25dfe5dd7fe4c48a6f69b1e168b1964a", "net-sircl/tests/standin/shm_verbs.c": "3921790d413212dee23f906a2abc897ff2367c27ac910d521174cf8c077b66a2", "net-sircl/tests/standin/shm_verbs.h": "53f1b6b16e26f807875bc1020f76764acae3bdcff26356eed6900f169be5bd63", "net-sircl/tests/topology_progress_test.c": "f0bcd956edfc4cfa3bfd339f34a7c7f580256da315d6d8b592b0d0a24c52af02", - "transport-core/include/sircl_core/core.h": "07ef70851ac78bedb98f61522cdcb697971f98cfbf36df83899c5215d8537753", + "transport-core/include/sircl_core/core.h": "17586a64b04b5174106e1f97eac7bb3750abe32f2b1d69c6b09c8b28dcc3f762", "transport-core/include/sircl_core/emulation_verbs.h": "4492551757c091045ac75150585a645f4f5682402e8cd4564d5116d31d0de3da", "transport-core/include/sircl_core/legacy_proxy_names.h": "94e302cb90785a3394ab3c1ca7cd454fbead8767e0fa7ad3d6e072afcf9db7f3", "transport-core/include/sircl_core/shm_verbs.c": "27ac4ea05c5e15185fcf51106895655a9b34a08913232a664448f7fe2db70d15", "transport-core/include/sircl_core/shm_verbs.h": "9ecdd4dc59aa1b17b7d1a9790901f73541ab9112831971de762d3189ee7fe085", - "transport-core/include/sircl_core/verbs.h": "8ccc714b80220e54c868e59c7fc4034cac2afe3b8c23cc872ae52d2141e3b0f1", + "transport-core/include/sircl_core/verbs.h": "af6ea6391d044272defe0284dfa45e7b3824e4b49920d17993a615b4f9dc2152", "transport-core/include/sircl_core/verbs_dl.c": "917eb77893adad8a62c053146ca8954d567b8e037a987a20a8e8393ac1f5f4eb", - "transport-core/include/sircl_fabric.h": "5960d6fe55fba8c8f32a00bf747aecfd3a4b018db8248ce5134f75bd95843ebb", "transport-core/src/core.c": "3d32d0d6d58a2874573a3ba1ea1efddb5a96cbfc45b2bfd89e451fbd952549ef", "transport-core/src/emulation_limits.h": "e7bc515560b9c1b0610279dd3ed6c0be9d3a3f248246e245299cc78db6017693", - "transport-core/src/fabric.c": "edc6a98d8a8e1524ea502fade00b07467b57f299911ea8642b74a479497465b9", "transport-core/src/shm_memory.c": "4fcd9767b2e999d363b78100e360a84d9054edf4b65d3177db96cd4e9e263d4c", "transport-core/src/shm_memory.h": "defe5e56c0162f2c2ce3d7484693b2771bf0afb953f8a9994ba8ebe5e4f1e01b", - "transport-core/src/shm_verbs.c": "2bc7a33b4e492c1ab0ee25de3527695420ce7ddde4bd4b9b5128874093a1686b", - "transport-core/src/sysfs.c": "747062778a2cab1744d43e602c724b1887ad6ba66428d62ee892b351f7f5b7c2", - "transport-core/src/topology.c": "c0a61fd97072a7114bf39890055b8d17dff891ce3930d2970faaa4fcc4200832", + "transport-core/src/shm_verbs.c": "a9884723b77c0dd175ac59971300c5d54e22c39fb8d82c09c0eafc7f826c2178", + "transport-core/src/sysfs.c": "e7e238e98df0db59b2c762584acb0f00f738d258553ed6ba24fea815d619cc68", + "transport-core/src/topology.c": "a4d2cd0440f86d06a211270ba5ea9c3e3f3a8f923ddb139fd6d155af69585add", "transport-core/src/verbs_dl.c": "ea38fd0ef71bc215f8d97c4f836179aa9190dc87a34125a4a24a96e23bbc4d84", "transport-core/tests/fake_verbs/infiniband/verbs.h": "8c2173547a2169bb455d103b7842463168e75d4350f4434d92ab5dabc353c64c", "transport-core/tests/test_core.c": "af50eedb132df536ab1a4700b9513d7a0d101ec9d26049a9ae6466c89ceb2218", - "transport-core/tests/test_emulator_lifetime.c": "9a6b273b84cee7da73ec12eb03759098e11103bb461af02b5af6dd03311c0506", - "transport-core/tests/test_verbs.c": "ec84a8971e48c2fd098dc06d630733af2a5f21c6cd6e9eaa89dca67a9871c220" + "transport-core/tests/test_emulator_lifetime.c": "cd27e54f8b8cbda90d379965d1869fc6f9dc91d28789ba8316aec6900683ce6b", + "transport-core/tests/test_verbs.c": "161c408383b2cc498bf9025f62a41091ff797b7f0950601474dc95e4dd9a3be7" }, "upstream_source_sha256": { "net-sircl/nccl/common.h": "60d138a9f2eb836161b2d0040901d38de5d28f7257b32f8b2d8b7f4e3935b0d1", diff --git a/examples/ring4-two-hca.topology b/examples/ring4-two-hca.topology index 4243952..f5b5326 100644 --- a/examples/ring4-two-hca.topology +++ b/examples/ring4-two-hca.topology @@ -1,7 +1,7 @@ net-sircl-topology # Four hosts in a ring with one RDMA function per physical port (two HCAs per host). # Port 0 of host i is cabled to port 1 of host (i + 1) mod 4. -hosts spark1 spark2 spark3 spark4 +hosts node-0 node-1 node-2 node-3 cabling ring port0 rocep1s0f0 port1 rocep1s0f1 diff --git a/tests/test_release.py b/tests/test_release.py index dd55457..1f3b0d2 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -34,19 +34,24 @@ def test_archive_reproducible_and_complete(self): subprocess.run([sys.executable, str(ROOT / "transport-core/tools/package.py"), "--output", str(path)], check=True) self.assertEqual(archives[0].read_bytes(), archives[1].read_bytes()) + version = (ROOT / "net-sircl/VERSION").read_text().strip() + prefix = f"net-sircl-{version}/" with tarfile.open(archives[0]) as archive: members = archive.getmembers() - names = {m.name for m in members} + raw_names = {m.name for m in members} + self.assertEqual(len(raw_names), len(members)) + for member in members: + self.assertTrue(member.name.startswith(prefix), f"missing versioned root dir: {member.name}") + names = {m.name[len(prefix):] for m in members} tracked = set(filter(None, subprocess.check_output( ["git", "ls-files", "-z"], cwd=ROOT).decode().split("\0"))) self.assertEqual(names, tracked) - self.assertEqual(len(names), len(members)) for required in ("README.md", "LICENSE", "NOTICE", "Makefile", "SOURCE.json", "examples/pair.topology", "examples/ring4-two-hca.topology", ".github/workflows/ci.yml", "net-sircl/nccl/LICENSE.txt", "docs/transport-core.md", "RELEASE_NOTES-0.1.1.md", "RELEASE_NOTES-0.1.2.md", "RELEASE_NOTES-0.1.3.md", - "net-sircl/ROUTE-ALLOWANCE.md", + "net-sircl/ROUTE-ALLOWANCE.md", "net-sircl/net_sircl.map", "net-sircl/net_sircl_tuner.h", "net-sircl/nccl/tuner_v4.h", "examples/torch_teardown.py", "scripts/check_teardown.py", "scripts/check_channels.py", "scripts/check_compat.py", @@ -57,11 +62,15 @@ def test_archive_reproducible_and_complete(self): "fabric-tool/mesh_marker.c", "fabric-tool/fabric_tool/cli.py", "fabric-tool/fabric-tool", "fabric-tool/tests/test_plan.py"): self.assertIn(required, names) + modes = {m.name[len(prefix):]: m.mode for m in members} + self.assertEqual(modes["fabric-tool/fabric-tool"], 0o755) + self.assertEqual(modes["README.md"], 0o644) for member in members: + rel = member.name[len(prefix):] self.assertTrue(member.isfile()) self.assertNotIn("..", Path(member.name).parts) - self.assertFalse(set(Path(member.name).parts) & {".git", "build", ".core-build", "dist", "test-results"}) - self.assertEqual(archive.extractfile(member).read(), (ROOT / member.name).read_bytes()) + self.assertFalse(set(Path(rel).parts) & {".git", "build", ".core-build", "dist", "test-results"}) + self.assertEqual(archive.extractfile(member).read(), (ROOT / rel).read_bytes()) self.assertEqual(member.mtime, 0) def test_version_strings_agree(self): @@ -82,7 +91,9 @@ def test_version_strings_agree(self): self.assertIn(f"Version **{fabric}**", (ROOT / "fabric-tool/README.md").read_text()) self.assertIn(f"Version {core}, ABI", (ROOT / "transport-core/README.md").read_text()) self.assertTrue((ROOT / f"RELEASE_NOTES-{plugin}.md").is_file()) - self.assertIn(f"dist/net-sircl-{plugin}.tar.gz", (ROOT / ".github/workflows/ci.yml").read_text()) + ci_text = (ROOT / ".github/workflows/ci.yml").read_text() + self.assertIn('VERSION="$(cat net-sircl/VERSION)"', ci_text) + self.assertIn('dist/net-sircl-${VERSION}.tar.gz', ci_text) def test_release_identity_is_built_in(self): subprocess.run(["make", "-C", str(ROOT / "net-sircl"), "emu"], check=True) diff --git a/transport-core/tools/package.py b/transport-core/tools/package.py index 7823832..90afe68 100644 --- a/transport-core/tools/package.py +++ b/transport-core/tools/package.py @@ -13,10 +13,19 @@ def tracked_files(): # Refuse a parent checkout when invoked from an extracted archive. if not (ROOT / ".git").exists(): raise ValueError("source packaging requires this repository's Git checkout") - names = subprocess.check_output( - ["git", "ls-files", "--cached", "-z"], cwd=ROOT).decode("utf-8").split("\0") + entries = subprocess.check_output( + ["git", "ls-files", "--stage", "-z"], cwd=ROOT).decode("utf-8").split("\0") files = [] - for name in sorted(set(filter(None, names))): + seen = set() + for entry in entries: + if not entry: + continue + meta, _, name = entry.partition("\t") + if not name or name in seen: + continue + seen.add(name) + git_mode = meta.split(" ", 1)[0] + mode = 0o755 if git_mode == "100755" else 0o644 path = ROOT / name if (path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(ROOT)): @@ -25,29 +34,35 @@ def tracked_files(): or name == "scripts/config/site-values.txt" or path.suffix in {".so", ".o", ".a", ".d", ".pyc"}): raise ValueError(f"generated or private file must not be tracked: {name}") - files.append((name, path)) - return files + files.append((name, path, mode)) + return sorted(files, key=lambda item: item[0]) def main(): + version = (ROOT / "net-sircl" / "VERSION").read_text(encoding="utf-8").strip() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path, help="output .tar.gz source archive") + parser.add_argument("--prefix", default=f"net-sircl-{version}", + help=f"top-level directory inside archive (default net-sircl-{version})") args = parser.parse_args() try: members = tracked_files() except (OSError, ValueError, subprocess.SubprocessError) as exc: parser.error(str(exc)) - if args.output.resolve() in {path.resolve() for _, path in members}: + if args.output.resolve() in {path.resolve() for _, path, _ in members}: parser.error("output must not overwrite a tracked source file") + prefix = args.prefix.strip("/") + if not prefix or "/" in prefix or prefix in (".", ".."): + parser.error("prefix must be a single clean directory name") args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open("wb") as raw, gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as compressed: with tarfile.open(fileobj=compressed, mode="w") as archive: - for name, path in members: - info = archive.gettarinfo(str(path), name) + for name, path, mode in members: + info = archive.gettarinfo(str(path), f"{prefix}/{name}") info.uid = info.gid = 0 info.uname = info.gname = "" info.mtime = 0 - info.mode = 0o644 + info.mode = mode with path.open("rb") as source: archive.addfile(info, source) print(args.output)