1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Remote memory access (RMA) plumbing on the UCX progress thread.
//!
//! [`RdmaEndpoint`] is the cheap-clone handle the rest of the crate uses to
//! register memory and to pull remote memory with `ucp_get_nbx`. It carries no
//! UCX state: every `ucp_*` handle (`ucp_mem_h`, `ucp_rkey_h`) is created,
//! used and destroyed inside [`worker`](super::worker), which owns the single
//! `UCS_THREAD_MODE_SINGLE` worker. What crosses this boundary is a region id,
//! a byte range, and a *packed* rkey as plain [`Bytes`].
//!
//! ## Submission path
//!
//! Commands ride the progress thread's existing bounded ring
//! (`send_async` + [`Doorbell::ring`](super::worker::Doorbell::ring)) and are
//! answered by a `oneshot`. They deliberately do **not** go through
//! `Transport::send_message` or an `AdmissionGate`: those implement Active
//! Message frame semantics (eager caps, drain rejection, `SendOutcome`) which
//! have nothing to say about an RMA operation. The bounded ring is the
//! backpressure mechanism, exactly as for `check_health`.
//!
//! ## Why the not-started and shutting-down checks come first
//!
//! Before `Transport::start` the ring exists but has no consumer, so a push
//! *succeeds* and the reply oneshot is never resolved — a hang, not an error.
//! After `shutdown()` the receiver is dropped, which does surface as an error,
//! but only once the drop has happened. Both states are therefore checked
//! before the push, so every method resolves promptly with a diagnosis.
//!
//! ## Offsets are relative to the pointer the caller mapped
//!
//! `ucp_mem_map` rounds the pinned range outward to page boundaries, so the
//! range `ucp_mem_query` reports can start below and end above the caller's
//! allocation. [`MappedRegion`] reports that effective range as a fact, but
//! [`RmaGetRequest::local_offset`] is measured from the pointer passed to
//! [`RdmaEndpoint::map_region`] and bounds-checked against that length. A
//! caller can therefore never name a byte inside the registration but outside
//! its own allocation, which would be a silent write into unrelated heap.
//!
//! ## Cancellation
//!
//! Every method here is a future the caller may drop (a `select!` arm, a
//! `timeout`). Dropping one must never orphan a pinned region — the caller that
//! saw a failure is entitled by [`map_region`](RdmaEndpoint::map_region)'s own
//! contract to free the buffer, and freeing memory UCX still has pinned is the
//! whole hazard class this module exists to contain. So:
//!
//! * **`map_region`** — the region id is minted *before* the push, so a dropped
//! future can compensate: a `Drop` guard pushes an [`Cmd::UnmapRegion`] for
//! that id. The progress thread independently rolls back when it finds the
//! reply channel already closed at send time. Between them, cancelling
//! `map_region` means "no region exists", with a full ring the only gap.
//! * **`unmap_region`** — idempotent and fire-and-forget once pushed: the
//! progress thread performs the unmap whether or not anyone is still waiting,
//! and a repeat call for an id that is already gone answers `Ok(())`. The
//! advisory range entry is dropped the moment the command is *enqueued*, not
//! before: a future cancelled before the push completes leaves the region
//! mapped and retryable, and once enqueued the id stops gating regardless.
//! * **`get`** — dropping it abandons only the notification. The operation keeps
//! running and keeps the region's in-flight count raised, which is exactly
//! what stops the destination being unmapped underneath UCX.
use ;
use ;
use Bytes;
use DashMap;
use InstanceId;
use ;
/// Largest packed rkey this side will accept.
///
/// Bounds the copy and the pre-parse loop. Descriptors are velo-authored and a
/// real packed rkey is tens of bytes even with several memory domains, so a blob
/// past this size is malformed by definition.
pub const MAX_PACKED_RKEY: usize = 1024;
/// Slack in the buffer `prepare_get` unpacks from, filled with `0xFF`.
///
/// Belt-and-braces only — [`preparse_packed_rkey`] is the containment. See its
/// docs for why a length bound cannot be one, and why the filler is `0xFF`
/// rather than zero.
pub const RKEY_UNPACK_PAD: usize = 512;
/// `UCS_SYS_DEVICE_ID_UNKNOWN`: the value that terminates UCX's distance walk.
pub const SYS_DEV_UNKNOWN: u8 = u8MAX;
/// `UCS_MEMORY_TYPE_LAST` (`ucs/memory/memory_type.h`): the enum runs
/// `HOST = 0 .. GAUDI = 9`, then `LAST = 10`, with `UNKNOWN == LAST` a sentinel
/// that is never *stored* on a mapped region. UCX indexes arrays sized
/// `[UCS_MEMORY_TYPE_LAST]` (10 entries) by this byte with no bounds check —
/// `worker->mem_type_ep[mem_type]` in proto init, `ucs_memory_type_names[..]`
/// evaluated eagerly in `proto_common.c` — so a peer-supplied `mem_type >= 10`
/// is an out-of-bounds read on the progress thread. Velo only maps host memory,
/// whose packer emits `0`, so rejecting `>= LAST` refuses nothing legitimate.
const UCS_MEMORY_TYPE_LAST: u8 = 10;
/// `sizeof(ucp_rkey_packed_distance_t)` — `{ u8 sys_dev, fp8 latency, fp8
/// bandwidth }`, `UCS_S_PACKED` (`ucp_rkey.c:27`).
const PACKED_DISTANCE_LEN: usize = 3;
/// Why an RMA operation could not be performed.
pub
/// A locally registered memory region, as reported by the progress thread.
pub
/// One remote read: `len` bytes at `remote_addr` on `peer`, landing at
/// `local_offset` inside `local_region`.
pub
/// Submit-side state shared by every [`RdmaEndpoint`] clone of one transport.
pub
/// Handle for RMA operations on a started [`UcxTransport`](super::UcxTransport).
///
/// Obtained from `UcxTransport::rdma_endpoint`. Cloning is two atomic
/// increments; every clone addresses the same progress thread and the same
/// region-id space.
pub
/// Compensating unmap for a [`RdmaEndpoint::map_region`] whose caller went away.
///
/// The region id is minted before the push, so the id of a region that may now
/// exist is known even though the reply never arrived. Pushing an idempotent
/// `UnmapRegion` for it is therefore always safe: the progress thread either
/// unmaps a real region, or answers `Ok(())` for one that was never created (or
/// that its own rollback already removed).
///
/// `try_send` rather than an await, because `Drop` cannot block — but it can
/// spawn, so a full ring falls back to an awaited push on the transport's
/// runtime. What is left after that is a *closed* ring, which only happens once
/// the progress thread has begun tearing down, and teardown force-unmaps every
/// region it still holds.
/// Refuse a packed rkey `ucp_ep_rkey_unpack` could not parse within its own
/// bytes. Bounds first, then [`preparse_packed_rkey`].
pub
/// Prove that UCX's parse of `packed` terminates inside `packed`, and that the
/// one value UCX indexes arrays by is in range.
///
/// `ucp_ep_rkey_unpack` takes no length — the public API has no parameter for
/// one — so nothing stops a malformed blob walking off the end of whatever
/// buffer it lives in, and UCX's internal assertions are compiled out of a
/// release build. Neither a length check nor trailing padding can fix that, for
/// two separate reasons found in the 1.22.0 source:
///
/// * **Stage 1** (`ucp_rkey_pack_memh`'s format, read back in
/// `ucp_ep_rkey_unpack_internal`) is `md_map: u64le`, `mem_type: u8`, then one
/// `len: u8` + `len` bytes per set bit of `md_map`, then `sys_dev: u8` iff
/// `md_map != 0`. The walk is driven by `md_map`, never by a buffer end, and a
/// length byte sitting at the last content byte may declare 255 — so no fixed
/// pad size is provably enough.
/// * **Stage 2** (`ucp_rkey_unpack_lanes_distance`, reached through
/// `ucp_rkey_proto_resolve` whenever the peer is UCX >= 1.20 and the blob's
/// `sys_dev` is not `UNKNOWN`) sets `buffer_end = UINTPTR_MAX`
/// (`ucp_rkey.c:897`) and walks 3-byte records, breaking **only** on a `0xFF`
/// byte (`ucp_rkey.c:820`). Zero padding does not stop it; it feeds it.
///
/// So containment has to come from the blob itself. This walks the two format
/// stages and requires every read that drives them to land inside `packed`: the
/// stage-1 framing bytes (the `len` byte of each entry, the `sys_dev` byte) and
/// — when `sys_dev` is not `0xFF` and stage 2 therefore runs — a `0xFF`
/// terminator reachable on the 3-byte stride. UCX's own packer always produces
/// such a blob (`ucp_rkey_pack_memh` writes the terminator at `ucp_rkey.c:264`),
/// so nothing legitimate is refused.
///
/// Two reads are deliberately *not* covered here, and are contained elsewhere:
///
/// * The `mem_type` byte is not a walk position but an array index. UCX stores
/// it unchecked and later indexes `[UCS_MEMORY_TYPE_LAST]`-sized arrays with
/// it, so a value `>= UCS_MEMORY_TYPE_LAST` is an out-of-bounds read even
/// though the framing is perfect. It is validated below against
/// [`UCS_MEMORY_TYPE_LAST`].
/// * `uct_ib_rkey_unpack` reads a full `u64` out of each transport-key entry
/// regardless of the `len` byte, so a short IB entry makes UCX read up to
/// 8 bytes past the declared content. That over-read is bounded by
/// [`RKEY_UNPACK_PAD`] (an entry can start at offset ≤ 1024 in a 1536-byte
/// buffer), not by this walk — which validates framing, not per-entry content
/// length against the transport's fixed read width.
///
/// The whole scheme rests on one UCX invariant: `ucp_ep_rkey_unpack` passes
/// `length = 0`, so the two early-return exits below (`md_map == 0`,
/// `sys_dev == UNKNOWN`) are safe against trailing bytes only because UCX itself
/// stops there. A UCX variant that passed a real length and kept reading would
/// break that assumption — a version bump has to re-check it.
///
/// # This contains framing, not staleness
///
/// A *semantically* stale rkey — framing perfect, region long gone — passes
/// here identically, and on InfiniBand the consequence is not a recoverable
/// error: the unpack succeeds against a real local memory domain, the GET
/// posts, and `uct_rc_verbs` escalates the HCA completion error to `ucs_fatal`,
/// aborting the process. Over `UCX_TLS=tcp` the same blob comes back as an
/// ordinary `Err`, so no tcp-only test can reach the class (measured
/// 2026-08-29, `agent-docs/2026-08-29-rdma-phase3-hardware-checkpoint.md` §3).
///
/// What keeps that unreachable is D3 — single-use rkeys plus revalidation at
/// every acquire — not this function. Anything that lets an rkey outlive its
/// op, a consumer-side rkey cache or an arena reclaimed under a live
/// descriptor, removes the only guard there is, and this pre-parse is what
/// stands between a bad descriptor and `ucs_fatal` after that.
pub