logo
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
use std::{
    borrow::Borrow,
    cell::UnsafeCell,
    marker::PhantomData as marker,
    ops::{Deref, DerefMut},
    sync::{
        atomic::{self, Ordering},
        Arc,
    },
    time::Duration,
};

use super::{
    readset::ReadSet,
    transact::{TransactionState, Txn, TxnManager},
};

use super::version::*;
use log::*;

use parking_lot::*;

use super::utils;

use crate::txn::transact::TransactionConcurrency;
use crate::txn::writeset::WriteSet;
use std::alloc::{dealloc, Layout};
use std::any::Any;

///
/// Transactional variable
#[derive(Clone)]
pub struct TVar<T>
where
    T: Clone + Any + Send + Sync,
{
    pub(crate) data: Var,
    pub(crate) lock: Arc<ReentrantMutex<bool>>,
    /// TVar ID
    pub(crate) id: u64,
    /// R/W Timestamp
    pub(crate) stamp: u64,
    /// Revision of last modification on this key.
    pub(crate) modrev: u64,
    timeout: usize,
    marker: marker<T>,
}

impl<T> TVar<T>
where
    T: Clone + Any + Send + Sync,
{
    ///
    /// Instantiates transactional variable for later use in a transaction.
    pub fn new(data: T) -> Self {
        TVar {
            data: Arc::new(data),
            lock: Arc::new(ReentrantMutex::new(true)),
            id: TxnManager::dispense_tvar_id(),
            stamp: TxnManager::rts(),
            modrev: TxnManager::rts(),
            timeout: super::constants::DEFAULT_TX_TIMEOUT,
            marker,
        }
    }

    ///
    /// New transactional variable with overridden timeout for overriding timeout for specific
    /// transactional variable.
    ///
    /// Highly discouraged for the daily use unless you have various code paths that can
    /// interfere over the variable that you instantiate.
    pub fn new_with_timeout(data: T, timeout: usize) -> Self {
        TVar {
            data: Arc::new(data),
            lock: Arc::new(ReentrantMutex::new(true)),
            id: TxnManager::dispense_tvar_id(),
            stamp: TxnManager::rts(),
            modrev: TxnManager::rts(),
            timeout,
            marker,
        }
    }

    pub(crate) fn set_stamp(&mut self, stamp: u64) {
        self.stamp = stamp;
    }

    pub(crate) fn set_mod_rev(&mut self, modrev: u64) {
        self.modrev = modrev;
    }

    ///
    /// Get's the underlying data for the transactional variable.
    ///
    /// Beware that this will not give correct results any given point
    /// in time during the course of execution of a transaction.
    pub fn get_data(&self) -> T {
        let val = self.data.clone();

        (&*val as &dyn Any)
            .downcast_ref::<T>()
            .expect("Only tx vars are allowed for values.")
            .clone()
    }

    pub(crate) fn open_read(&self) -> T {
        let rs = ReadSet::local();
        let txn = Txn::get_local();
        let state: &TransactionState = &*txn.state.get();

        match state {
            TransactionState::Committed | TransactionState::Unknown => self.get_data(),
            TransactionState::Active => {
                let ws = WriteSet::local();

                let scratch = ws.get_by_stamp::<T>(self.stamp);

                if scratch.is_none() {
                    if self.is_locked() {
                        // TODO: throw abort
                        txn.rollback();
                        // panic!("READ: You can't lock and still continue processing");
                    }

                    let tvar = self.clone();
                    let arctvar = Arc::new(tvar);
                    rs.add(arctvar);

                    self.get_data()
                } else {
                    let written = scratch.unwrap();
                    let v: T = utils::version_to_dest(written);
                    v
                }
            }
            TransactionState::MarkedRollback => {
                debug!("Starting rolling back: {}", TxnManager::rts());
                txn.rolling_back();
                txn.on_abort::<T>();
                self.get_data()
            }
            TransactionState::RollingBack => {
                // Give some time to recover and prevent inconsistency with giving only the pure
                // data back.
                // std::thread::sleep(Duration::from_millis(10));
                self.get_data()
            }
            TransactionState::Suspended => {
                std::thread::sleep(Duration::from_millis(100));
                self.get_data()
            }
            TransactionState::RolledBack => {
                txn.rolled_back();
                panic!("Transaction rollback finalized.");
            }
            s => {
                panic!("Unexpected transaction state: {:?}", s);
            }
        }
    }

    ///
    /// Convenience over deref mut writes
    pub(crate) fn open_write_deref_mut(&mut self) -> T {
        self.open_write(self.get_data())
    }

    ///
    /// Explicit writes
    pub(crate) fn open_write(&mut self, data: T) -> T {
        // dbg!("OPEN WRITE");
        let txn = Txn::get_local();
        let state: &TransactionState = &*txn.state.get();

        match state {
            TransactionState::Committed | TransactionState::Unknown => self.get_data(),
            TransactionState::Active => {
                let mut ws = WriteSet::local();

                let this = Arc::new(self.clone());
                if ws.get_by_stamp::<T>(this.stamp).is_none() {
                    if self.is_locked() {
                        // TODO: throw abort
                        // panic!("WRITE: You can't lock and still continue processing");
                        txn.rollback();
                    }
                    self.modrev = self.modrev.saturating_add(1);
                    let this = Arc::new(self.clone());
                    ws.put::<T>(this, Arc::new(data.clone()));

                    // match txn.iso {
                    //     TransactionIsolation::ReadCommitted => {
                    //         dbg!("READ_COMMITTED_COMING");
                    //         if let Some(mut l) = GLOBAL_DELTAS.try_lock() {
                    //             let this = Arc::new(self.clone());
                    //             l.push(Version::Write(this));
                    //         }
                    //     },
                    //     _ => {
                    //         // todo!()
                    //     }
                    // }

                    self.data = Arc::new(data.clone());
                }
                self.data = Arc::new(data);
                self.get_data()
            }
            TransactionState::MarkedRollback
            | TransactionState::RollingBack
            | TransactionState::RolledBack => {
                // TODO: Normally aborted, I am still unsure that should I represent this as
                // full committed read or panic with a fault.
                // According to science serializable systems get panicked here.

                // panic!("Panic abort, no writes are possible.");
                txn.state.replace_with(|_| TransactionState::Unknown);
                self.get_data()
            }
            TransactionState::Suspended => {
                std::thread::sleep(Duration::from_millis(100));
                self.get_data()
            }
            s => {
                panic!("Unexpected transaction state: {:?}", s);
            }
        }
    }

    pub(crate) fn validate(&self) -> bool {
        let txn = Txn::get_local();
        let state: &TransactionState = &*txn.state.get();

        match state {
            TransactionState::Committed | TransactionState::Unknown => true,
            TransactionState::Active => {
                let free = self.is_not_locked_and_current();
                let pure = self.stamp <= TxnManager::rts();

                free & pure
            }
            TransactionState::MarkedRollback
            | TransactionState::RollingBack
            | TransactionState::RolledBack => false,
            s => {
                panic!("Unexpected transaction state: {:?}", s);
            }
        }
    }

    pub(crate) fn is_locked(&self) -> bool {
        self.lock.try_lock().is_none()
    }

    pub(crate) fn is_not_locked_and_current(&self) -> bool {
        !self.is_locked()
    }

    pub(crate) fn is_writer_held_by_current_thread(&self) -> bool {
        self.is_locked()
    }
}

impl<T: Any + Clone + Send + Sync> Deref for TVar<T> {
    type Target = T;

    fn deref(&self) -> &T {
        let x: *mut T = BoxMemory.allocate(self.open_read());
        unsafe { &*(x) }
    }
}

impl<T: 'static + Any + Clone + Send + Sync> DerefMut for TVar<T> {
    fn deref_mut(&mut self) -> &mut T {
        let x: *mut T = BoxMemory.allocate(self.open_write_deref_mut());
        unsafe { &mut *(x) }
    }
}

/// A type that can allocate and deallocate far heap memory.
pub(crate) trait Memory {
    /// Allocates memory.
    fn allocate<T>(&self, value: T) -> *mut T;

    /// Deallocates the memory associated with the supplied pointer.
    unsafe fn deallocate<T>(&self, pointer: *mut T);
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct BoxMemory;

impl BoxMemory {
    pub(crate) fn reclaim<T>(&self, pointer: *const T) -> T {
        assert!(!pointer.is_null());
        unsafe { std::ptr::read_volatile::<T>(pointer as *mut T) }
    }

    pub(crate) fn reclaim_mut<T>(&self, pointer: *mut T) -> T {
        assert!(!pointer.is_null());
        unsafe { std::ptr::read_volatile::<T>(pointer) }
    }

    pub(crate) fn volatile_read<T: Clone>(&self, pointer: *mut T) -> T {
        assert!(!pointer.is_null());
        unsafe { std::ptr::read_volatile::<T>(pointer) }
    }

    pub(crate) fn deallocate_raw<T>(&self, p: *mut T) {
        unsafe {
            std::ptr::drop_in_place(p);
            dealloc(p as *mut u8, Layout::new::<T>());
        }
    }

    pub(crate) fn replace_with<T: Clone, X>(&self, ptr: *mut T, mut thunk: X)
    where
        X: FnMut(T) -> T,
    {
        let read = unsafe { std::ptr::read_volatile::<T>(ptr as *const T) };
        let res = thunk(read);
        unsafe { std::ptr::write_volatile::<T>(ptr, res) };
    }
}

impl Memory for BoxMemory {
    fn allocate<T>(&self, value: T) -> *mut T {
        Box::into_raw(Box::new(value))
    }

    unsafe fn deallocate<T>(&self, pointer: *mut T) {
        assert!(!pointer.is_null());
        Box::from_raw(pointer);
    }
}