async-rdma 0.5.0

A rust async wrapper for RDMA ibvers lib
Documentation
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
use super::{raw::RawMemoryRegion, IbvAccess, MrAccess, MrToken};
#[cfg(test)]
use crate::protection_domain::ProtectionDomain;
use crate::{
    lock_utilities::{MappedRwLockReadGuard, MappedRwLockWriteGuard},
    MRManageStrategy,
};

use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use rdma_sys::ibv_access_flags;
use sealed::sealed;
use std::{
    alloc::{dealloc, Layout},
    fmt::Debug,
    ops::Range,
    slice,
    sync::Arc,
    time::{Duration, SystemTime},
};
use tracing::debug;

/// Local memory region trait
///
/// # Safety
///
/// For the `fn`s that have not been marked as `unsafe`, we should make sure the implementations
/// meet all safety requirements, for example the memory of mrs should be initialized.
///
/// For the `unsafe` `fn`s, we should make sure no other safety issues have been introduced except
/// for the issues that have been listed in the `Safety` documents of `fn`s.
#[sealed]
pub unsafe trait LocalMrReadAccess: MrAccess {
    /// Get the start pointer until it is readable
    ///
    /// If this mr is being used in RDMA ops, the thread may be blocked
    #[allow(clippy::as_conversions)]
    #[inline]
    fn as_ptr(&self) -> MappedRwLockReadGuard<*const u8> {
        MappedRwLockReadGuard::new(self.get_inner().read(), self.addr() as *const u8)
    }

    /// Try to get the start pointer
    ///
    /// Return `None` if this mr is being used in RDMA ops without blocking thread
    #[allow(clippy::as_conversions)]
    #[inline]
    fn try_as_ptr(&self) -> Option<MappedRwLockReadGuard<*const u8>> {
        self.get_inner().try_read().map_or_else(
            || None,
            |guard| return Some(MappedRwLockReadGuard::new(guard, self.addr() as *const u8)),
        )
    }

    /// Get the start pointer without lock
    ///
    /// # Safety
    ///
    /// Make sure the mr is readable without cancel safety issue
    #[inline]
    #[allow(clippy::as_conversions)]
    fn as_ptr_unchecked(&self) -> *const u8 {
        self.addr() as _
    }

    /// Get the memory region as slice until it is readable
    ///
    /// If this mr is being used in RDMA ops, the thread may be blocked
    #[inline]
    #[allow(clippy::as_conversions)]
    fn as_slice(&self) -> MappedRwLockReadGuard<&[u8]> {
        // SAFETY: memory of this mr should have been initialized
        MappedRwLockReadGuard::map(self.as_ptr(), |ptr| unsafe {
            slice::from_raw_parts(ptr, self.length())
        })
    }

    /// Try to get the memory region as slice
    ///
    /// Return `None` if this mr is being used in RDMA ops without blocking thread
    #[allow(clippy::as_conversions)]
    #[inline]
    fn try_as_slice(&self) -> Option<MappedRwLockReadGuard<&[u8]>> {
        self.try_as_ptr().map_or_else(
            || None,
            |guard| {
                // SAFETY: memory of this mr should have been initialized
                return Some(MappedRwLockReadGuard::map(guard, |ptr| unsafe {
                    slice::from_raw_parts(ptr, self.length())
                }));
            },
        )
    }

    /// Get the memory region as slice without lock
    ///
    /// # Safety
    ///
    /// * Make sure the mr is readable without cancel safety issue.
    /// * The memory of this mr is initialized.
    /// * The total size of this mr of the slice must be no larger than `isize::MAX`.
    #[inline]
    unsafe fn as_slice_unchecked(&self) -> &[u8] {
        slice::from_raw_parts(self.as_ptr_unchecked(), self.length())
    }

    /// Get the local key
    fn lkey(&self) -> u32;

    /// Get the local key without lock
    ///
    /// # Safety
    ///
    /// Must ensure that there are no data races, for example:
    ///
    /// * The current thread logically owns a guard but that guard has been discarded using `mem::forget`.
    /// * The `lkey` of this mr is going to be changed.(It's not going to happen so far, because variable
    /// lkey has not been implemented yet.)
    #[inline]
    #[allow(clippy::unreachable)] // inner will not be null
    unsafe fn lkey_unchecked(&self) -> u32 {
        // SAFETY: must ensure that there are no data races
        let inner = self.get_inner().data_ptr();
        // SAFETY: rely on the former ?
        <*const LocalMrInner>::as_ref(inner)
            .map_or_else(|| unreachable!("get null inner"), LocalMrInner::lkey)
    }

    /// Get the remote key without lock
    ///
    /// # Safety
    ///
    /// Must ensure that there are no data races, for example:
    /// * The current thread logically owns a guard but that guard has been discarded using `mem::forget`.
    /// * The `rkey` of this mr is going to be changed.(It's not going to happen so far, because variable
    /// rkey has not been implemented yet.)
    #[inline]
    #[allow(clippy::unreachable)] // inner will not be null
    unsafe fn rkey_unchecked(&self) -> u32 {
        // SAFETY: must ensure that there are no data races
        let inner = self.get_inner().data_ptr();
        // SAFETY: rely on the former ?
        <*const LocalMrInner>::as_ref(inner)
            .map_or_else(|| unreachable!("get null inner"), LocalMrInner::rkey)
    }

    /// New a token with specified timeout
    #[inline]
    fn token_with_timeout(&self, timeout: Duration) -> Option<MrToken> {
        SystemTime::now().checked_add(timeout).map_or_else(
            || None,
            |ddl| {
                Some(MrToken {
                    addr: self.addr(),
                    len: self.length(),
                    rkey: self.rkey(),
                    ddl,
                    access: self.ibv_access().0,
                })
            },
        )
    }

    /// New a token with specified timeout with `rkey_unchecked`
    ///
    /// # Safety
    ///
    /// Must ensure that there are no data races about `rkey`, for example:
    /// * The current thread logically owns a guard but that guard has been discarded using `mem::forget`.
    /// * The `rkey` of this mr is going to be changed.(It's not going to happen so far, because variable
    /// rkey has not been implemented yet.)
    ///
    #[inline]
    unsafe fn token_with_timeout_unchecked(&self, timeout: Duration) -> Option<MrToken> {
        SystemTime::now().checked_add(timeout).map_or_else(
            || None,
            |ddl| {
                Some(MrToken {
                    addr: self.addr(),
                    len: self.length(),
                    rkey: self.rkey_unchecked(),
                    ddl,
                    access: self.ibv_access().0,
                })
            },
        )
    }

    /// Get the corresponding `RwLocalMrInner`
    fn get_inner(&self) -> &Arc<RwLocalMrInner>;

    /// Is the corresponding `RwLocalMrInner` readable?
    #[inline]
    fn is_readable(&self) -> bool {
        !self.get_inner().is_locked_exclusive()
    }

    /// Get read lock of `LocalMrInenr`
    #[inline]
    fn read_inner(&self) -> RwLockReadGuard<LocalMrInner> {
        self.get_inner().read()
    }
}

/// Writable local mr trait
///
/// # Safety
///
/// For the `fn`s that have not been marked as `unsafe`, we should make sure the implementations
/// meet all safety requirements, for example the memory should be initialized.
///
/// For the `unsafe` `fn`s, we should make sure no other safety issues have been introduced except
/// for the issues that have been listed in the `Safety` documents of `fn`s.
#[sealed]
pub unsafe trait LocalMrWriteAccess: MrAccess + LocalMrReadAccess {
    /// Get the mutable start pointer until it is writeable
    ///
    /// If this mr is being used in RDMA ops, the thread may be blocked
    #[inline]
    #[allow(clippy::as_conversions)]
    fn as_mut_ptr(&mut self) -> MappedRwLockWriteGuard<*mut u8> {
        MappedRwLockWriteGuard::new(self.get_inner().write(), self.addr() as *mut u8)
    }

    /// Try to get the mutable start pointer
    ///
    /// Return `None` if this mr is being used in RDMA ops without blocking thread
    #[allow(clippy::as_conversions)]
    #[inline]
    fn try_as_mut_ptr(&self) -> Option<MappedRwLockWriteGuard<*mut u8>> {
        self.get_inner().try_write().map_or_else(
            || None,
            |guard| return Some(MappedRwLockWriteGuard::new(guard, self.addr() as *mut u8)),
        )
    }

    /// Get the memory region start mut addr without lock
    ///
    /// # Safety
    ///
    /// Make sure the mr is writeable without cancel safety issue
    #[inline]
    #[allow(clippy::as_conversions)]
    fn as_mut_ptr_unchecked(&mut self) -> *mut u8 {
        // const pointer to mut pointer is safe
        self.as_ptr_unchecked() as _
    }

    /// Get the memory region as mutable slice until it is writeable
    ///
    /// If this mr is being used in RDMA ops, the thread may be blocked
    #[inline]
    #[allow(clippy::as_conversions)]
    fn as_mut_slice(&mut self) -> MappedRwLockWriteGuard<&mut [u8]> {
        let len = self.length();
        // SAFETY: memory of this mr should have been initialized
        MappedRwLockWriteGuard::map(self.as_mut_ptr(), |ptr| unsafe {
            slice::from_raw_parts_mut(ptr, len)
        })
    }

    /// Try to get the memory region as mutable slice
    ///
    /// Return `None` if this mr is being used in RDMA ops without blocking thread
    #[allow(clippy::as_conversions)]
    #[inline]
    fn try_as_mut_slice(&mut self) -> Option<MappedRwLockWriteGuard<&mut [u8]>> {
        self.try_as_mut_ptr().map_or_else(
            || None,
            |guard| {
                // SAFETY: memory of this mr should have been initialized
                return Some(MappedRwLockWriteGuard::map(guard, |ptr| unsafe {
                    slice::from_raw_parts_mut(ptr, self.length())
                }));
            },
        )
    }

    /// Get the memory region as mut slice without lock
    ///
    /// # Safety
    ///
    /// * Make sure the mr is writeable without cancel safety issue.
    /// * The memory of this mr is initialized.
    /// * The total size of this mr of the slice must be no larger than `isize::MAX`.
    #[inline]
    unsafe fn as_mut_slice_unchecked(&mut self) -> &mut [u8] {
        slice::from_raw_parts_mut(self.as_mut_ptr_unchecked(), self.length())
    }

    /// Is the corresponding `RwLocalMrInner` writeable?
    #[inline]
    fn is_writeable(&self) -> bool {
        !self.get_inner().is_locked()
    }

    /// Get write lock of `LocalMrInenr`
    #[inline]
    fn write_inner(&self) -> RwLockWriteGuard<LocalMrInner> {
        self.get_inner().write()
    }
}

/// Local Memory Region
#[derive(Debug)]
pub struct LocalMr {
    /// The corresponding `RwLocalMrInner`.
    inner: Arc<RwLocalMrInner>,
    /// The start address of this mr
    addr: usize,
    /// the length of this mr
    len: usize,
}

impl MrAccess for LocalMr {
    #[inline]
    fn addr(&self) -> usize {
        self.addr
    }

    #[inline]
    fn length(&self) -> usize {
        self.len
    }

    #[inline]
    fn rkey(&self) -> u32 {
        self.read_inner().rkey()
    }
}

impl IbvAccess for LocalMr {
    #[inline]
    fn ibv_access(&self) -> ibv_access_flags {
        self.read_inner().ibv_access()
    }
}

#[sealed]
unsafe impl LocalMrReadAccess for LocalMr {
    #[inline]
    fn lkey(&self) -> u32 {
        self.read_inner().lkey()
    }

    #[inline]
    fn get_inner(&self) -> &Arc<RwLocalMrInner> {
        &self.inner
    }
}

#[sealed]
unsafe impl LocalMrWriteAccess for LocalMr {}

impl LocalMr {
    /// New Local Mr
    pub(crate) fn new(inner: LocalMrInner) -> Self {
        let addr = inner.addr;
        let len = inner.layout.size();
        let inner = Arc::new(RwLock::new(inner));
        Self { inner, addr, len }
    }

    /// Get a local mr slice
    ///
    /// Return `None` if the inputed range is wrong
    #[inline]
    #[must_use]
    pub fn get(&self, i: Range<usize>) -> Option<LocalMrSlice> {
        // SAFETY: `self` is checked to be valid and in bounds above.
        if i.start >= i.end || i.end > self.len {
            None
        } else {
            Some(LocalMrSlice::new(
                self,
                Arc::<RwLocalMrInner>::clone(&self.inner),
                self.addr().wrapping_add(i.start),
                i.len(),
            ))
        }
    }

    /// Get an unchecked local mr slice
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible that these preconditions are
    /// satisfied:
    ///
    /// * The starting index must not exceed the ending index;
    /// * Indexes must be within bounds of the original `LocalMr`.
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked(&self, i: Range<usize>) -> LocalMrSlice {
        LocalMrSlice::new(
            self,
            Arc::<RwLocalMrInner>::clone(&self.inner),
            self.addr().wrapping_add(i.start),
            i.len(),
        )
    }

    /// Get a mutable local mr slice
    ///
    /// Return `None` if the inputed range is wrong
    #[inline]
    pub fn get_mut(&mut self, i: Range<usize>) -> Option<LocalMrSliceMut> {
        // SAFETY: `self` is checked to be valid and in bounds above.
        if i.start >= i.end || i.end > self.length() {
            None
        } else {
            Some(LocalMrSliceMut::new(
                self,
                Arc::<RwLocalMrInner>::clone(&self.inner),
                self.addr().wrapping_add(i.start),
                i.len(),
            ))
        }
    }

    /// Get an unchecked mutable local mr slice
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible that these preconditions are
    /// satisfied:
    ///
    /// * The starting index must not exceed the ending index;
    /// * Indexes must be within bounds of the original `LocalMr`.
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, i: Range<usize>) -> LocalMrSliceMut {
        LocalMrSliceMut::new(
            self,
            Arc::<RwLocalMrInner>::clone(&self.inner),
            self.addr().wrapping_add(i.start),
            i.len(),
        )
    }

    /// Take the ownership and return a sub local mr from self
    ///
    /// Return `None` if the inputed range is wrong
    #[inline]
    pub(crate) fn take(mut self, i: Range<usize>) -> Option<Self> {
        // SAFETY: `self` is checked to be valid and in bounds above.
        if i.start >= i.end || i.end > self.length() {
            None
        } else {
            self.addr = self.addr.wrapping_add(i.start);
            self.len = i.end.wrapping_sub(i.start);
            Some(self)
        }
    }

    /// Take the ownership and return an unchecked sub local mr from self
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible that these preconditions are
    /// satisfied:
    ///
    /// * The starting index must not exceed the ending index;
    /// * Indexes must be within bounds of the original `LocalMr`.
    #[inline]
    #[allow(dead_code)]
    pub(crate) unsafe fn take_unchecked(mut self, i: Range<usize>) -> Self {
        self.addr = self.addr.wrapping_add(i.start);
        self.len = i.end.wrapping_sub(i.start);
        self
    }
}

/// `LocalMrInner` in `RwLock`
pub(crate) type RwLocalMrInner = RwLock<LocalMrInner>;
/// Local Memory Region inner
#[derive(Debug)]
pub struct LocalMrInner {
    /// The start address of this mr
    addr: usize,
    /// The layout of this mr
    layout: Layout,
    /// The raw mr where this local mr comes from.
    raw: Arc<RawMemoryRegion>,
    /// Strategy to manage this `MR`
    strategy: MRManageStrategy,
}

impl Drop for LocalMrInner {
    #[inline]
    #[allow(clippy::as_conversions)]
    fn drop(&mut self) {
        debug!("drop LocalMr {:?}", self);
        match self.strategy {
            crate::MRManageStrategy::Jemalloc => {
                // SAFETY: ffi
                unsafe { tikv_jemalloc_sys::free(self.addr as _) }
            }
            crate::MRManageStrategy::Raw => {
                // SAFETY: The ptr is allocated via this allocator, and the layout is the same layout
                // that was used to allocate that block of memory.
                unsafe {
                    dealloc(self.addr as _, self.layout);
                }
            }
        }
    }
}

impl MrAccess for LocalMrInner {
    #[inline]
    fn addr(&self) -> usize {
        self.addr
    }

    #[inline]
    fn length(&self) -> usize {
        self.layout.size()
    }

    #[inline]
    fn rkey(&self) -> u32 {
        self.raw.rkey()
    }
}

impl IbvAccess for LocalMrInner {
    #[inline]
    fn ibv_access(&self) -> ibv_access_flags {
        self.raw.ibv_access()
    }
}

impl LocalMrInner {
    /// Crate a new `LocalMrInner`
    pub(crate) fn new(
        addr: usize,
        layout: Layout,
        raw: Arc<RawMemoryRegion>,
        strategy: MRManageStrategy,
    ) -> Self {
        Self {
            addr,
            layout,
            raw,
            strategy,
        }
    }

    /// Get local key of memory region
    fn lkey(&self) -> u32 {
        self.raw.lkey()
    }

    /// Get pd of this memory region
    #[cfg(test)]
    pub(crate) fn pd(&self) -> &Arc<ProtectionDomain> {
        self.raw.pd()
    }
}

impl MrAccess for &LocalMr {
    #[inline]
    fn addr(&self) -> usize {
        self.addr
    }

    #[inline]
    fn length(&self) -> usize {
        self.len
    }

    #[inline]
    fn rkey(&self) -> u32 {
        self.read_inner().rkey()
    }
}

impl IbvAccess for &LocalMr {
    #[inline]
    fn ibv_access(&self) -> ibv_access_flags {
        self.read_inner().ibv_access()
    }
}

#[sealed]
unsafe impl LocalMrReadAccess for &LocalMr {
    #[inline]
    fn lkey(&self) -> u32 {
        self.read_inner().lkey()
    }

    #[inline]
    fn get_inner(&self) -> &Arc<RwLocalMrInner> {
        &self.inner
    }
}

/// A slice of `LocalMr`
#[derive(Debug)]
pub struct LocalMrSlice<'a> {
    /// The local mr where this local mr slice comes from.
    lmr: &'a LocalMr,
    /// The corresponding `RwLocalMrInner`.
    inner: Arc<RwLocalMrInner>,
    /// The start address of this mr
    addr: usize,
    /// the length of this mr
    len: usize,
}

impl MrAccess for LocalMrSlice<'_> {
    #[inline]
    fn addr(&self) -> usize {
        self.addr
    }

    #[inline]
    fn length(&self) -> usize {
        self.len
    }

    #[inline]
    fn rkey(&self) -> u32 {
        self.lmr.rkey()
    }
}

impl IbvAccess for LocalMrSlice<'_> {
    #[inline]
    fn ibv_access(&self) -> ibv_access_flags {
        self.read_inner().ibv_access()
    }
}

#[sealed]
unsafe impl LocalMrReadAccess for LocalMrSlice<'_> {
    fn lkey(&self) -> u32 {
        self.lmr.lkey()
    }

    #[inline]
    fn get_inner(&self) -> &Arc<RwLocalMrInner> {
        &self.inner
    }
}

impl<'a> LocalMrSlice<'a> {
    /// New a local mr slice.
    pub(crate) fn new(
        lmr: &'a LocalMr,
        inner: Arc<RwLocalMrInner>,
        addr: usize,
        len: usize,
    ) -> Self {
        Self {
            lmr,
            inner,
            addr,
            len,
        }
    }
}

/// Mutable local mr slice
#[derive(Debug)]
pub struct LocalMrSliceMut<'a> {
    /// The local mr where this local mr slice comes from.
    lmr: &'a mut LocalMr,
    /// The corresponding `RwLocalMrInner`.
    inner: Arc<RwLocalMrInner>,
    /// The start address of this mr
    addr: usize,
    /// the length of this mr
    len: usize,
}

impl<'a> LocalMrSliceMut<'a> {
    /// New a mutable local mr slice.
    pub(crate) fn new(
        lmr: &'a mut LocalMr,
        inner: Arc<RwLocalMrInner>,
        addr: usize,
        len: usize,
    ) -> Self {
        Self {
            lmr,
            inner,
            addr,
            len,
        }
    }
}

impl MrAccess for LocalMrSliceMut<'_> {
    #[inline]
    fn addr(&self) -> usize {
        self.addr
    }

    #[inline]
    fn length(&self) -> usize {
        self.len
    }

    #[inline]
    fn rkey(&self) -> u32 {
        self.lmr.rkey()
    }
}

impl IbvAccess for LocalMrSliceMut<'_> {
    #[inline]
    fn ibv_access(&self) -> ibv_access_flags {
        self.read_inner().ibv_access()
    }
}

#[sealed]
unsafe impl LocalMrReadAccess for LocalMrSliceMut<'_> {
    fn lkey(&self) -> u32 {
        self.lmr.lkey()
    }

    #[inline]
    fn get_inner(&self) -> &Arc<RwLocalMrInner> {
        &self.inner
    }
}

#[sealed]
unsafe impl LocalMrWriteAccess for LocalMrSliceMut<'_> {}