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
//! Definition and implementations of of `HazardEpoch`
//!
use util::WrappedAlign64Type;
use spin_lock::SpinLock;
use hazard_pointer::{ThreadStore, VersionHandle};
use std::ptr;
use std::mem;
use std::intrinsics;
use util;
use error;
use util::sync_fetch_and_add;
use util::sync_add_and_fetch;

pub use hazard_pointer::{BaseHazardNode, HazardNodeT};

cfg_if! {
    if #[cfg(feature = "max_thread_count_4096")] {
        pub const MAX_THREAD_COUNT: usize = 4096;
    } else if #[cfg(feature = "max_thread_count_256")] {
        pub const MAX_THREAD_COUNT: usize = 256;
    } else {
        /// Maximum thread count
        pub const MAX_THREAD_COUNT: usize = 16;
    }
}

struct VersionTimestamp {
    curr_min_version: u64,
    curr_min_version_timestamp: i64,
}

/// `HazardEpoch` a practical implementation of `Hazard Pointers`, which use global incremental
/// version to identify shared object to be reclaimed. Because of [`False sharing`](https://en.wikipedia.org/wiki/False_sharing),
/// a part of the member variables, might be frequently modified by different threads, are aligned
/// to 64 bytes.
pub struct HazardEpoch {
    thread_waiting_threshold: i64,
    min_version_cache_time_us: i64,
    version: WrappedAlign64Type<u64>,
    thread_lock: WrappedAlign64Type<SpinLock>,
    threads: [ThreadStore; MAX_THREAD_COUNT],
    thread_list: *mut ThreadStore,
    thread_count: i64,
    hazard_waiting_count: WrappedAlign64Type<i64>,
    curr_min_version_info: WrappedAlign64Type<VersionTimestamp>,
}

impl HazardEpoch {
    #[inline]
    unsafe fn curr_min_version(&self) -> u64 {
        intrinsics::atomic_load(&self.curr_min_version_info.curr_min_version)
    }

    #[inline]
    unsafe fn set_curr_min_version(&mut self, curr_min_version: u64) {
        intrinsics::atomic_store(
            &mut self.curr_min_version_info.curr_min_version,
            curr_min_version,
        );
    }

    #[inline]
    unsafe fn curr_min_version_timestamp(&self) -> i64 {
        intrinsics::atomic_load(&self.curr_min_version_info.curr_min_version_timestamp)
    }

    #[inline]
    unsafe fn set_curr_min_version_timestamp(&mut self, curr_min_version_timestamp: i64) {
        intrinsics::atomic_store(
            &mut self.curr_min_version_info.curr_min_version_timestamp,
            curr_min_version_timestamp,
        );
    }

    /// To improve performance, `HazardEpoch` can be allocated in stack directly, but it can't be
    /// moved after calling any method. `thread_waiting_threshold` means the maximum of the number of
    /// shared objects to be reclaimed under one thread. `min_version_cache_time_us` means the time
    /// interval(microsecond) to update minimum version cache.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_lockfree::hazard_epoch::HazardEpoch;
    ///
    /// let h = unsafe { HazardEpoch::new_in_stack(64, 200000) };
    /// let addr_h = &h as *const _ as usize;
    /// assert_eq!(addr_h % 64, 0);
    /// ```
    ///
    #[inline]
    pub unsafe fn new_in_stack(
        thread_waiting_threshold: i64,
        min_version_cache_time_us: i64,
    ) -> HazardEpoch {
        let mut ret = HazardEpoch {
            thread_waiting_threshold,
            min_version_cache_time_us,
            version: WrappedAlign64Type(0),
            thread_lock: WrappedAlign64Type(SpinLock::default()),
            threads: mem::zeroed(),
            thread_list: ptr::null_mut(),
            thread_count: 0,
            hazard_waiting_count: WrappedAlign64Type(0),
            curr_min_version_info: WrappedAlign64Type(VersionTimestamp {
                curr_min_version: 0,
                curr_min_version_timestamp: 0,
            }),
        };
        for idx in 0..ret.threads.len() {
            ret.threads[idx] = ThreadStore::default();
        }
        ret
    }

    /// Alloc `HazardEpoch` in heap. Usage is the same as `new_in_stack`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_lockfree::hazard_epoch::HazardEpoch;
    ///
    /// let h = HazardEpoch::new_in_heap(64, 200000);
    /// let _addr_h = &h as *const _ as usize;
    /// ```
    ///
    #[inline]
    pub fn new_in_heap(thread_waiting_threshold: i64, min_version_cache_time_us: i64) -> Box<Self> {
        unsafe {
            Box::new(Self::new_in_stack(
                thread_waiting_threshold,
                min_version_cache_time_us,
            ))
        }
    }

    /// Return `Self::new_in_stack(64, 200000)`
    #[inline]
    pub unsafe fn default_new_in_stack() -> Self {
        Self::new_in_stack(64, 200000)
    }

    /// Return `Self::new_in_heap(64, 200000)`
    #[inline]
    pub fn default_new_in_heap() -> Box<Self> {
        Self::new_in_heap(64, 200000)
    }

    #[inline]
    unsafe fn destroy(&mut self) {
        self.retire();
    }

    /// Reclaim all shared objects waiting to be reclaimed. It will be called when dropping `HazardEpoch`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_lockfree::hazard_epoch::HazardEpoch;
    /// use rs_lockfree::hazard_epoch::BaseHazardNode;
    ///
    /// let mut h = HazardEpoch::new_in_heap(64, 200000);
    /// let node = Box::into_raw(Box::new(BaseHazardNode::default()));
    /// unsafe { h.add_node(node); }
    /// unsafe { h.retire(); }
    /// ```
    ///
    pub unsafe fn retire(&mut self) {
        let mut ts = ptr::null_mut::<ThreadStore>();
        let ret = self.get_thread_store(&mut ts);
        if ret != error::Status::Success {
            warn!("get_thread_store fail, ret={}", ret);
            return;
        }
        let min_version = self.get_min_version(true);
        let retire_count = (*ts).retire(min_version, &mut *ts);
        sync_fetch_and_add(self.hazard_waiting_count.as_mut_ptr(), -retire_count);

        let mut iter = self.atomic_load_thread_list();
        while !iter.is_null() {
            if iter != ts {
                let retire_count = (*iter).retire(min_version, &mut *ts);
                sync_fetch_and_add(self.hazard_waiting_count.as_mut_ptr(), -retire_count);
            }
            iter = (*iter).next();
        }
    }

    /// Reclaim all shared objects waiting to be reclaimed. `node` can be any type as long as it implements
    /// Trait `HazardNodeT`. `BaseHazardNode` is used to realize `vtable`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_lockfree::hazard_epoch::HazardEpoch;
    /// use rs_lockfree::hazard_epoch::{BaseHazardNode, HazardNodeT};
    /// use std::cell::RefCell;
    ///
    /// struct Node<'a, T> {
    ///     base: BaseHazardNode,
    ///     cnt: &'a RefCell<i32>,
    ///     v: T,
    /// }
    ///
    /// impl<'a, T> Drop for Node<'a, T> {
    ///     fn drop(&mut self) {
    ///         *self.cnt.borrow_mut() += 10;
    ///     }
    /// }
    ///
    /// impl<'a, T> HazardNodeT for Node<'a, T> {
    ///     fn get_base_hazard_node(&self) -> *mut BaseHazardNode {
    ///         &self.base as *const _ as *mut _
    ///     }
    /// }
    ///
    /// let cnt = RefCell::new(0);
    /// let mut h = HazardEpoch::default_new_in_heap();
    /// let node = Box::into_raw(Box::new(Node{
    ///     base: Default::default(),
    ///     cnt: &cnt,
    ///     v: 2333,
    /// }));
    /// unsafe { h.add_node(node); }
    /// drop(h);
    /// assert_eq!(*cnt.borrow(), 10);
    /// ```
    ///
    #[inline]
    pub unsafe fn add_node<T>(&mut self, node: *mut T) -> error::Status
    where
        T: HazardNodeT,
    {
        let mut ts = ptr::null_mut::<ThreadStore>();
        let mut ret;
        if node.is_null() {
            warn!("node is null");
            ret = error::Status::InvalidParam;
        } else if error::Status::Success != {
            ret = self.get_thread_store(&mut ts);
            ret
        } {
            warn!("get_thread_store fail, ret={}", ret);
        } else if error::Status::Success != {
            ret = (*ts).add_node(sync_add_and_fetch(self.version.as_mut_ptr(), 1), node);
            ret
        } {
            warn!("add_node fail, ret={}", ret);
        } else {
            sync_fetch_and_add(self.hazard_waiting_count.as_mut_ptr(), 1);
        }
        ret
    }

    #[inline]
    fn atomic_load_version(&self) -> u64 {
        unsafe { intrinsics::atomic_load(self.version.as_ptr()) }
    }

    /// Before accessing a shared object, call method `acquire` to get the `handle` of this operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_lockfree::hazard_epoch::HazardEpoch;
    /// use rs_lockfree::hazard_epoch::BaseHazardNode;
    /// use rs_lockfree::error::Status;
    ///
    /// let mut h = HazardEpoch::default_new_in_heap();
    /// let node = Box::into_raw(Box::new(BaseHazardNode::default()));
    /// let mut handle = 0;
    /// assert_eq!(h.acquire(&mut handle), Status::Success);
    /// let _o = unsafe { &(*node) };
    /// unsafe { h.release(handle); }
    /// ```
    ///
    pub fn acquire(&mut self, handle: &mut u64) -> error::Status {
        let mut ts = ptr::null_mut::<ThreadStore>();
        let mut ret;
        if error::Status::Success != {
            ret = unsafe { self.get_thread_store(&mut ts) };
            ret
        } {
            warn!("get_thread_store fail, ret={}", ret);
        } else {
            let ts = unsafe { &mut *ts };
            loop {
                let version = self.atomic_load_version();
                let mut version_handle = VersionHandle::new(0);
                if error::Status::Success != {
                    ret = ts.acquire(version, &mut version_handle);
                    ret
                } {
                    warn!("thread store acquire fail, ret={}", ret);
                    break;
                } else if version != self.atomic_load_version() {
                    ts.release(&version_handle);
                } else {
                    *handle = version_handle.ver_u64();
                    break;
                }
            }
        }
        ret
    }

    /// Atomic load count of thread
    #[inline]
    fn atomic_load_thread_count(&self) -> i64 {
        unsafe { intrinsics::atomic_load(&self.thread_count) }
    }

    /// After accessing a shared object, call method `release` to trigger reclaiming. Usage is the
    /// same as `acquire`.
    #[inline]
    pub unsafe fn release(&mut self, handle: u64) {
        let version_handle = VersionHandle::new(handle);
        if MAX_THREAD_COUNT > version_handle.tid() as usize {
            let ts = self.threads
                .as_mut_ptr()
                .offset(version_handle.tid() as isize);
            (*ts).release(&version_handle);
            if self.thread_waiting_threshold < (*ts).get_hazard_waiting_count() {
                let min_version = self.get_min_version(false);
                let retire_count = (*ts).retire(min_version, &mut *ts);
                sync_fetch_and_add(self.hazard_waiting_count.as_mut_ptr(), -retire_count);
            } else if self.atomic_load_thread_count() * self.thread_waiting_threshold
                < self.atomic_load_hazard_waiting_count()
            {
                self.retire();
            }
        }
    }

    /// Atomic load count of shared objects waiting to be reclaimed.
    #[inline]
    pub fn atomic_load_hazard_waiting_count(&self) -> i64 {
        unsafe { intrinsics::atomic_load(self.hazard_waiting_count.as_ptr()) }
    }

    #[inline]
    unsafe fn get_thread_store(&mut self, ts: &mut *mut ThreadStore) -> error::Status {
        let mut ret = error::Status::Success;
        let tn = util::get_thread_id() as u16;
        if MAX_THREAD_COUNT <= tn as usize {
            warn!("thread number overflow, tn={}", tn);
            ret = error::Status::ThreadNumOverflow;
        } else {
            *ts = self.threads.as_mut_ptr().offset(tn as isize);
            let ts_obj = &mut **ts;
            // different thread use different thread store.
            if !ts_obj.is_enabled() {
                // CAS can be used directly here, no ABA problem.
                // Atomicity of thread_count is not necessary.

                self.thread_lock.lock();

                ts_obj.set_enabled(tn);
                ts_obj.set_next(self.atomic_load_thread_list());
                intrinsics::atomic_store(
                    &mut self.thread_list as *mut _ as *mut usize,
                    *ts as usize,
                );
                sync_fetch_and_add(&mut self.thread_count, 1);

                self.thread_lock.unlock();
            }
        }
        ret
    }

    #[inline]
    unsafe fn atomic_load_thread_list(&self) -> *mut ThreadStore {
        util::atomic_load_raw_ptr(&self.thread_list)
    }

    unsafe fn get_min_version(&mut self, force_flush: bool) -> u64 {
        let mut ret = 0;
        if !force_flush && 0 != {
            ret = self.curr_min_version();
            ret
        }
            && self.curr_min_version_timestamp() + self.min_version_cache_time_us
                > util::get_cur_microseconds_time()
        {
        } else {
            ret = self.atomic_load_version();
            let mut iter = self.atomic_load_thread_list();
            while !iter.is_null() {
                let ts_min_version = (*iter).version();
                if ret > ts_min_version {
                    ret = ts_min_version;
                }
                iter = (*iter).next();
            }
            self.set_curr_min_version(ret);
            self.set_curr_min_version_timestamp(util::get_cur_microseconds_time());
        }
        ret
    }
}

impl Drop for HazardEpoch {
    fn drop(&mut self) {
        unsafe {
            self.destroy();
        }
    }
}