├── Concurrent ├── .gitignore ├── CMakeLists.txt ├── include │ ├── common.h │ └── tlbtree.h ├── src │ ├── CMakeLists.txt │ ├── fixtree.h │ ├── flush.h │ ├── pmallocator.h │ ├── spinlock.h │ ├── tlbtree_impl.cc │ ├── tlbtree_impl.h │ ├── wotree256.cc │ └── wotree256.h └── test │ ├── CMakeLists.txt │ ├── datagen.cc │ ├── main.cc │ ├── preload.cc │ └── zipfian.h ├── LICENSE ├── README.md └── Single ├── .gitignore ├── CMakeLists.txt ├── include ├── common.h └── tlbtree.h ├── src ├── CMakeLists.txt ├── fixtree.h ├── flush.h ├── pmallocator.h ├── spinlock.h ├── tlbtree_impl.cc ├── tlbtree_impl.h ├── wotree256.cc └── wotree256.h └── test ├── CMakeLists.txt ├── datagen.cc ├── gen.sh ├── main.cc ├── preload.cc ├── test.cc └── zipfian.h /Concurrent/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .vscode -------------------------------------------------------------------------------- /Concurrent/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(TLBtree) 2 | 3 | cmake_minimum_required(VERSION 3.16) 4 | 5 | add_compile_options(-mclwb -fmax-errors=5 -fopenmp) 6 | add_compile_options(-O3) 7 | link_libraries(/usr/lib/x86_64-linux-gnu/libpmemobj.so) 8 | add_link_options(-pthread -fopenmp) 9 | 10 | include_directories(include) 11 | 12 | add_subdirectory(src) 13 | add_subdirectory(test) -------------------------------------------------------------------------------- /Concurrent/include/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #ifndef __COMMON_H__ 6 | #define __COMMON_H__ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define LOADSCALE 8 14 | 15 | #define KILO 1024 16 | #define MILLION (KILO * KILO) 17 | #define CACHE_LINE_SIZE 64 18 | 19 | #define DOFLUSH 20 | 21 | #ifndef KEYTYPE 22 | using _key_t = int64_t; 23 | #else 24 | using _key_t = KEYTYPE; 25 | #endif 26 | 27 | const _key_t MAX_KEY = std::numeric_limits<_key_t>::max(); 28 | const _key_t MIN_KEY = typeid(_key_t) == typeid(double) || typeid(_key_t) == typeid(float) 29 | ? -1 * MAX_KEY : std::numeric_limits<_key_t>::min(); 30 | 31 | struct Record { 32 | _key_t key; 33 | char * val; 34 | Record(_key_t k=MAX_KEY, char * v=NULL) : key(k), val(v) {} 35 | bool operator < (const Record & other) { 36 | return key < other.key; 37 | } 38 | }; 39 | 40 | enum OperationType {READ = 0, INSERT, UPDATE, DELETE}; 41 | 42 | struct QueryType { 43 | OperationType op; 44 | int64_t key; 45 | }; 46 | 47 | struct res_t { // a result type use to pass info when split and search 48 | bool flag; 49 | Record rec; 50 | res_t(bool f, Record e):flag(f), rec(e) {} 51 | }; 52 | 53 | #include 54 | inline double seconds() 55 | { 56 | timeval now; 57 | gettimeofday(&now, NULL); 58 | return now.tv_sec + now.tv_usec/1000000.0; 59 | } 60 | 61 | inline int getRandom() { 62 | timeval now; 63 | gettimeofday(&now, NULL); 64 | return now.tv_usec; 65 | } 66 | 67 | inline bool file_exist(const char *pool_path) { 68 | struct stat buffer; 69 | return (stat(pool_path, &buffer) == 0); 70 | } 71 | 72 | #endif //__COMMON_H__ -------------------------------------------------------------------------------- /Concurrent/include/tlbtree.h: -------------------------------------------------------------------------------- 1 | #ifndef __TLBTREE_H__ 2 | #define __TLBTREE_H__ 3 | 4 | #include "../src/tlbtree_impl.h" 5 | 6 | using tlbtree::TLBtreeImpl; 7 | 8 | // configure the PMEM file and file size 9 | static constexpr uint64_t POOL_SIZE = 512UL * 1024 * 1024; 10 | 11 | class TLBtree { 12 | public: 13 | TLBtree(std::string tlbname, uint64_t poolsize = POOL_SIZE) { 14 | bool recover = file_exist(tlbname.c_str()); 15 | tree_ = new TLBtreeImpl<2,2>(tlbname, recover, poolsize); 16 | } 17 | 18 | ~TLBtree() { 19 | delete tree_; 20 | } 21 | 22 | inline void insert(_key_t key, uint64_t val) { 23 | tree_->insert(key, val); 24 | } 25 | 26 | inline bool update(_key_t key, uint64_t val) { 27 | return tree_->update(key, val); 28 | } 29 | 30 | inline uint64_t lookup(_key_t key) { 31 | uint64_t val; 32 | bool found = tree_->find(key, val); 33 | 34 | if(found) 35 | return val; 36 | else 37 | return 0; 38 | } 39 | 40 | inline bool remove(_key_t key) { 41 | return tree_->remove(key); 42 | } 43 | 44 | private: 45 | TLBtreeImpl <2,2> * tree_; 46 | }; 47 | 48 | #endif //__TLBTREE_H__ -------------------------------------------------------------------------------- /Concurrent/src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(tlbtree tlbtree_impl.cc wotree256.cc) -------------------------------------------------------------------------------- /Concurrent/src/fixtree.h: -------------------------------------------------------------------------------- 1 | /* fixtree.h - A search-optimized fixed tree 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | 6 | #ifndef __FIXTREE__ 7 | #define __FIXTREE__ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "flush.h" 17 | #include "pmallocator.h" 18 | 19 | namespace fixtree { 20 | const int INNER_CARD = 32; // node size: 256B, the fanout of inner node is 32 21 | const int LEAF_CARD = 15; // node size: 256B, the fanout of leaf node is 16 22 | const int LEAF_REBUILD_CARD = 8; 23 | const int MAX_HEIGHT = 10; 24 | 25 | // the entrance of fixtree that stores its persistent tree metadata 26 | struct entrance_t { 27 | void * leaf_buff; 28 | void * inner_buff; 29 | uint32_t height; // the tree height 30 | uint32_t leaf_cnt; 31 | }; 32 | 33 | /* Fixtree: 34 | a search-optimized linearize tree structure which can absort moderate insertions: 35 | */ 36 | class Fixtree { 37 | public: 38 | struct INNode { // inner node is packed keys, which is very compact 39 | _key_t keys[INNER_CARD]; 40 | } __attribute__((aligned(CACHE_LINE_SIZE))); 41 | 42 | struct LFNode { // leaf node is packed key-ptr along with a header. 43 | // leaf node has some gap to absort insert 44 | Spinlock mtx; 45 | uint64_t node_version; 46 | _key_t keys[LEAF_CARD]; 47 | char * vals[LEAF_CARD]; 48 | } __attribute__((aligned(CACHE_LINE_SIZE))); 49 | 50 | public: 51 | // volatile structures 52 | INNode * inner_nodes_; 53 | LFNode * leaf_nodes_; 54 | uint32_t height_; 55 | uint32_t leaf_cnt_; 56 | entrance_t * entrance_; 57 | uint32_t level_offset_[MAX_HEIGHT]; 58 | 59 | public: 60 | Fixtree(entrance_t * ent) { // recovery the tree from the entrance 61 | inner_nodes_ = (INNode *)galc->absolute(ent->inner_buff); 62 | leaf_nodes_ = (LFNode *)galc->absolute(ent->leaf_buff); 63 | height_ = ent->height; 64 | leaf_cnt_ = ent->leaf_cnt; 65 | entrance_ = ent; 66 | 67 | uint32_t tmp = 0; 68 | for(int l = 0; l < height_; l++) { 69 | level_offset_[l] = tmp; 70 | tmp += std::pow(INNER_CARD, l); 71 | } 72 | level_offset_[height_] = tmp; 73 | } 74 | 75 | Fixtree(std::vector records) { 76 | const int lfary = LEAF_REBUILD_CARD; 77 | int record_count = records.size(); 78 | 79 | uint32_t lfnode_cnt = std::ceil((float)record_count / lfary); 80 | leaf_nodes_ = (LFNode *) galc->malloc(std::max((size_t)4096, lfnode_cnt * sizeof(LFNode))); 81 | 82 | height_ = std::ceil(std::log(std::max((uint32_t)INNER_CARD, lfnode_cnt)) / std::log(INNER_CARD)); 83 | uint32_t innode_cnt = (std::pow(INNER_CARD, height_) - 1) / (INNER_CARD - 1); 84 | inner_nodes_ = (INNode *) galc->malloc(std::max((size_t)4096, innode_cnt * sizeof(INNode))); 85 | 86 | // fill leaf nodes 87 | for(int i = 0; i < lfnode_cnt; i++) { 88 | for(int j = 0; j < lfary; j++) { 89 | auto idx = i * lfary + j; 90 | leaf_nodes_[i].keys[j] = idx < record_count ? records[idx].key : MAX_KEY; 91 | leaf_nodes_[i].vals[j] = idx < record_count ? records[idx].val : 0; 92 | } 93 | for(int j = lfary; j < LEAF_CARD; j++) { // intialized key 94 | leaf_nodes_[i].keys[j] = MAX_KEY; 95 | } 96 | clwb(leaf_nodes_ + i, sizeof(LFNode)); 97 | } 98 | 99 | int cur_level_cnt = lfnode_cnt; 100 | int cur_level_off = innode_cnt - std::pow(INNER_CARD, height_ - 1); 101 | int last_level_off = 0; 102 | 103 | // fill parent innodes of leaf nodes 104 | for(int i = 0; i < cur_level_cnt; i++) 105 | inner_insert(cur_level_off + i / INNER_CARD, i % INNER_CARD, leaf_nodes_[i].keys[0]); 106 | if(cur_level_cnt % INNER_CARD) 107 | inner_insert(cur_level_off + cur_level_cnt / INNER_CARD, cur_level_cnt % INNER_CARD, MAX_KEY); 108 | clwb(&inner_nodes_[cur_level_off], sizeof(INNode) * (cur_level_cnt / INNER_CARD + 1)); 109 | 110 | cur_level_cnt = std::ceil((float)cur_level_cnt / INNER_CARD); 111 | last_level_off = cur_level_off; 112 | cur_level_off = cur_level_off - std::pow(INNER_CARD, height_ - 2); 113 | 114 | // fill other inner nodes 115 | for(int l = height_ - 2; l >= 0; l--) { // level by level 116 | for(int i = 0; i < cur_level_cnt; i++) 117 | inner_insert(cur_level_off + i / INNER_CARD, i % INNER_CARD, inner_nodes_[last_level_off + i].keys[0]); 118 | if(cur_level_cnt % INNER_CARD) 119 | inner_insert(cur_level_off + cur_level_cnt / INNER_CARD, cur_level_cnt % INNER_CARD, MAX_KEY); 120 | clwb(&inner_nodes_[cur_level_off], sizeof(INNode) * (cur_level_cnt / INNER_CARD + 1)); 121 | 122 | cur_level_cnt = std::ceil((float)cur_level_cnt / INNER_CARD); 123 | last_level_off = cur_level_off; 124 | cur_level_off = cur_level_off - std::pow(INNER_CARD, l - 1); 125 | } 126 | 127 | leaf_cnt_ = lfnode_cnt; 128 | entrance_ = (entrance_t *)galc->malloc(4096); // the allocator is not thread_safe, allocate a large entrance 129 | uint32_t tmp = 0; 130 | for(int l = 0; l < height_; l++) { 131 | level_offset_[l] = tmp; 132 | tmp += std::pow(INNER_CARD, l); 133 | } 134 | level_offset_[height_] = tmp; 135 | 136 | persist_assign(&(entrance_->leaf_buff), (void *) galc->relative(leaf_nodes_)); 137 | persist_assign(&(entrance_->inner_buff), (void *) galc->relative(inner_nodes_)); 138 | persist_assign(&(entrance_->height), height_); 139 | persist_assign(&(entrance_->leaf_cnt), lfnode_cnt); 140 | 141 | return ; 142 | } 143 | 144 | public: 145 | char ** find_lower(_key_t key) const { 146 | /* linear search, return the position of the stored value */ 147 | int cur_idx = level_offset_[0]; 148 | for(int l = 0; l < height_; l++) { 149 | #ifdef DEBUG 150 | INNode * inner = inner_nodes_ + cur_idx; 151 | #endif 152 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 153 | } 154 | cur_idx -= level_offset_[height_]; 155 | 156 | return leaf_search(cur_idx, key); 157 | } 158 | 159 | bool insert(_key_t key, uint64_t val) { 160 | uint32_t cur_idx = level_offset_[0]; 161 | for(int l = 0; l < height_; l++) { 162 | #ifdef DEBUG 163 | INNode * inner = inner_nodes_ + cur_idx; 164 | #endif 165 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 166 | } 167 | cur_idx -= level_offset_[height_]; 168 | 169 | LFNode * cur_leaf = leaf_nodes_ + cur_idx; 170 | 171 | for(int i = 0; i < LEAF_CARD; i++) { 172 | if (cur_leaf->keys[i] == MAX_KEY) { // empty slot 173 | cur_leaf->mtx.lock(); 174 | leaf_insert(cur_idx, i, {key, (char *)val}); 175 | cur_leaf->node_version++; 176 | cur_leaf->mtx.unlock(); 177 | return true; 178 | } 179 | } 180 | return false; 181 | } 182 | 183 | bool try_remove(_key_t key) { 184 | int cur_idx = level_offset_[0]; 185 | for(int l = 0; l < height_; l++) { 186 | #ifdef DEBUG 187 | INNode * inner = inner_nodes_ + cur_idx; 188 | #endif 189 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 190 | } 191 | cur_idx -= level_offset_[height_]; 192 | 193 | LFNode * cur_leaf = leaf_nodes_ + cur_idx; 194 | 195 | cur_leaf->mtx.lock(); 196 | 197 | _key_t max_leqkey = cur_leaf->keys[0]; 198 | int8_t max_leqi = 0; 199 | int8_t rec_cnt = 1; 200 | for(int i = 1; i < LEAF_CARD; i++) { 201 | if(cur_leaf->keys[i] != MAX_KEY) { 202 | rec_cnt += 1; 203 | if (cur_leaf->keys[i] <= key && cur_leaf->keys[i] > max_leqkey) { 204 | max_leqkey = cur_leaf->keys[i]; 205 | max_leqi = i; 206 | } 207 | } 208 | } 209 | 210 | /* There are three cases: 211 | 1. | k1 | --- | kx |, delete k1, leaf is not empty if k1 is deleted (fail) 212 | 2. | k1 | --- |, delete k1, leaf is empty if k1 is deleted (success) 213 | 3. | k1 | --- | kx |, delete kx, leaf is not empty if kx is deleted (success) 214 | */ 215 | if(max_leqi == 0 && rec_cnt > 1) { // case 1 216 | cur_leaf->mtx.unlock(); 217 | return false; 218 | } else { // case 2, 3 219 | persist_assign(&(cur_leaf->keys[max_leqi]), MAX_KEY); 220 | 221 | cur_leaf->node_version++; 222 | cur_leaf->mtx.unlock(); 223 | return true; 224 | } 225 | } 226 | 227 | void printAll() { 228 | for(int l = 0; l < height_; l++) { 229 | printf("level: %d =>", l); 230 | 231 | for(int i = level_offset_[l]; i < level_offset_[l + 1]; i++) { 232 | inner_print(i); 233 | } 234 | printf("\n"); 235 | } 236 | 237 | printf("leafs"); 238 | 239 | for(int i = 0; i < leaf_cnt_; i++) { 240 | leaf_print(i); 241 | } 242 | } 243 | 244 | char ** find_first() { 245 | return (char **)&(leaf_nodes_[0].vals[0]); 246 | } 247 | 248 | void merge(std::vector & in, std::vector & out) { // merge the records with in to out 249 | uint32_t insize = in.size(); 250 | 251 | uint32_t incur = 0, innode_pos = 0, cur_lfcnt = 0; 252 | Record tmp[LEAF_CARD]; 253 | load_node(tmp, &leaf_nodes_[0]); 254 | _key_t k1 = in[0].key, k2 = tmp[0].key; 255 | while(incur < insize && cur_lfcnt < leaf_cnt_) { 256 | if(k1 == k2) { 257 | out.push_back(in[incur]); 258 | 259 | incur += 1; 260 | innode_pos += 1; 261 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 262 | cur_lfcnt += 1; 263 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 264 | innode_pos = 0; 265 | } 266 | 267 | k1 = in[incur].key; 268 | k2 = tmp[innode_pos].key; 269 | } else if(k1 > k2) { 270 | out.push_back(tmp[innode_pos]); 271 | 272 | innode_pos += 1; 273 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 274 | cur_lfcnt += 1; 275 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 276 | innode_pos = 0; 277 | } 278 | 279 | k2 = tmp[innode_pos].key;; 280 | } else { 281 | out.push_back(in[incur]); 282 | 283 | incur += 1; 284 | k1 = in[incur].key; 285 | } 286 | } 287 | 288 | if(incur < insize) { 289 | for(int i = incur; i < insize; i++) 290 | out.push_back(in[i]); 291 | } 292 | 293 | if(cur_lfcnt < leaf_cnt_) { 294 | while(cur_lfcnt < leaf_cnt_) { 295 | out.push_back(tmp[innode_pos]); 296 | 297 | innode_pos += 1; 298 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 299 | cur_lfcnt += 1; 300 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 301 | innode_pos = 0; 302 | } 303 | } 304 | } 305 | } 306 | 307 | private: 308 | int inner_search(int node_idx, _key_t key) const{ 309 | INNode * cur_inner = inner_nodes_ + node_idx; 310 | for(int i = 0; i < INNER_CARD; i++) { 311 | if (cur_inner->keys[i] > key) { 312 | return i - 1; 313 | } 314 | } 315 | 316 | return INNER_CARD - 1; 317 | } 318 | 319 | char **leaf_search(int node_idx, _key_t key) const { 320 | LFNode * cur_leaf = leaf_nodes_ + node_idx; 321 | 322 | retry: 323 | auto old_version = cur_leaf->node_version; 324 | 325 | _key_t max_leqkey = cur_leaf->keys[0]; 326 | int8_t max_leqi = 0; 327 | for(int i = 1; i < LEAF_CARD; i++) { 328 | if (cur_leaf->keys[i] <= key && cur_leaf->keys[i] > max_leqkey) { 329 | max_leqkey = cur_leaf->keys[i]; 330 | max_leqi = i; 331 | } 332 | } 333 | 334 | if (old_version != cur_leaf->node_version) goto retry; 335 | 336 | return (char **) &(cur_leaf->vals[max_leqi]); 337 | } 338 | 339 | void leaf_insert(int node_idx, int off, Record rec) { // TODO: should do it in a CAS way 340 | leaf_nodes_[node_idx].vals[off] = rec.val; 341 | clwb(&leaf_nodes_[node_idx].vals[off], 8); 342 | mfence(); 343 | 344 | leaf_nodes_[node_idx].keys[off] = rec.key; 345 | clwb(&leaf_nodes_[node_idx].keys[off], 8); 346 | mfence(); 347 | } 348 | 349 | inline void inner_insert(int node_idx, int off, _key_t key) { 350 | inner_nodes_[node_idx].keys[off] = key; 351 | } 352 | 353 | void inner_print(int node_idx) { 354 | printf("("); 355 | for(int i = 0; i < INNER_CARD; i++) { 356 | printf("%lu ", inner_nodes_[node_idx].keys[i]); 357 | } 358 | printf(") "); 359 | } 360 | 361 | void leaf_print(int node_idx) { 362 | printf("("); 363 | for(int i = 0; i < LEAF_CARD; i++) { 364 | printf("[%lu, %lu] ", leaf_nodes_[node_idx].keys[i], (long unsigned int)leaf_nodes_[node_idx].vals[i]); 365 | } 366 | printf(") \n"); 367 | } 368 | 369 | static void load_node(Record * to, LFNode * from) { 370 | for(int i = 0; i < LEAF_CARD; i++) { 371 | to[i].key = from->keys[i]; 372 | to[i].val = from->vals[i]; 373 | } 374 | 375 | std::sort(to, to + LEAF_CARD); 376 | } 377 | }; 378 | 379 | inline entrance_t * get_entrance(Fixtree * tree) { 380 | return tree->entrance_; 381 | } 382 | 383 | inline void free(Fixtree * tree) { 384 | entrance_t * upent = get_entrance(tree); 385 | delete tree; 386 | 387 | galc->free(galc->absolute(upent->inner_buff)); 388 | galc->free(galc->absolute(upent->leaf_buff)); 389 | galc->free(upent); 390 | 391 | return ; 392 | } 393 | 394 | typedef Fixtree uptree_t; 395 | 396 | } // namespace fixtree 397 | 398 | #endif //__FIXTREE__ -------------------------------------------------------------------------------- /Concurrent/src/flush.h: -------------------------------------------------------------------------------- 1 | #ifndef __FLUSH_H__ 2 | #define __FLUSH_H__ 3 | 4 | #include 5 | 6 | #include "common.h" 7 | 8 | static inline void mfence() { 9 | asm volatile("sfence" ::: "memory"); 10 | } 11 | 12 | static inline void flush(void * ptr) { 13 | #ifdef CLWB 14 | _mm_clwb(ptr); 15 | #elif defined(CLFLUSHOPT) 16 | _mm_clflushopt(ptr); 17 | #else 18 | _mm_clflush(ptr); 19 | #endif 20 | } 21 | 22 | inline void clwb(void *data, int len) { 23 | #ifdef DOFLUSH 24 | volatile char *ptr = (char *)((unsigned long long)data &~(CACHE_LINE_SIZE-1)); 25 | for(; ptr < (char *)data + len; ptr += CACHE_LINE_SIZE) { 26 | flush((void *)ptr); 27 | } 28 | #endif //DOFLUSH 29 | } 30 | 31 | inline void clflush(void *data, int len, bool fence=true) 32 | { 33 | #ifdef DOFLUSH 34 | volatile char *ptr = (char *)((unsigned long long)data &~(CACHE_LINE_SIZE-1)); 35 | if(fence) mfence(); 36 | for(; ptr < (char *)data + len; ptr += CACHE_LINE_SIZE){ 37 | flush((void *)ptr); 38 | } 39 | if(fence) mfence(); 40 | #endif //DOFLUSH 41 | } 42 | 43 | template 44 | inline void persist_assign(T* addr, const T &v) { // To ensure atomicity, the size of T should be less equal than 8 45 | *addr = v; 46 | clwb(addr, sizeof(T)); 47 | } 48 | 49 | #endif // __FLUSH_H__ -------------------------------------------------------------------------------- /Concurrent/src/pmallocator.h: -------------------------------------------------------------------------------- 1 | /* 2 | A wrapper for using PMDK allocator easily (refer to pmwcas) 3 | Copyright (c) Luo Yongping All Rights Reserved! 4 | */ 5 | 6 | #ifndef __BLKALLOCATOR_H__ 7 | #define __BLKALLOCATOR_H__ 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "common.h" 14 | #include "flush.h" 15 | #include "spinlock.h" 16 | 17 | POBJ_LAYOUT_BEGIN(pmallocator); 18 | POBJ_LAYOUT_TOID(pmallocator, char) 19 | POBJ_LAYOUT_END(pmallocator) 20 | 21 | /* 22 | Persistent Memory Allocator: a wrapper of PMDK allocation lib: https://pmem.io/pmdk/ 23 | 24 | PMAllocator allocates persistent memory from a pool file that resides on NVM file system. 25 | It uses malloc() and free() as the allocation and reclaiment interfaces. 26 | Other public interfaces like get_root(), absolute() and relative() are essential to memory 27 | management in persistent environment. 28 | */ 29 | class PMAllocator { 30 | private: 31 | static const int PEICE_CNT = 64; 32 | static const size_t ALIGN_SIZE = 256; 33 | 34 | struct MetaType { 35 | char * buffer[PEICE_CNT]; 36 | size_t blk_per_piece; 37 | size_t cur_blk; 38 | // entrance of DS in buffer 39 | void * entrance; 40 | }; 41 | MetaType * meta_; 42 | 43 | // volatile domain 44 | PMEMobjpool *pop_; 45 | 46 | char * buff_[PEICE_CNT]; 47 | char * buff_aligned_[PEICE_CNT]; 48 | size_t piece_size_; 49 | size_t max_blk_; 50 | Spinlock alloc_mtx; 51 | 52 | public: 53 | /* 54 | * Construct a PM allocator, map a pool file into virtual memory 55 | * @param filename pool file name 56 | * @param recover if doing recover, false for the first time 57 | * @param layout_name ID of a group of allocations (in characters), each ID corresponding to a root entry 58 | * @param pool_size pool size of the pool file, vaild if the file doesn't exist 59 | */ 60 | PMAllocator(const char *file_name, bool recover, const char *layout_name, uint64_t pool_size) { 61 | PMEMobjpool *tmp_pool = nullptr; 62 | pool_size = pool_size + ((pool_size & ((1 << 23) - 1)) > 0 ? (1 << 23) : 0); // align to 8MB 63 | if(recover == false) { 64 | if(file_exist(file_name)) { 65 | printf("[CAUTIOUS]: The pool file already exists\n"); 66 | printf("Try (1) remove the pool file %s\nOr (2) set the recover parameter to be true\n", file_name); 67 | exit(-1); 68 | } 69 | pop_ = pmemobj_create(file_name, layout_name, pool_size, S_IWUSR | S_IRUSR); 70 | meta_ = (MetaType *)pmemobj_direct(pmemobj_root(pop_, sizeof(MetaType))); 71 | 72 | // maintain volatile domain 73 | uint64_t alloc_size = (pool_size >> 1) + (pool_size >> 2) + (pool_size >> 3); // 7/8 of the pool is used as block alloction 74 | for(int i = 0; i < PEICE_CNT; i++) { 75 | buff_[i] = (char *)mem_alloc(alloc_size / PEICE_CNT); 76 | buff_aligned_[i] = (char *) ((uint64_t)buff_[i] + ((uint64_t) buff_[i] % ALIGN_SIZE == 0 ? 0 : (ALIGN_SIZE - (uint64_t) buff_[i] % ALIGN_SIZE))); 77 | } 78 | piece_size_ = (alloc_size / PEICE_CNT) / ALIGN_SIZE - 1; 79 | max_blk_ = piece_size_ * PEICE_CNT; 80 | 81 | // initialize meta_ 82 | for(int i = 0; i < PEICE_CNT; i++) 83 | meta_->buffer[i] = relative(buff_[i]); 84 | meta_->blk_per_piece = piece_size_; 85 | meta_->cur_blk = 0; 86 | meta_->entrance = NULL; 87 | clwb(meta_, sizeof(MetaType)); 88 | } else { 89 | if(!file_exist(file_name)) { 90 | printf("Pool File Not Exist\n"); 91 | exit(-1); 92 | } 93 | pop_ = pmemobj_open(file_name, layout_name); 94 | meta_ = (MetaType *)pmemobj_direct(pmemobj_root(pop_, sizeof(MetaType))); 95 | // maintain volatile domain 96 | for(int i = 0; i < PEICE_CNT; i++) { 97 | buff_[i] = absolute(meta_->buffer[i]); 98 | buff_aligned_[i] = (char *) ((uint64_t)buff_[i] + ((uint64_t) buff_[i] % ALIGN_SIZE == 0 ? 0 : (ALIGN_SIZE - (uint64_t) buff_[i] % ALIGN_SIZE))); 99 | } 100 | piece_size_ = meta_->blk_per_piece; 101 | max_blk_ = piece_size_ * PEICE_CNT; 102 | } 103 | } 104 | 105 | ~PMAllocator() { 106 | pmemobj_close(pop_); 107 | } 108 | 109 | public: 110 | /* 111 | * Get/allocate the root entry of the allocator. 112 | * 113 | * The root entry is the entrance of one group of allocation, each group is 114 | * identified by the layout_name when constructing it. 115 | * 116 | * Each group of allocations is a independent, self-contained in-memory structure in the pool 117 | * such as b-tree or link-list 118 | */ 119 | void * get_root(size_t nsize) { // the root of DS stored in buff_ is recorded at meta_->entrance 120 | if(meta_->entrance == NULL) { 121 | meta_->entrance = relative(malloc(nsize)); 122 | clwb(meta_, sizeof(MetaType)); 123 | } 124 | return absolute(meta_->entrance); 125 | } 126 | 127 | /* 128 | * Allocate a non-root piece of persistent memory from the mapped pool 129 | * return the virtual memory address 130 | */ 131 | void * malloc(size_t nsize) { 132 | if(nsize >= (1 << 12)) { // large than 4KB, make sure it is atomic 133 | void * mem = mem_alloc(nsize + ALIGN_SIZE); // not aligned 134 | // | UNUSED |HEADER| memory you can use | 135 | // mem (mem + off) 136 | uint64_t offset = ALIGN_SIZE - (uint64_t)mem % ALIGN_SIZE; 137 | // store a header in the front 138 | uint64_t * header = (uint64_t *)((uint64_t)mem + offset - 8); 139 | *header = offset; 140 | 141 | return (void *)((uint64_t)mem + offset); 142 | } 143 | 144 | retry_malloc: 145 | uint64_t old_cur_blk = meta_->cur_blk; 146 | 147 | int blk_demand = (nsize + ALIGN_SIZE - 1) / ALIGN_SIZE; 148 | // case 1: not enough in the buffer 149 | if(blk_demand + meta_->cur_blk > max_blk_) { 150 | printf("run out of memory\n"); 151 | exit(-1); 152 | } 153 | // case 2: current piece can not accommdate this allocation 154 | int piece_id = meta_->cur_blk / piece_size_; 155 | if((meta_->cur_blk % piece_size_ + blk_demand) > piece_size_) { 156 | void * mem = buff_aligned_[piece_id + 1]; // allocate from a new peice 157 | 158 | uint64_t new_cur_blk = piece_size_ * (piece_id + 1) + blk_demand; 159 | if(__sync_bool_compare_and_swap(&(meta_->cur_blk), old_cur_blk, new_cur_blk) == false) 160 | goto retry_malloc; 161 | clwb(&(meta_->cur_blk), 8); 162 | 163 | return mem; 164 | } 165 | // case 3: current piece has enough space 166 | else { 167 | void * mem = buff_aligned_[piece_id] + ALIGN_SIZE * (meta_->cur_blk % piece_size_); 168 | 169 | uint64_t new_cur_blk = old_cur_blk + blk_demand; 170 | if(__sync_bool_compare_and_swap(&(meta_->cur_blk), old_cur_blk, new_cur_blk) == false) 171 | goto retry_malloc; 172 | clwb(&(meta_->cur_blk), 8); 173 | 174 | return mem; 175 | } 176 | } 177 | 178 | void free(void* addr) { 179 | for(int i = 0; i < PEICE_CNT; i++) { 180 | uint64_t offset = (uint64_t)addr - (uint64_t)buff_aligned_[i]; 181 | if(offset > 0 && offset < piece_size_ * ALIGN_SIZE) { 182 | // the addr is in this piece, do not reclaim it 183 | return ; 184 | } 185 | } 186 | 187 | // larger than 4KB, reclaim it 188 | uint64_t * header = (uint64_t *)((uint64_t)addr - 8); 189 | uint64_t offset = *header; 190 | 191 | alloc_mtx.lock(); 192 | auto oid_ptr = pmemobj_oid((void *)((uint64_t)addr - offset)); 193 | alloc_mtx.unlock(); 194 | 195 | TOID(char) ptr_cpy; 196 | TOID_ASSIGN(ptr_cpy, oid_ptr); 197 | POBJ_FREE(&ptr_cpy); 198 | } 199 | 200 | /* 201 | * Distinguish from virtual memory address and offset in the pool 202 | * Each memory piece allocated from the pool has an in-pool offset, which remains unchanged 203 | * until reclaiment. We cannot ensure that the pool file is mapped at the same position at 204 | * any time, so it may locate at different virtual memory addresses next time. 205 | * 206 | * So the rule is that, using virtual memory when doing normal operations like to DRAM 207 | * space, using offset to store link relationship, for exmaple, next pointer in linklist 208 | * / 209 | 210 | /* 211 | * convert the virtual memory address to an offset 212 | */ 213 | template 214 | inline T *absolute(T *pmem_offset) { 215 | if(pmem_offset == NULL) 216 | return NULL; 217 | return reinterpret_cast(reinterpret_cast(pmem_offset) + reinterpret_cast(pop_)); 218 | } 219 | 220 | template 221 | inline T *relative(T *pmem_direct) { 222 | if(pmem_direct == NULL) 223 | return NULL; 224 | return reinterpret_cast(reinterpret_cast(pmem_direct) - reinterpret_cast(pop_)); 225 | } 226 | 227 | private: 228 | void * mem_alloc(size_t nsize) { 229 | PMEMoid tmp; 230 | 231 | alloc_mtx.lock(); 232 | pmemobj_alloc(pop_, &tmp, nsize, TOID_TYPE_NUM(char), NULL, NULL); 233 | alloc_mtx.unlock(); 234 | 235 | void * mem = pmemobj_direct(tmp); 236 | assert(mem != nullptr); 237 | return mem; 238 | } 239 | }; 240 | 241 | extern PMAllocator * galc; 242 | 243 | #endif // __BLKALLOCATOR_H__ 244 | -------------------------------------------------------------------------------- /Concurrent/src/spinlock.h: -------------------------------------------------------------------------------- 1 | /* Copyright(c): Guo Zhongming 2 | */ 3 | 4 | #ifndef __SPINLOCK_H__ 5 | #define __SPINLOCK_H__ 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | class Spinlock { 12 | public: 13 | Spinlock() { 14 | atomic_val.store(0, std::memory_order_relaxed); 15 | } 16 | 17 | Spinlock(const Spinlock &) = delete; 18 | Spinlock & operator = (const Spinlock &) = delete; 19 | 20 | public: 21 | inline void lock() { 22 | while(atomic_val.exchange(1, std::memory_order_acquire) == 1){ 23 | while(1) { 24 | _mm_pause(); // delay for 140 cycle 25 | 26 | if(atomic_val.load(std::memory_order_relaxed) == 0) // check the atomic_val 27 | break; 28 | 29 | std::this_thread::yield(); // delay for 113ns 30 | 31 | if(atomic_val.load(std::memory_order_relaxed) == 0) // check the atomic_val 32 | break; 33 | } 34 | 35 | // if at here, the atomic_val must be just be 0 36 | } 37 | 38 | return ; 39 | } 40 | 41 | inline void unlock() { 42 | atomic_val.exchange(0, std::memory_order_acquire); 43 | } 44 | 45 | inline bool trylock() { 46 | return atomic_val.exchange(1, std::memory_order_acquire) == 0; 47 | } 48 | 49 | private: 50 | std::atomic_short atomic_val; 51 | }; 52 | 53 | #endif // __SPINLOCK_H__ -------------------------------------------------------------------------------- /Concurrent/src/tlbtree_impl.cc: -------------------------------------------------------------------------------- 1 | #include "tlbtree_impl.h" 2 | 3 | PMAllocator * galc; -------------------------------------------------------------------------------- /Concurrent/src/tlbtree_impl.h: -------------------------------------------------------------------------------- 1 | /* tlbtree.h - A two level btree for persistent memory 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | 6 | #ifndef __TLBTREEIMPL_H__ 7 | #define __TLBTREEIMPL_H__ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "pmallocator.h" 15 | #include "fixtree.h" 16 | #include "spinlock.h" 17 | #include "wotree256.h" 18 | 19 | extern PMAllocator * galc; 20 | 21 | #define BACKGROUND_REBUILD 22 | // choose uptree type, providing interfaces: insert, remove, update, find, merge, free_uptree 23 | #define UPTREE_NS fixtree 24 | // choose downtree type, providing interfaces: insert, find_lower, remove_lower 25 | #define DOWNTREE_NS wotree256 26 | 27 | namespace tlbtree { 28 | 29 | using std::string; 30 | using std::vector; 31 | using Node = DOWNTREE_NS::Node; 32 | 33 | template 34 | class TLBtreeImpl { 35 | private: 36 | typedef TLBtreeImpl SelfType; 37 | 38 | // the entrance of TLBtree that stores its persistent tree metadata 39 | struct tlbtree_entrance_t { 40 | UPTREE_NS::entrance_t * upent; // the entrance of the top layer 41 | Record * restore; // restore subroots that fails to insert into the top layer 42 | int restore_size; 43 | bool is_clean; // is TLBtree shutdown expectedly 44 | bool use_rebuild_recover; // whether to use recover rebuilding next time 45 | }; 46 | 47 | // volatile domain 48 | UPTREE_NS::uptree_t * uptree_; 49 | tlbtree_entrance_t * entrance_; 50 | vector * mutable_; 51 | Spinlock rebuild_mtx_; 52 | Spinlock mutable_mtx_; 53 | bool is_rebuilding_; 54 | 55 | public: 56 | TLBtreeImpl(string path, bool recover=true, uint64_t pool_size=10 * (1024UL * 1024 * 1024)); 57 | 58 | ~TLBtreeImpl(); 59 | 60 | void insert(const _key_t & k, uint64_t v); 61 | 62 | bool find(const _key_t & k, uint64_t & v) const ; 63 | 64 | bool update(const _key_t & k, const uint64_t & v); 65 | 66 | bool remove(const _key_t & k); 67 | 68 | inline void printAll() { uptree_->printAll();} 69 | 70 | private: 71 | void rebuild_fast(); 72 | 73 | void rebuild_recover(); 74 | }; 75 | 76 | template 77 | TLBtreeImpl::TLBtreeImpl(string path, bool recover, uint64_t pool_size) { 78 | mutable_ = new vector(); 79 | mutable_->reserve(0xfff); 80 | bool is_rebuilding_ = false; 81 | 82 | if(recover == false) { 83 | galc = new PMAllocator(path.c_str(), false, "tlbtree", pool_size); 84 | // initialize entrance_ 85 | entrance_ = (tlbtree_entrance_t *) galc->get_root(sizeof(tlbtree_entrance_t)); 86 | entrance_->upent = NULL; 87 | entrance_->restore = NULL; 88 | entrance_->restore_size = 0; 89 | entrance_->is_clean = false; 90 | entrance_->use_rebuild_recover = true; 91 | clwb(entrance_, sizeof(tlbtree_entrance_t)); 92 | 93 | //allocate a entrance_ to the fixtree 94 | std::vector init = {Record(MIN_KEY, (char *)galc->relative(new Node()))}; 95 | uptree_ = new UPTREE_NS::uptree_t(init); 96 | persist_assign(&(entrance_->upent), galc->relative(UPTREE_NS::get_entrance(uptree_))); 97 | persist_assign(&(entrance_->use_rebuild_recover), false); // use fast rebuilding next time 98 | } else { 99 | galc = new PMAllocator(path.c_str(), true, "tlbtree", pool_size); 100 | 101 | entrance_ = (tlbtree_entrance_t *) galc->get_root(sizeof(tlbtree_entrance_t)); 102 | if(entrance_ == NULL || entrance_->upent == NULL) { // empty tree 103 | printf("the tree is empty\n"); 104 | exit(-1); 105 | } 106 | 107 | if(entrance_->is_clean == false) { // TLBtree crashed at last usage 108 | persist_assign(&(entrance_->use_rebuild_recover), true); // use recover rebuilding next time 109 | } else { // normal shutdown 110 | // recover all subroots from PM back to mutable_, within miliseconds 111 | if(entrance_->restore != NULL) { 112 | Record * rec = galc->absolute(entrance_->restore); 113 | for(int i = 0; i < entrance_->restore_size; i++) { 114 | mutable_->push_back(rec[i]); 115 | } 116 | entrance_->restore = NULL; 117 | entrance_->restore_size = 0; 118 | clwb(&entrance_->restore, 16); 119 | galc->free(rec); 120 | } 121 | } 122 | 123 | uptree_ = new UPTREE_NS::uptree_t (galc->absolute(entrance_->upent)); 124 | } 125 | 126 | persist_assign(&(entrance_->is_clean), false); // set the TLBtree state to be dirty 127 | } 128 | 129 | template 130 | TLBtreeImpl::~TLBtreeImpl() { 131 | if(entrance_->use_rebuild_recover == false) { // fast rebuilding next time 132 | // save all subroots in mutable_ into PM 133 | Record * rec = (Record *) galc->malloc(std::max((size_t)4096, mutable_->size() * sizeof(Record))); 134 | for(int i = 0; i < mutable_->size(); i++) { 135 | rec[i] = (*mutable_)[i]; 136 | } 137 | clwb(rec, mutable_->size() * sizeof(Record)); 138 | mfence(); 139 | entrance_->restore = galc->relative(rec); 140 | entrance_->restore_size = mutable_->size(); 141 | clwb(&entrance_->restore, 16); 142 | } 143 | 144 | //printf("%lx %d\n", entrance_->restore, entrance_->restore_size); 145 | 146 | persist_assign(&(entrance_->is_clean), true); // a intended shutdown 147 | 148 | delete uptree_; 149 | delete mutable_; 150 | delete galc; 151 | } 152 | 153 | template 154 | void TLBtreeImpl::insert(const _key_t & k, uint64_t v) { 155 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 156 | Node * downroot = (Node *)galc->absolute(*root_ptr); 157 | 158 | // travese in sibling chain 159 | int8_t goes_steps = 0; 160 | _key_t splitkey; Node ** sibling_ptr; 161 | downroot->get_sibling(splitkey, sibling_ptr); 162 | while(splitkey < k) { // the splitkey 163 | root_ptr = sibling_ptr; // where is current root store 164 | downroot = (Node *)galc->absolute(*root_ptr); 165 | downroot->get_sibling(splitkey, sibling_ptr); 166 | goes_steps += 1; 167 | } 168 | res_t insert_res = DOWNTREE_NS::insert(root_ptr, k, v, DOWNLEVEL); 169 | 170 | // we rebuild if the searching in the linklist is too long 171 | if(goes_steps > REBUILD_THRESHOLD && rebuild_mtx_.trylock()) { 172 | if(entrance_->use_rebuild_recover == true) { 173 | #ifdef BACKGROUND_REBUILD 174 | std::thread rebuild_thread(&SelfType::rebuild_recover, this); 175 | rebuild_thread.detach(); 176 | #else 177 | rebuild_recover(); 178 | #endif 179 | } else { 180 | #ifdef BACKGROUND_REBUILD 181 | std::thread rebuild_thread(&SelfType::rebuild_fast, this); 182 | rebuild_thread.detach(); 183 | #else 184 | rebuild_fast(); 185 | #endif 186 | } 187 | } 188 | 189 | if(insert_res.flag == true) { // a sub-index tree is splitted 190 | // try save the sub-indices root into the top layer 191 | bool succ = uptree_->insert(insert_res.rec.key, (uint64_t)galc->relative(insert_res.rec.val)); 192 | 193 | // save these records into mutable_ 194 | if(is_rebuilding_ == true || succ == false) { 195 | mutable_mtx_.lock(); 196 | mutable_->push_back({insert_res.rec.key, (char *)galc->relative(insert_res.rec.val)}); 197 | mutable_mtx_.unlock(); 198 | } 199 | } 200 | } 201 | 202 | template 203 | bool TLBtreeImpl::find(const _key_t & k, uint64_t & v) const { 204 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 205 | Node * downroot = (Node *)galc->absolute(*root_ptr); 206 | 207 | // traverse in sibling chain 208 | _key_t splitkey; Node ** sibling_ptr; 209 | downroot->get_sibling(splitkey, sibling_ptr); 210 | while(splitkey <= k) { // the splitkey 211 | root_ptr = sibling_ptr; // where is current root store 212 | downroot = (Node *)galc->absolute(*root_ptr); 213 | downroot->get_sibling(splitkey, sibling_ptr); 214 | } 215 | 216 | return DOWNTREE_NS::find(root_ptr, k, v); 217 | } 218 | 219 | template 220 | bool TLBtreeImpl::remove(const _key_t & k) { 221 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 222 | Node ** last_root_ptr = NULL; // record the last root ptr for laster use 223 | Node *downroot = (Node *)galc->absolute(*root_ptr); 224 | 225 | // travese in sibling chain 226 | _key_t splitkey; Node ** sibling_ptr; 227 | downroot->get_sibling(splitkey, sibling_ptr); 228 | while(splitkey < k) { // the splitkey 229 | root_ptr = sibling_ptr; // where is current root store 230 | downroot = (Node *)galc->absolute(*root_ptr); 231 | downroot->get_sibling(splitkey, sibling_ptr); 232 | } 233 | 234 | bool emptyif = DOWNTREE_NS::remove(root_ptr, k); 235 | if(emptyif) { // the DOWNTREE_NS is empty now 236 | uptree_->try_remove(k); // TODO: rebuilding should also be triggered when the top layer is too empty 237 | } 238 | 239 | return true; 240 | } 241 | 242 | template 243 | bool TLBtreeImpl::update(const _key_t & k, const uint64_t & v) { 244 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 245 | Node * downroot = (Node *)galc->absolute(*root_ptr); 246 | 247 | // travese in sibling chain 248 | _key_t splitkey; Node ** sibling_ptr; 249 | downroot->get_sibling(splitkey, sibling_ptr); 250 | while(splitkey < k) { // the splitkey 251 | root_ptr = sibling_ptr; // where is current root store 252 | downroot = (Node *)galc->absolute(*root_ptr); 253 | downroot->get_sibling(splitkey, sibling_ptr); 254 | } 255 | 256 | return DOWNTREE_NS::update(root_ptr, k, v); 257 | } 258 | 259 | template 260 | void TLBtreeImpl::rebuild_fast() { // fast rebuilding function 261 | // switch the restore to be immutable 262 | vector * new_mutable = new vector; 263 | new_mutable->reserve(0xffff); 264 | 265 | mutable_mtx_.lock(); 266 | vector * immutable = mutable_; // make the restore vector be immutable 267 | mutable_ = new_mutable; // before this line, the mutable_ is still the old one 268 | mutable_mtx_.unlock(); 269 | 270 | is_rebuilding_ = true; 271 | 272 | std::sort(immutable->begin(), immutable->end()); 273 | // get the snapshot of all sub-index trees by combining the top layer with immutable 274 | std::vector subroots; 275 | subroots.reserve(0x2ffff); 276 | uptree_->merge(*immutable, subroots); 277 | 278 | /* rebuild the top layer with immutable */ 279 | UPTREE_NS::uptree_t * old_tree = uptree_; 280 | UPTREE_NS::entrance_t * old_upent = galc->absolute(entrance_->upent); 281 | UPTREE_NS::uptree_t * new_tree = new UPTREE_NS::uptree_t(subroots); 282 | UPTREE_NS::entrance_t * new_upent = UPTREE_NS::get_entrance(new_tree); 283 | 284 | // install the new top layer 285 | persist_assign(&(entrance_->upent), galc->relative(new_upent)); 286 | uptree_ = new_tree; 287 | 288 | /* free the old top layer */ 289 | #ifdef BACKGROUND_REBUILD 290 | usleep(50); // TODO: unsafe memory reclamation 291 | #endif 292 | UPTREE_NS::free(old_tree); // free the old_tree 293 | 294 | is_rebuilding_ = false; 295 | asm volatile("" ::: "memory"); 296 | rebuild_mtx_.unlock(); 297 | 298 | delete immutable; 299 | } 300 | 301 | template 302 | void TLBtreeImpl::rebuild_recover() { // slow rebuilding function 303 | is_rebuilding_ = true; 304 | // get the snapshot of all sub-index trees by traverse in the down layer 305 | std::vector subroots; 306 | subroots.reserve(0x2fffff); 307 | 308 | _key_t split_key = 0; 309 | Node ** sibling_ptr = (Node **)uptree_->find_first(); 310 | Node * cur_root = (Node *)galc->absolute(*sibling_ptr); 311 | while (cur_root != NULL) { 312 | subroots.emplace_back(split_key, (char *)(*sibling_ptr)); 313 | // get next sibling 314 | cur_root->get_sibling(split_key, sibling_ptr); 315 | cur_root = galc->absolute(*sibling_ptr); 316 | } 317 | 318 | /* rebuild the top layer with immutable */ 319 | UPTREE_NS::uptree_t * old_tree = uptree_; 320 | UPTREE_NS::entrance_t * old_upent = galc->absolute(entrance_->upent); 321 | UPTREE_NS::uptree_t * new_tree = new UPTREE_NS::uptree_t(subroots); 322 | UPTREE_NS::entrance_t * new_upent = UPTREE_NS::get_entrance(new_tree); 323 | 324 | // install the new top layer 325 | persist_assign(&(entrance_->upent), galc->relative(new_upent)); 326 | uptree_ = new_tree; 327 | 328 | /* free the old top layer */ 329 | #ifdef BACKGROUND_REBUILD 330 | usleep(50); // TODO: unsafe memory reclamation 331 | #endif 332 | UPTREE_NS::free(old_tree); // free the old_tree 333 | 334 | is_rebuilding_ = false; 335 | asm volatile("" ::: "memory"); 336 | rebuild_mtx_.unlock(); 337 | 338 | persist_assign(&(entrance_->use_rebuild_recover), false); // use fast rebuilding next time 339 | } 340 | 341 | } // tlbtree namespace 342 | 343 | #endif //__TLBTREEIMPL_H__ -------------------------------------------------------------------------------- /Concurrent/src/wotree256.cc: -------------------------------------------------------------------------------- 1 | #include "wotree256.h" 2 | 3 | namespace wotree256 { 4 | 5 | bool insert_recursive(Node * n, _key_t k, uint64_t v, _key_t &split_k, Node * &split_node, int8_t &level) { 6 | if(n->leftmost_ptr_ == NULL) { 7 | return n->store(k, v, split_k, split_node); 8 | } else { 9 | level++; 10 | Node * child = (Node *) galc->absolute(n->get_child(k)); 11 | 12 | _key_t split_k_child; 13 | Node * split_node_child; 14 | bool splitIf = insert_recursive(child, k, v, split_k_child, split_node_child, level); 15 | 16 | if(splitIf) { 17 | return n->store(split_k_child, (uint64_t)galc->relative(split_node_child), split_k, split_node); 18 | } 19 | return false; 20 | } 21 | } 22 | 23 | bool remove_recursive(Node * n, _key_t k) { 24 | if(n->leftmost_ptr_ == NULL) { 25 | n->remove(k); 26 | return n->state_.unpack.count < UNDERFLOW_CARD; 27 | } 28 | else { 29 | Node * child = (Node *) galc->absolute(n->get_child(k)); 30 | 31 | bool shouldMrg = remove_recursive(child, k); 32 | 33 | if(shouldMrg) { 34 | Node *leftsib = NULL, *rightsib = NULL; 35 | n->get_lrchild(k, leftsib, rightsib); 36 | 37 | if(leftsib != NULL && (child->state_.unpack.count + leftsib->state_.unpack.count) < CARDINALITY) { 38 | // merge with left node 39 | int8_t slotid = child->state_.read(0); 40 | n->remove(child->recs_[slotid].key); 41 | Node::merge(leftsib, child); 42 | 43 | return n->state_.unpack.count < UNDERFLOW_CARD; 44 | } else if (rightsib != NULL && (child->state_.unpack.count + rightsib->state_.unpack.count) < CARDINALITY) { 45 | // merge with right node 46 | int8_t slotid = rightsib->state_.read(0); 47 | n->remove(rightsib->recs_[slotid].key); 48 | Node::merge(child, rightsib); 49 | 50 | return n->state_.unpack.count < UNDERFLOW_CARD; 51 | } 52 | } 53 | return false; 54 | } 55 | } 56 | 57 | bool find(Node ** rootPtr, _key_t key, uint64_t &val) { 58 | Node * cur = galc->absolute(*rootPtr); 59 | while(cur->leftmost_ptr_ != NULL) { // no prefetch here 60 | char * child_ptr = cur->get_child(key); 61 | cur = (Node *)galc->absolute(child_ptr); 62 | } 63 | 64 | val = (uint64_t) cur->get_child(key); 65 | 66 | if((char *)val == NULL) 67 | return false; 68 | else 69 | return true; 70 | } 71 | 72 | res_t insert(Node ** rootPtr, _key_t key, uint64_t val, int threshold) { 73 | Node *root_= galc->absolute(*rootPtr); 74 | 75 | int8_t level = 1; 76 | _key_t split_k; 77 | Node * split_node; 78 | bool splitIf = insert_recursive(root_, key, val, split_k, split_node, level); 79 | 80 | if(splitIf) { 81 | if(level < threshold) { 82 | Node *new_root = new Node; 83 | new_root->leftmost_ptr_ = (char *)galc->relative(root_); 84 | new_root->append({split_k, (char *)galc->relative(split_node)}, 0, 0); 85 | new_root->state_.unpack.count = 1; 86 | 87 | clwb(new_root, 64); 88 | 89 | mfence(); // a barrier to make sure the new node is persisted 90 | persist_assign(rootPtr, (Node *)galc->relative(new_root)); 91 | 92 | return res_t(false, {0, NULL}); 93 | } else { 94 | return res_t(true, {split_k, (char *)split_node}); 95 | } 96 | } 97 | else { 98 | return res_t(false, {0, NULL}); 99 | } 100 | } 101 | 102 | bool update(Node ** rootPtr, _key_t key, uint64_t val) { 103 | Node * cur = galc->absolute(*rootPtr); 104 | while(cur->leftmost_ptr_ != NULL) { // no prefetch here 105 | char * child_ptr = cur->get_child(key); 106 | cur = (Node *)galc->absolute(child_ptr); 107 | } 108 | 109 | val = (uint64_t) cur->update(key, val); 110 | return true; 111 | } 112 | 113 | bool remove(Node ** rootPtr, _key_t key) { 114 | Node *root_= galc->absolute(*rootPtr); 115 | if(root_->leftmost_ptr_ == NULL) { 116 | root_->remove(key); 117 | 118 | return root_->state_.unpack.count == 0; 119 | } 120 | else { 121 | Node * child = (Node *) galc->absolute(root_->get_child(key)); 122 | 123 | bool shouldMrg = remove_recursive(child, key); 124 | 125 | if(shouldMrg) { 126 | Node *leftsib = NULL, *rightsib = NULL; 127 | root_->get_lrchild(key, leftsib, rightsib); 128 | 129 | if(leftsib != NULL && (child->state_.unpack.count + leftsib->state_.unpack.count) < CARDINALITY) { 130 | // merge with left node 131 | int8_t slotid = child->state_.read(0); 132 | root_->remove(child->recs_[slotid].key); 133 | Node::merge(leftsib, child); 134 | } 135 | else if (rightsib != NULL && (child->state_.unpack.count + rightsib->state_.unpack.count) < CARDINALITY) { 136 | // merge with right node 137 | int8_t slotid = rightsib->state_.read(0); 138 | root_->remove(rightsib->recs_[slotid].key); 139 | Node::merge(child, rightsib); 140 | } 141 | 142 | if(root_->state_.unpack.count == 0) { // the root is empty 143 | Node * old_root = root_; 144 | 145 | persist_assign(rootPtr, (Node *)root_->leftmost_ptr_); 146 | 147 | galc->free(old_root); 148 | } 149 | } 150 | 151 | return false; 152 | } 153 | } 154 | 155 | void printAll(Node ** rootPtr) { 156 | Node *root= galc->absolute(*rootPtr); 157 | root->print("", true); 158 | } 159 | 160 | } // namespace wotree256 -------------------------------------------------------------------------------- /Concurrent/src/wotree256.h: -------------------------------------------------------------------------------- 1 | /* 2 | log free wbtree with 256B nodesize, nonclass version of wbtree_slotonly 3 | Copyright(c) Luo Yongping All rights reserved! 4 | */ 5 | 6 | #ifndef __DOWNTREE256__ 7 | #define __DOWNTREE256__ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "flush.h" 16 | #include "pmallocator.h" 17 | 18 | namespace wotree256 { 19 | 20 | inline void barrier() { __asm__ __volatile__("": : :"memory");} 21 | 22 | using std::string; 23 | constexpr int CARDINALITY = 13; 24 | constexpr int UNDERFLOW_CARD = 4; 25 | 26 | struct state_t { 27 | struct statefield_t { // totally 8 bytes 28 | uint64_t slotArray : 52; 29 | uint64_t count : 4; 30 | uint64_t sibling_version : 1; 31 | uint64_t latch : 1; 32 | uint64_t node_version : 6; 33 | }; 34 | // the real data field of state 35 | union { 36 | uint64_t pack; // to do 8 bytes assignment 37 | statefield_t unpack;// to facilite accessing subfields 38 | }; 39 | 40 | public: 41 | state_t(uint64_t s = 0): pack(s) {} 42 | 43 | inline int8_t read(int8_t idx) const { 44 | uint64_t p = this->unpack.slotArray << 12; 45 | return (p & ((uint64_t)0xf << ((15 - idx) * 4))) >> ((15 - idx) * 4); 46 | } 47 | 48 | inline int8_t alloc() { 49 | int8_t occupy[CARDINALITY] = {0}; 50 | for(int8_t i = 0; i < unpack.count; i++) { 51 | occupy[read(i)] = 1; 52 | } 53 | for(int i = 0; i < CARDINALITY; i++) { 54 | if(occupy[i] == 0) return i; 55 | } 56 | return CARDINALITY; // never be here 57 | } 58 | 59 | void lock(bool change_version = true) { 60 | state_t new_state = pack; 61 | new_state.unpack.latch = 0; 62 | uint64_t old = new_state.pack; 63 | new_state.unpack.latch = 1; 64 | if(change_version) new_state.unpack.node_version++; 65 | uint64_t desired = new_state.pack; 66 | 67 | while(!__atomic_compare_exchange(&(this->pack), &old, &desired, 68 | false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)){ 69 | // the latch is hold by other thread or the state is changed 70 | while(1) { // if the latch is not released, wait it 71 | _mm_pause(); // delay for 140 cycle 72 | if(unpack.latch == 0) // check if the latch is released 73 | break; 74 | } 75 | 76 | state_t new_state = pack; 77 | new_state.unpack.latch = 0; 78 | old = new_state.pack; 79 | new_state.unpack.latch = 1; 80 | if(change_version) new_state.unpack.node_version++; 81 | desired = new_state.pack; 82 | } 83 | } 84 | 85 | void unlock(bool change_version = true) { 86 | state_t new_state = pack; 87 | new_state.unpack.latch = 0; 88 | if(change_version) new_state.unpack.node_version++; 89 | uint64_t desired = new_state.pack; 90 | uint64_t old; 91 | 92 | __atomic_exchange(&(this->pack), &desired, &old, __ATOMIC_ACQUIRE); 93 | } 94 | 95 | inline uint64_t add(int8_t idx, int8_t slot) { 96 | state_t new_state(this->pack); 97 | 98 | // update bit fields 99 | uint64_t p = this->unpack.slotArray << 12; 100 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 101 | uint64_t add_value = (uint64_t)slot << ((15 - idx) * 4); 102 | new_state.unpack.slotArray = ((p & (~mask)) + add_value + ((p & mask) >> 4)) >> 12; 103 | new_state.unpack.count++; 104 | 105 | return new_state.pack; 106 | } 107 | 108 | inline uint64_t remove(int idx) { // delete a slot id at position idx 109 | state_t new_state(this->pack); 110 | // update bit fields 111 | uint64_t p = this->unpack.slotArray << 12; 112 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 113 | new_state.unpack.slotArray = ((p & ~mask) + ((p & (mask>>4)) << 4)) >> 12; 114 | new_state.unpack.count--; 115 | 116 | return new_state.pack; 117 | } 118 | 119 | inline uint64_t append(int8_t idx, int8_t slot) { 120 | // Append the record at slotid, append the slotArray entry, but DO NOT modify the count 121 | state_t new_state(this->pack); 122 | 123 | // update bit fields 124 | uint64_t p = this->unpack.slotArray << 12; 125 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 126 | uint64_t add_value = (uint64_t)slot << ((15 - idx) * 4); 127 | new_state.unpack.slotArray = ((p & (~mask)) + add_value + ((p & mask) >> 4)) >> 12; 128 | 129 | return new_state.pack; 130 | } 131 | }; 132 | 133 | class Node { 134 | public: 135 | // First Cache Line 136 | state_t state_; // a very complex and compact state field 137 | char * leftmost_ptr_;// the left most child of current node 138 | Record siblings_[2]; // shadow sibling of current node 139 | // Slots 140 | Record recs_[CARDINALITY]; 141 | 142 | friend class wbtree; 143 | 144 | public: 145 | Node(bool isleaf = false): state_(0), leftmost_ptr_(NULL) { 146 | siblings_[0] = {MAX_KEY, NULL}; 147 | siblings_[1] = {MAX_KEY, NULL}; 148 | } 149 | 150 | void *operator new(size_t size) { 151 | void * ret = galc->malloc(size); 152 | return ret; 153 | } 154 | 155 | bool store(_key_t k, uint64_t v, _key_t & split_k, Node * & split_node) { 156 | // there is one exclusive writer 157 | state_.lock(); 158 | 159 | Record &sibling = siblings_[state_.unpack.sibling_version]; // the sibling is updated atomically, we are safe here 160 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 161 | Node * sib_node = (Node *)galc->absolute(sibling.val); 162 | state_.unlock(); 163 | return sib_node->store(k, v, split_k, split_node); 164 | } 165 | 166 | if(state_.unpack.count == CARDINALITY) { // should split the node 167 | uint64_t m = state_.unpack.count / 2; 168 | split_k = recs_[state_.read(m)].key; 169 | 170 | // copy half of the records into split node 171 | int8_t j = 0; 172 | state_t new_state = state_; 173 | if(leftmost_ptr_ == NULL) { 174 | split_node = new Node; 175 | split_node->state_.lock(); 176 | for(int i = m; i < state_.unpack.count; i++) { 177 | int8_t slotid = state_.read(i); 178 | split_node->append(recs_[slotid], j, j); 179 | j += 1; 180 | } 181 | 182 | new_state.unpack.count -= j; 183 | } else { 184 | int8_t slotid = state_.read(m); 185 | split_node = new Node(); 186 | split_node->state_.lock(); 187 | split_node->leftmost_ptr_ = recs_[slotid].val; 188 | 189 | for(int i = m + 1; i < state_.unpack.count; i++) { 190 | slotid = state_.read(i); 191 | split_node->append(recs_[slotid], j, j); 192 | j += 1; 193 | } 194 | 195 | new_state.unpack.count -= (j + 1); 196 | } 197 | split_node->state_.unpack.count = j; 198 | split_node->state_.unpack.sibling_version = 0; 199 | // the sibling node of current node pointed by split_node 200 | split_node->siblings_[0] = siblings_[state_.unpack.sibling_version]; 201 | clwb(split_node, 64); // persist header 202 | clwb(&split_node->recs_[1], sizeof(Record) * (j - 1)); // persist all the inserted records 203 | 204 | // the split node is installed as the shadow sibling of current node 205 | siblings_[(state_.unpack.sibling_version + 1) % 2] = {split_k, (char *)galc->relative(split_node)}; 206 | // persist_assign the state field 207 | new_state.unpack.sibling_version = (state_.unpack.sibling_version + 1) % 2; 208 | mfence(); // a barrier here to make sure all the update is persisted to storage 209 | 210 | persist_assign(&(state_.pack), new_state.pack); 211 | 212 | // go on the insertion 213 | if(k < split_k) { 214 | insertone(k, (char *)v); 215 | } else { 216 | split_node->insertone(k, (char *)v); 217 | } 218 | split_node->state_.unlock(); 219 | state_.unlock(); 220 | return true; 221 | } else { 222 | insertone(k, (char *)v); 223 | 224 | state_.unlock(); 225 | return false; 226 | } 227 | } 228 | 229 | char * get_child(_key_t k) { 230 | // use optimized lock to coordinate reader with writer 231 | get_retry: 232 | uint64_t old_version = state_.unpack.node_version; 233 | barrier(); 234 | 235 | Record &sibling = siblings_[state_.unpack.sibling_version]; // the sibling is updated atomically, we are safe here 236 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 237 | Node * sib_node = (Node *)galc->absolute(sibling.val); 238 | 239 | barrier(); 240 | if(old_version != state_.unpack.node_version || old_version % 2 != 0) { 241 | goto get_retry; 242 | } 243 | return sib_node->get_child(k); 244 | } 245 | 246 | if(leftmost_ptr_ == NULL) { 247 | int8_t slotid = 0; 248 | for(int i = 0; i < state_.unpack.count; i++) { 249 | slotid = state_.read(i); 250 | if(recs_[slotid].key >= k) { 251 | break; 252 | } 253 | } 254 | 255 | char * ret; 256 | if (recs_[slotid].key == k && state_.unpack.count > 0) 257 | ret = recs_[slotid].val; 258 | else 259 | ret = NULL; 260 | 261 | barrier(); 262 | if(old_version != state_.unpack.node_version || old_version % 2 != 0) { 263 | goto get_retry; 264 | } 265 | return ret; 266 | } else { 267 | int8_t slotid = 0, pos = state_.unpack.count; 268 | for(int i = 0; i < state_.unpack.count; i++) { 269 | slotid = state_.read(i); 270 | if(recs_[slotid].key > k) { 271 | pos = i; 272 | break; 273 | } 274 | } 275 | 276 | char * ret; 277 | if (pos == 0) // all the key is bigger than k 278 | ret = leftmost_ptr_; 279 | else 280 | ret = recs_[state_.read(pos - 1)].val; 281 | 282 | barrier(); 283 | if(old_version != state_.unpack.node_version || old_version % 2 != 0) { 284 | goto get_retry; 285 | } 286 | return ret; 287 | } 288 | } 289 | 290 | bool update(_key_t k, uint64_t v) { 291 | state_.lock(false); 292 | 293 | Record &sibling = siblings_[state_.unpack.sibling_version]; // the sibling is updated atomically, we are safe here 294 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 295 | Node * sib_node = (Node *)galc->absolute(sibling.val); 296 | state_.unlock(false); 297 | return sib_node->update(k, v); 298 | } 299 | 300 | uint64_t slotid = 0; 301 | for(int i = 0; i < state_.unpack.count; i++) { 302 | slotid = state_.read(i); 303 | if(recs_[slotid].key >= k) { 304 | break; 305 | } 306 | } 307 | 308 | bool found = false; 309 | if (recs_[slotid].key == k) { 310 | recs_[slotid].val = (char *)v; 311 | clwb(&recs_[slotid], sizeof(Record)); 312 | found = true; 313 | } 314 | 315 | state_.unlock(false); 316 | return found; 317 | } 318 | 319 | bool remove(_key_t k) { 320 | // Non-SMO delete takes only one clwb 321 | state_.lock(); 322 | Record &sibling = siblings_[state_.unpack.sibling_version]; 323 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 324 | Node * sib_node = (Node *)galc->absolute(sibling.val); 325 | state_.unlock(); 326 | return sib_node->remove(k); 327 | } 328 | 329 | if(leftmost_ptr_ == NULL) { 330 | int8_t idx, slotid; 331 | for(idx = 0; idx < state_.unpack.count; idx++) { 332 | slotid = state_.read(idx); 333 | if(recs_[slotid].key >= k) 334 | break; 335 | } 336 | 337 | if(recs_[slotid].key == k) { 338 | uint64_t newpack = state_.remove(idx); 339 | persist_assign(&(state_.pack), newpack); 340 | state_.unlock(); 341 | return true; 342 | } else { 343 | state_.unlock(); 344 | return false; 345 | } 346 | } else { 347 | int8_t idx; 348 | for(idx = 0; idx < state_.unpack.count; idx++) { 349 | int8_t slotid = state_.read(idx); 350 | if(recs_[slotid].key > k) 351 | break; 352 | } 353 | /* NOTICE: 354 | * We will never remove the leftmost child in our wbtree design 355 | * So the idx here must be larger than 0 356 | */ 357 | uint64_t newpack = state_.remove(idx - 1); 358 | persist_assign(&(state_.pack), newpack); 359 | 360 | state_.unlock(); 361 | return true; 362 | } 363 | } 364 | 365 | void print(string prefix, bool recursively) const { 366 | printf("%s[%lx(%ld) ", prefix.c_str(), state_.unpack.slotArray, state_.unpack.count); 367 | 368 | for(int i = 0; i < state_.unpack.count; i++) { 369 | printf("%d ", state_.read(i)); 370 | } 371 | 372 | for(int i = 0; i < state_.unpack.count; i++) { 373 | int8_t slotid = state_.read(i); 374 | printf("(%ld 0x%lx) ", recs_[slotid].key, (uint64_t)recs_[slotid].val); 375 | } 376 | printf("]\n"); 377 | 378 | if(recursively && leftmost_ptr_ != NULL) { 379 | Node * child = (Node *)galc->absolute(leftmost_ptr_); 380 | child->print(prefix + " ", recursively); 381 | 382 | for(int i = 0; i < state_.unpack.count; i++) { 383 | Node * child = (Node *)galc->absolute(recs_[state_.read(i)].val); 384 | child->print(prefix + " ", recursively); 385 | } 386 | } 387 | } 388 | 389 | void get_sibling(_key_t & k, Node ** &sibling) { 390 | Record &sib = siblings_[state_.unpack.sibling_version]; 391 | k = sib.key; 392 | sibling = (Node **)&(sib.val); 393 | } 394 | 395 | public: 396 | void insertone(_key_t key, char * right) { 397 | int8_t idx; 398 | for(idx = 0; idx < state_.unpack.count; idx++) { 399 | int8_t slotid = state_.read(idx); 400 | if(key < recs_[slotid].key) { 401 | break; 402 | } 403 | } 404 | 405 | // insert and flush the kv 406 | int8_t slotid = state_.alloc(); // alloc a slot in the node 407 | recs_[slotid] = {key, (char *) right}; 408 | clwb(&recs_[slotid], sizeof(Record)); 409 | mfence(); 410 | 411 | // atomically update the state 412 | uint64_t new_pack = state_.add(idx, slotid); 413 | persist_assign(&(state_.pack), new_pack); 414 | } 415 | 416 | void append(Record r, int8_t slotid, int8_t pos) { 417 | recs_[slotid] = r; 418 | state_.pack = state_.append(pos, slotid); 419 | } 420 | 421 | static void merge(Node * left, Node * right) { 422 | left->state_.lock(); 423 | right->state_.lock(); 424 | 425 | Record & sibling = left->siblings_[left->state_.unpack.sibling_version]; 426 | 427 | state_t new_state = left->state_; 428 | if(left->leftmost_ptr_ != NULL) { // insert the leftmost_ptr of the right node 429 | int8_t slotid = new_state.alloc(); 430 | left->append({sibling.key, right->leftmost_ptr_}, slotid, new_state.unpack.count); 431 | new_state.pack = new_state.add(new_state.unpack.count, slotid); 432 | } 433 | for(int i = 0; i < right->state_.unpack.count; i++) { 434 | int8_t slotid = new_state.alloc(); 435 | left->append(right->recs_[right->state_.read(i)], slotid, new_state.unpack.count); 436 | new_state.pack = new_state.add(new_state.unpack.count, slotid);; 437 | } 438 | 439 | Record tmp = right->siblings_[right->state_.unpack.sibling_version]; 440 | left->siblings_[(left->state_.unpack.sibling_version + 1) % 2] = tmp; 441 | new_state.unpack.sibling_version = (left->state_.unpack.sibling_version + 1) % 2; 442 | clwb(left, sizeof(Node)); // persist the whole leaf node 443 | 444 | // persist_assign the state_ field 445 | mfence(); 446 | left->state_.pack = new_state.pack; 447 | clwb(left, 64); 448 | 449 | left->state_.unlock(); 450 | 451 | galc->free(right); // WARNING: persistent memory leak here 452 | } 453 | 454 | void get_lrchild(_key_t k, Node * & left, Node * & right) { 455 | get_retry: 456 | uint64_t old_version = state_.unpack.node_version; 457 | barrier(); 458 | if(old_version != state_.unpack.node_version || old_version % 2 != 0) { 459 | goto get_retry; 460 | } 461 | 462 | int16_t i = 0; 463 | for( ; i < state_.unpack.count; i++) { 464 | int8_t slotid = state_.read(i); 465 | if(recs_[slotid].key > k) 466 | break; 467 | } 468 | 469 | if(i == 0) { 470 | left = NULL; 471 | } else if(i == 1) { 472 | left = (Node *)galc->absolute(leftmost_ptr_); 473 | } else { 474 | left = (Node *)galc->absolute(recs_[state_.read(i - 2)].val); 475 | } 476 | 477 | if(i == state_.unpack.count) { 478 | right = NULL; 479 | } else { 480 | right = (Node *)galc->absolute(recs_[state_.read(i)].val); 481 | } 482 | 483 | barrier(); 484 | if(old_version != state_.unpack.node_version || old_version % 2 != 0) { 485 | goto get_retry; 486 | } 487 | return ; 488 | } 489 | }; 490 | 491 | extern bool insert_recursive(Node * n, _key_t k, uint64_t v, _key_t &split_k, 492 | Node * &split_node, int8_t &level); 493 | extern bool remove_recursive(Node * n, _key_t k); 494 | extern bool find(Node ** rootPtr, _key_t key, uint64_t &val); 495 | extern res_t insert(Node ** rootPtr, _key_t key, uint64_t val, int threshold); 496 | extern bool update(Node ** rootPtr, _key_t key, uint64_t val); 497 | extern bool remove(Node ** rootPtr, _key_t key); 498 | extern void printAll(Node ** rootPtr); 499 | 500 | } // namespace wotree256 501 | 502 | #endif // __DOWNTREE256__ -------------------------------------------------------------------------------- /Concurrent/test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(datagen "datagen.cc") 2 | 3 | add_executable(main "main.cc") 4 | target_link_libraries(main tlbtree) 5 | 6 | add_executable(preload "preload.cc") 7 | target_link_libraries(preload tlbtree) -------------------------------------------------------------------------------- /Concurrent/test/datagen.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "common.h" 10 | #include "zipfian.h" 11 | 12 | using std::cout; 13 | using std::endl; 14 | using std::string; 15 | using std::ofstream; 16 | using std::ifstream; 17 | 18 | enum DistributionType {RAND = 0, ZIPFIAN}; 19 | 20 | struct WorkloadType { 21 | int operations = MILLION; 22 | float read = 1.0; 23 | float insert = 0; 24 | float update = 0; 25 | float remove = 0; 26 | DistributionType dist = RAND; 27 | float skewness = 0.8; 28 | bool valid() { 29 | return read + insert + update + remove == 1.0 && skewness > 0 && skewness < 1.0; 30 | } 31 | void print() { 32 | cout << "=========WORKLOAD TYPE=========" << endl; 33 | cout << "Operations : " << operations << endl; 34 | cout << "Read Ratio : " << read << endl; 35 | cout << "Insert Ratio: " << insert << endl; 36 | cout << "Update Ratio: " << update << endl; 37 | cout << "Remove Ratio: " << remove << endl; 38 | cout << "Distribution: " << (dist == RAND ? "random" : "Zipfian") << endl; 39 | if (dist == ZIPFIAN) { 40 | cout << "Skewness " << skewness << endl; 41 | } 42 | cout << "===============================" << endl; 43 | } 44 | }; 45 | 46 | class OperationGenerator { 47 | public : 48 | OperationType mappings_[100]; 49 | std::default_random_engine gen_; 50 | std::uniform_int_distribution dist_; 51 | 52 | OperationGenerator(WorkloadType &w) : gen_(getRandom()) { 53 | int read_end = 100 * w.read; 54 | int insert_end = read_end + 100 * w.insert; 55 | int update_end = insert_end + 100 * w.update; 56 | int remove_end = update_end + 100 * w.remove; 57 | 58 | for(int i = 0; i < read_end; i++) 59 | mappings_[i] = OperationType::READ; 60 | 61 | for(int i = read_end; i < insert_end; i++) 62 | mappings_[i] = OperationType::INSERT; 63 | 64 | for(int i = insert_end; i < update_end; i++) 65 | mappings_[i] = OperationType::UPDATE; 66 | 67 | for(int i = update_end; i < remove_end; i++) 68 | mappings_[i] = OperationType::DELETE; 69 | } 70 | 71 | OperationType next() { 72 | return mappings_[dist_(gen_) % 100]; 73 | } 74 | }; 75 | 76 | // try not to generate duplicate keys, because some tree indices may not get used to it 77 | 78 | void gen_dataset(int64_t *arr, uint64_t scale, bool random) { 79 | std::mt19937 gen(10007); 80 | if(random) { 81 | uint64_t step = MAX_KEY / scale; 82 | std::uniform_int_distribution dist(0, MAX_KEY); 83 | for(int64_t i = 0; i < scale; i++) { 84 | #ifdef DEBUG 85 | arr[i] = i + 1; 86 | #else 87 | arr[i] = i * step + 1; // non duplicated keys, and no zero key 88 | #endif 89 | } 90 | std::shuffle(arr, arr + scale - 1, gen); 91 | } else { 92 | std::normal_distribution dist(MAX_KEY / 2, MAX_KEY / 8); 93 | int64_t i = 0; 94 | while (i < scale) { 95 | double val = (uint64_t)dist(gen); 96 | if(val < 0 || val > (double) MAX_KEY) { 97 | continue; 98 | } else { 99 | arr[i++] = (int64_t)std::round(val); 100 | } 101 | } 102 | } 103 | return ; 104 | } 105 | 106 | void gen_workload(int64_t *arr, uint64_t scale, QueryType * querys, WorkloadType w) { 107 | std::mt19937 gen(getRandom()); 108 | std::uniform_int_distribution idx1_dist(0, scale - 1); 109 | zipfian_int_distribution idx2_dist(0, scale - 1, w.skewness); 110 | OperationGenerator op_gen(w); 111 | 112 | for(int i = 0; i < w.operations; i++) { 113 | OperationType op = op_gen.next(); 114 | int idx = (w.dist == RAND ? idx1_dist(gen) : idx2_dist(gen)); 115 | // for insert operations, we should make sure the key does not exist in the dataset 116 | _key_t key = (op == OperationType::INSERT ? arr[idx] + getRandom(): arr[idx]); 117 | 118 | querys[i] = {op, key}; 119 | } 120 | } 121 | 122 | int main(int argc, char ** argv) { 123 | static const bool DATASET_RANDOM = true; 124 | bool opt_zipfian = false; 125 | WorkloadType w; 126 | 127 | static const char * optstr = "r:i:u:d:o:s:hz"; 128 | opterr = 0; 129 | char opt; 130 | while((opt = getopt(argc, argv, optstr)) != -1) { 131 | switch(opt) { 132 | case 'o': 133 | w.operations = atoi(optarg) * MILLION; 134 | break; 135 | case 's': 136 | w.skewness = atof(optarg); 137 | break; 138 | case 'r': 139 | w.read = atof(optarg); 140 | break; 141 | case 'i': 142 | w.insert = atof(optarg); 143 | break; 144 | case 'd': 145 | w.remove = atof(optarg); 146 | break; 147 | case 'u': 148 | w.update = atof(optarg); 149 | break; 150 | case 'z': 151 | opt_zipfian = true; 152 | break; 153 | case '?': 154 | case 'h': 155 | default: 156 | cout << "USAGE: "<< argv[0] << "[option]" << endl; 157 | cout << "\t -h: " << "Print the USAGE" << endl; 158 | cout << "\t -z: " << "Use zipfian distribution (Not specified: random distribution)" << endl; 159 | cout << "\t -o: " << "The number of operations" << endl; 160 | cout << "\t -s: " << "The skewness of query workload(0 - 1)" << endl; 161 | cout << "\t -r: " << "Read ratio" << endl; 162 | cout << "\t -i: " << "Insert ratio" << endl; 163 | cout << "\t -u: " << "update ratio" << endl; 164 | cout << "\t -d: " << "Delete ratio" << endl; 165 | exit(-1); 166 | } 167 | } 168 | 169 | if(!w.valid()) { 170 | cout << "Invalid workload configuration" << endl; 171 | exit(-1); 172 | } 173 | if(opt_zipfian == true) { 174 | w.dist = ZIPFIAN; 175 | } 176 | 177 | w.print(); 178 | 179 | #ifdef DEBUG 180 | uint64_t scale = LOADSCALE * KILO; 181 | #else 182 | uint64_t scale = LOADSCALE * MILLION; 183 | #endif 184 | 185 | int64_t * arr = new int64_t[scale]; 186 | if(!file_exist("dataset.dat")) { 187 | gen_dataset(arr, scale, DATASET_RANDOM); 188 | ofstream fout("dataset.dat", std::ios::binary); 189 | fout.write((char *) arr, sizeof(int64_t) * scale); 190 | fout.close(); 191 | cout << "generate a dataset file" << endl; 192 | } else { 193 | ifstream fin("dataset.dat", std::ios::binary); 194 | fin.read((char *)arr, sizeof(int64_t) * scale); 195 | fin.close(); 196 | } 197 | 198 | QueryType * querys = new QueryType[w.operations]; 199 | gen_workload(arr, scale, querys, w); 200 | 201 | ofstream fout("workload.txt"); 202 | for(int i = 0; i < w.operations; i++) { 203 | fout << querys[i].op << " " << querys[i].key << endl; 204 | } 205 | fout.close(); 206 | cout << "generate a query workload file" << endl; 207 | 208 | delete [] arr; 209 | delete [] querys; 210 | return 0; 211 | } -------------------------------------------------------------------------------- /Concurrent/test/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "tlbtree.h" 11 | 12 | using std::cout; 13 | using std::endl; 14 | using std::ifstream; 15 | using std::string; 16 | 17 | template 18 | double run_test(std::vector querys, int thread_cnt) { 19 | // construct a Btree 20 | BtreeType tree("/mnt/pmem/tlbtree.pool"); 21 | 22 | std::atomic_int cur_pos(0); 23 | int small_noise = getRandom() & 0xff; // each time we run, we will insert different keys 24 | 25 | // set the timer 26 | #pragma omp barrier 27 | auto start = seconds(); 28 | 29 | // start the section of parallel 30 | #pragma omp parallel num_threads(thread_cnt) 31 | { 32 | #pragma omp for schedule(static) 33 | for (size_t i = 0; i < querys.size(); ++i) { 34 | // get a unique query from querys 35 | int obtain_pos = cur_pos.fetch_add(1, std::memory_order_relaxed); 36 | OperationType op = querys[obtain_pos].op; 37 | _key_t key = querys[obtain_pos].key; 38 | uint64_t val = (uint64_t)key; 39 | 40 | switch (op) { 41 | case OperationType::READ: { 42 | auto val = tree.lookup(key); 43 | assert(val != 0); 44 | break; 45 | } 46 | case OperationType::INSERT: { 47 | tree.insert(key + small_noise, uint64_t((uint64_t)val + small_noise)); 48 | break; 49 | } 50 | case OperationType::UPDATE: { 51 | auto r = tree.update(key, val); 52 | assert(r); 53 | break; 54 | } 55 | case OperationType::DELETE: { 56 | auto r = tree.remove(key); 57 | assert(r); 58 | break; 59 | } 60 | default: 61 | std::cout << "Error: unknown operation!" << std::endl; 62 | exit(0); 63 | break; 64 | } 65 | } 66 | } 67 | 68 | #pragma omp barrier 69 | auto end = seconds(); 70 | 71 | return end - start; 72 | } 73 | 74 | 75 | int main(int argc, char ** argv) { 76 | string opt_fname = "../build/workload.txt"; 77 | int opt_num_thread = 1; 78 | 79 | static const char * optstr = "f:t:h"; 80 | opterr = 0; 81 | char opt; 82 | while((opt = getopt(argc, argv, optstr)) != -1) { 83 | switch(opt) { 84 | case 'f': 85 | opt_fname = string(optarg); 86 | break; 87 | case 't': 88 | if(atoi(optarg) > 0) 89 | opt_num_thread = atoi(optarg); 90 | break; 91 | case '?': 92 | case 'h': 93 | default: 94 | cout << "USAGE: "<< argv[0] << "[option]" << endl; 95 | cout << "\t -h: " << "Print the USAGE" << endl; 96 | cout << "\t -f: " << "Filename of the workload" << endl; 97 | cout << "\t -t: " << "Number of Threads to excute the workload" << endl; 98 | cout << "\t -i: " << "The index tree type" << endl; 99 | exit(-1); 100 | break; 101 | } 102 | } 103 | 104 | ifstream fin(opt_fname.c_str()); 105 | if(!fin) { 106 | cout << "workload file not openned" << endl; 107 | exit(-1); 108 | } 109 | std::vector querys; 110 | int op; 111 | _key_t key; 112 | while(fin >> op >> key) { 113 | querys.push_back({(OperationType)op, key}); 114 | } 115 | double time = run_test(querys, opt_num_thread); 116 | 117 | cout << time << endl; 118 | 119 | return 0; 120 | } -------------------------------------------------------------------------------- /Concurrent/test/preload.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "tlbtree.h" 9 | 10 | using std::cout; 11 | using std::endl; 12 | using std::ifstream; 13 | 14 | typedef double mytime_t; 15 | 16 | _key_t *keys; 17 | 18 | template 19 | void preload(BTreeType &tree, int64_t load_size, ifstream & fin, int thread_cnt) { 20 | #pragma omp parallel num_threads(thread_cnt) 21 | { 22 | #pragma omp for schedule(static) 23 | for(int64_t i = 0; i < load_size; i++) { 24 | _key_t key = keys[i]; 25 | tree.insert((_key_t)key, (uint64_t)key); 26 | } 27 | } 28 | return ; 29 | } 30 | 31 | int main(int argc, char ** argv) { 32 | int num_threads = 4; 33 | 34 | if(argc > 1 && atoi(argv[1]) > 0) { 35 | num_threads = atoi(argv[1]); 36 | } 37 | // open the data file 38 | std::string filename = "/home/lyp/TLBtree/Concurrent/build/dataset.dat"; 39 | std::ifstream fin(filename.c_str(), std::ios::binary); 40 | if(!fin) { 41 | cout << "File not exists or Open error\n"; 42 | exit(-1); 43 | } 44 | 45 | // read all the key into vector keys 46 | keys = new _key_t[sizeof(_key_t) * LOADSCALE * MILLION]; 47 | fin.read((char *)keys, sizeof(_key_t) * LOADSCALE * MILLION); 48 | 49 | cout << "tlbtree" << endl; 50 | TLBtree tree("/mnt/pmem/tlbtree.pool"); 51 | preload(tree, LOADSCALE * MILLION, fin, num_threads); 52 | 53 | delete keys; 54 | fin.close(); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Concurrent/test/zipfian.h: -------------------------------------------------------------------------------- 1 | /* Implementation derived from: 2 | * "Quickly Generating Billion-Record Synthetic Databases", Jim Gray et al, 3 | * SIGMOD 1994 4 | * 5 | * The zipfian_int_distribution class is intended to be compatible with other 6 | * distributions introduced in #include by the C++11 standard. 7 | * 8 | * Usage example: 9 | * #include 10 | * #include "zipfian_int_distribution.h" 11 | * int main() 12 | * { 13 | * std::default_random_engine generator; 14 | * zipfian_int_distribution distribution(1, 10, 0.99); 15 | * int i = distribution(generator); 16 | * } 17 | */ 18 | 19 | /* 20 | * IMPORTANT: constructing the distribution object requires calculating the zeta 21 | * value which becomes prohibetively expensive for very large ranges. As an 22 | * alternative for such cases, the user can pass the pre-calculated values and 23 | * avoid the calculation every time. 24 | * 25 | * Usage example: 26 | * #include 27 | * #include "zipfian_int_distribution.h" 28 | * int main() 29 | * { 30 | * std::default_random_engine generator; 31 | * zipfian_int_distribution::param_type p(1, 1e6, 0.99, 27.000); 32 | * zipfian_int_distribution distribution(p); 33 | * int i = distribution(generator); 34 | * } 35 | */ 36 | 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | template 43 | class zipfian_int_distribution 44 | { 45 | static_assert(std::is_integral<_IntType>::value, "Template argument not an integral type."); 46 | 47 | public: 48 | /** The type of the range of the distribution. */ 49 | typedef _IntType result_type; 50 | /** Parameter type. */ 51 | struct param_type 52 | { 53 | typedef zipfian_int_distribution<_IntType> distribution_type; 54 | 55 | explicit param_type(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max(), double __theta = 0.99) 56 | : _M_a(__a), _M_b(__b), _M_theta(__theta), 57 | _M_zeta(zeta(_M_b - _M_a + 1, __theta)), _M_zeta2theta(zeta(2, __theta)) 58 | { 59 | assert(_M_a <= _M_b && _M_theta > 0.0 && _M_theta < 1.0); 60 | } 61 | 62 | explicit param_type(_IntType __a, _IntType __b, double __theta, double __zeta) 63 | : _M_a(__a), _M_b(__b), _M_theta(__theta), _M_zeta(__zeta), 64 | _M_zeta2theta(zeta(2, __theta)) 65 | { 66 | __glibcxx_assert(_M_a <= _M_b && _M_theta > 0.0 && _M_theta < 1.0); 67 | } 68 | 69 | result_type a() const { return _M_a; } 70 | 71 | result_type b() const { return _M_b; } 72 | 73 | double theta() const { return _M_theta; } 74 | 75 | double zeta() const { return _M_zeta; } 76 | 77 | double zeta2theta() const { return _M_zeta2theta; } 78 | 79 | friend bool operator==(const param_type& __p1, const param_type& __p2) 80 | { 81 | return __p1._M_a == __p2._M_a 82 | && __p1._M_b == __p2._M_b 83 | && __p1._M_theta == __p2._M_theta 84 | && __p1._M_zeta == __p2._M_zeta 85 | && __p1._M_zeta2theta == __p2._M_zeta2theta; 86 | } 87 | 88 | private: 89 | _IntType _M_a; 90 | _IntType _M_b; 91 | double _M_theta; 92 | double _M_zeta; 93 | double _M_zeta2theta; 94 | 95 | /** 96 | * @brief Calculates zeta. 97 | * 98 | * @param __n [IN] The size of the domain. 99 | * @param __theta [IN] The skew factor of the distribution. 100 | */ 101 | double zeta(unsigned long __n, double __theta) 102 | { 103 | double ans = 0.0; 104 | for (unsigned long i=1; i<=__n; ++i) 105 | ans += std::pow(1.0 / i, __theta); 106 | return ans; 107 | } 108 | }; 109 | 110 | public: 111 | /** 112 | * @brief Constructs a zipfian_int_distribution object. 113 | * 114 | * @param __a [IN] The lower bound of the distribution. 115 | * @param __b [IN] The upper bound of the distribution. 116 | * @param __theta [IN] The skew factor of the distribution. 117 | */ 118 | explicit zipfian_int_distribution(_IntType __a = _IntType(0), _IntType __b = _IntType(1), double __theta = 0.99) 119 | : _M_param(__a, __b, __theta) 120 | { 121 | } 122 | 123 | explicit zipfian_int_distribution(const param_type& __p) : _M_param(__p) 124 | { 125 | } 126 | 127 | /** 128 | * @brief Resets the distribution state. 129 | * 130 | * Does nothing for the zipfian int distribution. 131 | */ 132 | void reset() {} 133 | 134 | result_type a() const { return _M_param.a(); } 135 | 136 | result_type b() const { return _M_param.b(); } 137 | 138 | double theta() const { return _M_param.theta(); } 139 | 140 | /** 141 | * @brief Returns the parameter set of the distribution. 142 | */ 143 | param_type param() const { return _M_param; } 144 | 145 | /** 146 | * @brief Sets the parameter set of the distribution. 147 | * @param __param The new parameter set of the distribution. 148 | */ 149 | void param(const param_type& __param) { _M_param = __param; } 150 | 151 | /** 152 | * @brief Returns the inclusive lower bound of the distribution range. 153 | */ 154 | result_type min() const { return this->a(); } 155 | 156 | /** 157 | * @brief Returns the inclusive upper bound of the distribution range. 158 | */ 159 | result_type max() const { return this->b(); } 160 | 161 | /** 162 | * @brief Generating functions. 163 | */ 164 | template 165 | result_type operator()(_UniformRandomNumberGenerator& __urng) 166 | { 167 | return this->operator()(__urng, _M_param); 168 | } 169 | 170 | template 171 | result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) 172 | { 173 | double alpha = 1 / (1 - __p.theta()); 174 | double eta = (1 - std::pow(2.0 / (__p.b() - __p.a() + 1), 1 - __p.theta())) / (1 - __p.zeta2theta() / __p.zeta()); 175 | 176 | double u = std::generate_canonical::digits, _UniformRandomNumberGenerator>(__urng); 177 | 178 | double uz = u * __p.zeta(); 179 | if (uz < 1.0) 180 | return __p.a(); 181 | if (uz < 1.0 + std::pow(0.5, __p.theta())) 182 | return __p.a() + 1; 183 | 184 | return __p.a() + ((__p.b() - __p.a() + 1) * std::pow(eta * u - eta + 1, alpha)); 185 | } 186 | 187 | /** 188 | * @brief Return true if two zipfian int distributions have 189 | * the same parameters. 190 | */ 191 | friend bool operator==(const zipfian_int_distribution& __d1, const zipfian_int_distribution& __d2) 192 | { 193 | return __d1._M_param == __d2._M_param; 194 | } 195 | 196 | private: 197 | param_type _M_param; 198 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Implementation of the paper "TLBtree: A Read/Write-Optimized Tree Index for Non-Volatile Memory (ICDE'21)" and paper "Two Birds with One Stone: Boosting Both Search and Write Performance for Tree Indices on Persistent Memory (TECS'21)". 2 | 3 | TLBtree is a read/write-optimized persistent index for NVM-only Memory System. It is composed of a read-optimized top layer and a NVM-friendly write-optimized down layer. The top layer is read frequently, so we adpot a less-mutable and cache-friendly design; The down layer is write frequently and should be carefully guarded by persistent instructions (e.g. clwb and sfence), so we employ a structure with low persistent cost on real NVM enviroment. 4 | 5 | Our idea is motivated by the observation that B+-tree-like range indices tend to absorb 99% of writes in the bottom 2-3 levels, while reads are evenly distributed in each level. According to the observation, we propose a Two Layer Persistent Index (TLPI) achitecture first. TLPI divides a pesistent tree index into two layers, so it enables to put together specific optimizations which may be too complicated to coexist in an individual index. TLBtree is a tailored instance of TLPI, you can also add new read optimizations into the top layer and write optimizations to the down layer, for further performance potential. 6 | 7 | 8 | #### Dependence 9 | We test our project on ubuntu LTS 2020. 10 | 1. This project depends on libpmemobj from [PMDK](https://pmem.io/pmdk/libpmemobj/). Install it using command 11 | ```shell 12 | sudo apt-get install make 13 | sudo apt-get install libpmemobj-dev 14 | ``` 15 | 2. Make sure you are avaliable with Optane memory (or you can use volatile memory to simulate pmem device on latest ubuntu version). The project assumes that your pmem device is mounted at address `/mnt/pmem` and you have write permission to it. 16 | 17 | (a). Avaiable to real Optane DC Memory, configure it in this [way](https://software.intel.com/content/www/us/en/develop/articles/qsg-part2-linux-provisioning-with-optane-pmem.html). 18 | 19 | (b). Not avaiable to Optane, try simluate it with DRAM following this [link](https://software.intel.com/content/www/us/en/develop/articles/how-to-emulate-persistent-memory-on-an-intel-architecture-server.html). 20 | 21 | 22 | #### Usage 23 | 1. Configure your PMEM file address and file size threshold in *include/tlbtree.h* 24 | 2. Compile the program with following commands (the same in Single or Concurrent) 25 | ```sh 26 | mkdir build 27 | cd build; cmake .. 28 | make 29 | ``` 30 | 3. Play with TLBtree using provided test modules: 31 | 32 | (a). generate data with `datagen` (type `datagen -h` if needed) 33 | 34 | (b). populate the TLBtree with some inital key value pairs 35 | 36 | (c). doing CUID operations with `main` 37 | 38 | #### Limitations 39 | Currently TLBtree supports only 8-byte integer key and payload 40 | -------------------------------------------------------------------------------- /Single/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .vscode 3 | -------------------------------------------------------------------------------- /Single/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(TLBtree) 2 | 3 | cmake_minimum_required(VERSION 3.16) 4 | 5 | add_compile_options(-mclwb -fmax-errors=5) 6 | add_compile_options(-O3) 7 | link_libraries(/usr/lib/x86_64-linux-gnu/libpmemobj.so) 8 | add_link_options(-pthread) 9 | 10 | include_directories(include) 11 | 12 | add_subdirectory(src) 13 | add_subdirectory(test) -------------------------------------------------------------------------------- /Single/include/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #ifndef __COMMON_H__ 6 | #define __COMMON_H__ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #define LOADSCALE 8 13 | #define DOFLUSH 14 | 15 | #define KILO 1024 16 | #define MILLION (KILO * KILO) 17 | #define CACHE_LINE_SIZE 64 18 | 19 | #ifndef KEYTYPE 20 | using _key_t = int64_t; 21 | #else 22 | using _key_t = KEYTYPE; 23 | #endif 24 | 25 | const _key_t MAX_KEY = std::numeric_limits<_key_t>::max(); 26 | const _key_t MIN_KEY = typeid(_key_t) == typeid(double) || typeid(_key_t) == typeid(float) 27 | ? -1 * MAX_KEY : std::numeric_limits<_key_t>::min(); 28 | 29 | struct Record { 30 | _key_t key; 31 | char * val; 32 | Record(_key_t k=MAX_KEY, char * v=NULL) : key(k), val(v) {} 33 | bool operator < (const Record & other) { 34 | return key < other.key; 35 | } 36 | }; 37 | 38 | enum OperationType {READ = 0, INSERT, UPDATE, DELETE}; 39 | 40 | struct res_t { // a result type use to pass info when split and search 41 | bool flag; 42 | Record rec; 43 | res_t(bool f, Record e):flag(f), rec(e) {} 44 | }; 45 | 46 | #include 47 | inline double seconds() 48 | { 49 | timeval now; 50 | gettimeofday(&now, NULL); 51 | return now.tv_sec + now.tv_usec/1000000.0; 52 | } 53 | 54 | inline int getRandom() { 55 | timeval now; 56 | gettimeofday(&now, NULL); 57 | return now.tv_usec; 58 | } 59 | 60 | inline bool file_exist(const char *pool_path) { 61 | struct stat buffer; 62 | return (stat(pool_path, &buffer) == 0); 63 | } 64 | 65 | #endif //__COMMON_H__ -------------------------------------------------------------------------------- /Single/include/tlbtree.h: -------------------------------------------------------------------------------- 1 | #ifndef __TLBTREE_H__ 2 | #define __TLBTREE_H__ 3 | 4 | #include "../src/tlbtree_impl.h" 5 | 6 | using tlbtree::TLBtreeImpl; 7 | 8 | // configure the PMEM file and file size 9 | static constexpr uint64_t POOL_SIZE = 512UL * 1024 * 1024; 10 | 11 | class TLBtree { 12 | public: 13 | TLBtree(std::string tlbname, uint64_t poolsize = POOL_SIZE) { 14 | bool recover = file_exist(tlbname.c_str()); 15 | tree_ = new TLBtreeImpl<2,2>(tlbname, recover, poolsize); 16 | } 17 | 18 | ~TLBtree() { 19 | delete tree_; 20 | } 21 | 22 | inline void insert(_key_t key, uint64_t val) { 23 | tree_->insert(key, val); 24 | } 25 | 26 | inline bool update(_key_t key, uint64_t val) { 27 | return tree_->update(key, val); 28 | } 29 | 30 | inline uint64_t lookup(_key_t key) { 31 | uint64_t val; 32 | bool found = tree_->find(key, val); 33 | 34 | if(found) 35 | return val; 36 | else 37 | return 0; 38 | } 39 | 40 | inline bool remove(_key_t key) { 41 | return tree_->remove(key); 42 | } 43 | 44 | private: 45 | TLBtreeImpl <2,2> * tree_; 46 | }; 47 | 48 | #endif //__TLBTREE_H__ -------------------------------------------------------------------------------- /Single/src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(tlbtree tlbtree_impl.cc wotree256.cc) -------------------------------------------------------------------------------- /Single/src/fixtree.h: -------------------------------------------------------------------------------- 1 | /* fixtree.h - A search-optimized fixed tree 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | 6 | #ifndef __FIXTREE__ 7 | #define __FIXTREE__ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "flush.h" 17 | #include "pmallocator.h" 18 | 19 | namespace fixtree { 20 | const int INNER_CARD = 32; // node size: 256B, the fanout of inner node is 32 21 | const int LEAF_CARD = 16; // node size: 256B, the fanout of leaf node is 16 22 | const int LEAF_REBUILD_CARD = 8; 23 | const int MAX_HEIGHT = 10; 24 | 25 | // the entrance of fixtree that stores its persistent tree metadata 26 | struct entrance_t { 27 | void * leaf_buff; 28 | void * inner_buff; 29 | uint32_t height; // the tree height 30 | uint32_t leaf_cnt; 31 | }; 32 | 33 | /* Fixtree: 34 | a search-optimized linearize tree structure which can absort moderate insertions: 35 | */ 36 | class Fixtree { 37 | public: 38 | struct INNode { // inner node is packed keys, which is very compact 39 | _key_t keys[INNER_CARD]; 40 | } __attribute__((aligned(CACHE_LINE_SIZE))); 41 | 42 | struct LFNode { // leaf node is packed key-ptr along with a header. 43 | // leaf node has some gap to absort insert 44 | _key_t keys[LEAF_CARD]; 45 | char * vals[LEAF_CARD]; 46 | } __attribute__((aligned(CACHE_LINE_SIZE))); 47 | 48 | public: 49 | // volatile structures 50 | INNode * inner_nodes_; 51 | LFNode * leaf_nodes_; 52 | uint32_t height_; 53 | uint32_t leaf_cnt_; 54 | entrance_t * entrance_; 55 | uint32_t level_offset_[MAX_HEIGHT]; 56 | 57 | public: 58 | Fixtree(entrance_t * ent) { // recovery the tree from the entrance 59 | inner_nodes_ = (INNode *)galc->absolute(ent->inner_buff); 60 | leaf_nodes_ = (LFNode *)galc->absolute(ent->leaf_buff); 61 | height_ = ent->height; 62 | leaf_cnt_ = ent->leaf_cnt; 63 | entrance_ = ent; 64 | 65 | uint32_t tmp = 0; 66 | for(int l = 0; l < height_; l++) { 67 | level_offset_[l] = tmp; 68 | tmp += std::pow(INNER_CARD, l); 69 | } 70 | level_offset_[height_] = tmp; 71 | } 72 | 73 | Fixtree(std::vector records) { 74 | const int lfary = LEAF_REBUILD_CARD; 75 | int record_count = records.size(); 76 | 77 | uint32_t lfnode_cnt = std::ceil((float)record_count / lfary); 78 | leaf_nodes_ = (LFNode *) galc->malloc(std::max((size_t)4096, lfnode_cnt * sizeof(LFNode))); 79 | 80 | height_ = std::ceil(std::log(std::max((uint32_t)INNER_CARD, lfnode_cnt)) / std::log(INNER_CARD)); 81 | uint32_t innode_cnt = (std::pow(INNER_CARD, height_) - 1) / (INNER_CARD - 1); 82 | inner_nodes_ = (INNode *) galc->malloc(std::max((size_t)4096, innode_cnt * sizeof(INNode))); 83 | 84 | // fill leaf nodes 85 | for(int i = 0; i < lfnode_cnt; i++) { 86 | for(int j = 0; j < lfary; j++) { 87 | auto idx = i * lfary + j; 88 | leaf_nodes_[i].keys[j] = idx < record_count ? records[idx].key : MAX_KEY; 89 | leaf_nodes_[i].vals[j] = idx < record_count ? records[idx].val : 0; 90 | } 91 | for(int j = lfary; j < LEAF_CARD; j++) { // intialized key 92 | leaf_nodes_[i].keys[j] = MAX_KEY; 93 | } 94 | clwb(leaf_nodes_ + i, sizeof(LFNode)); 95 | } 96 | 97 | int cur_level_cnt = lfnode_cnt; 98 | int cur_level_off = innode_cnt - std::pow(INNER_CARD, height_ - 1); 99 | int last_level_off = 0; 100 | 101 | // fill parent innodes of leaf nodes 102 | for(int i = 0; i < cur_level_cnt; i++) 103 | inner_insert(cur_level_off + i / INNER_CARD, i % INNER_CARD, leaf_nodes_[i].keys[0]); 104 | if(cur_level_cnt % INNER_CARD) 105 | inner_insert(cur_level_off + cur_level_cnt / INNER_CARD, cur_level_cnt % INNER_CARD, MAX_KEY); 106 | clwb(&inner_nodes_[cur_level_off], sizeof(INNode) * (cur_level_cnt / INNER_CARD + 1)); 107 | 108 | cur_level_cnt = std::ceil((float)cur_level_cnt / INNER_CARD); 109 | last_level_off = cur_level_off; 110 | cur_level_off = cur_level_off - std::pow(INNER_CARD, height_ - 2); 111 | 112 | // fill other inner nodes 113 | for(int l = height_ - 2; l >= 0; l--) { // level by level 114 | for(int i = 0; i < cur_level_cnt; i++) 115 | inner_insert(cur_level_off + i / INNER_CARD, i % INNER_CARD, inner_nodes_[last_level_off + i].keys[0]); 116 | if(cur_level_cnt % INNER_CARD) 117 | inner_insert(cur_level_off + cur_level_cnt / INNER_CARD, cur_level_cnt % INNER_CARD, MAX_KEY); 118 | clwb(&inner_nodes_[cur_level_off], sizeof(INNode) * (cur_level_cnt / INNER_CARD + 1)); 119 | 120 | cur_level_cnt = std::ceil((float)cur_level_cnt / INNER_CARD); 121 | last_level_off = cur_level_off; 122 | cur_level_off = cur_level_off - std::pow(INNER_CARD, l - 1); 123 | } 124 | 125 | leaf_cnt_ = lfnode_cnt; 126 | entrance_ = (entrance_t *)galc->malloc(4096); // the allocator is not thread_safe, allocate a large entrance 127 | uint32_t tmp = 0; 128 | for(int l = 0; l < height_; l++) { 129 | level_offset_[l] = tmp; 130 | tmp += std::pow(INNER_CARD, l); 131 | } 132 | level_offset_[height_] = tmp; 133 | 134 | persist_assign(&(entrance_->leaf_buff), (void *) galc->relative(leaf_nodes_)); 135 | persist_assign(&(entrance_->inner_buff), (void *) galc->relative(inner_nodes_)); 136 | persist_assign(&(entrance_->height), height_); 137 | persist_assign(&(entrance_->leaf_cnt), lfnode_cnt); 138 | 139 | return ; 140 | } 141 | 142 | public: 143 | char ** find_lower(_key_t key) { 144 | /* linear search, return the position of the stored value */ 145 | int cur_idx = level_offset_[0]; 146 | for(int l = 0; l < height_; l++) { 147 | #ifdef DEBUG 148 | INNode * inner = inner_nodes_ + cur_idx; 149 | #endif 150 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 151 | } 152 | cur_idx -= level_offset_[height_]; 153 | 154 | return leaf_search(cur_idx, key); 155 | } 156 | 157 | bool insert(_key_t key, uint64_t val) { 158 | uint32_t cur_idx = level_offset_[0]; 159 | for(int l = 0; l < height_; l++) { 160 | #ifdef DEBUG 161 | INNode * inner = inner_nodes_ + cur_idx; 162 | #endif 163 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 164 | } 165 | cur_idx -= level_offset_[height_]; 166 | 167 | LFNode * cur_leaf = leaf_nodes_ + cur_idx; 168 | 169 | for(int i = 0; i < LEAF_CARD; i++) { 170 | if (cur_leaf->keys[i] == MAX_KEY) { // empty slot 171 | leaf_insert(cur_idx, i, {key, (char *)val}); 172 | return true; 173 | } 174 | } 175 | return false; 176 | } 177 | 178 | bool try_remove(_key_t key) { 179 | int cur_idx = level_offset_[0]; 180 | for(int l = 0; l < height_; l++) { 181 | #ifdef DEBUG 182 | INNode * inner = inner_nodes_ + cur_idx; 183 | #endif 184 | cur_idx = level_offset_[l + 1] + (cur_idx - level_offset_[l]) * INNER_CARD + inner_search(cur_idx, key); 185 | } 186 | cur_idx -= level_offset_[height_]; 187 | 188 | LFNode * cur_leaf = leaf_nodes_ + cur_idx; 189 | 190 | _key_t max_leqkey = cur_leaf->keys[0]; 191 | int8_t max_leqi = 0; 192 | int8_t rec_cnt = 1; 193 | for(int i = 1; i < LEAF_CARD; i++) { 194 | if(cur_leaf->keys[i] != MAX_KEY) { 195 | rec_cnt += 1; 196 | if (cur_leaf->keys[i] <= key && cur_leaf->keys[i] > max_leqkey) { 197 | max_leqkey = cur_leaf->keys[i]; 198 | max_leqi = i; 199 | } 200 | } 201 | } 202 | 203 | /* There are three cases: 204 | 1. | k1 | --- | kx |, delete k1, leaf is not empty if k1 is deleted (fail) 205 | 2. | k1 | --- |, delete k1, leaf is empty if k1 is deleted (success) 206 | 3. | k1 | --- | kx |, delete kx, leaf is not empty if kx is deleted (success) 207 | */ 208 | if(max_leqi == 0 && rec_cnt > 1) { // case 1 209 | return false; 210 | } else { // case 2, 3 211 | persist_assign(&(cur_leaf->keys[max_leqi]), MAX_KEY); 212 | return true; 213 | } 214 | } 215 | 216 | void printAll() { 217 | for(int l = 0; l < height_; l++) { 218 | printf("level: %d =>", l); 219 | 220 | for(int i = level_offset_[l]; i < level_offset_[l + 1]; i++) { 221 | inner_print(i); 222 | } 223 | printf("\n"); 224 | } 225 | 226 | printf("leafs"); 227 | 228 | for(int i = 0; i < leaf_cnt_; i++) { 229 | leaf_print(i); 230 | } 231 | } 232 | 233 | char ** find_first() { 234 | return (char **)&(leaf_nodes_[0].vals[0]); 235 | } 236 | 237 | void merge(std::vector & in, std::vector & out) { // merge the records with in to out 238 | uint32_t insize = in.size(); 239 | 240 | uint32_t incur = 0, innode_pos = 0, cur_lfcnt = 0; 241 | Record tmp[LEAF_CARD]; 242 | load_node(tmp, &leaf_nodes_[0]); 243 | _key_t k1 = in[0].key, k2 = tmp[0].key; 244 | while(incur < insize && cur_lfcnt < leaf_cnt_) { 245 | if(k1 == k2) { 246 | out.push_back(in[incur]); 247 | 248 | incur += 1; 249 | innode_pos += 1; 250 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 251 | cur_lfcnt += 1; 252 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 253 | innode_pos = 0; 254 | } 255 | 256 | k1 = in[incur].key; 257 | k2 = tmp[innode_pos].key; 258 | } else if(k1 > k2) { 259 | out.push_back(tmp[innode_pos]); 260 | 261 | innode_pos += 1; 262 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 263 | cur_lfcnt += 1; 264 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 265 | innode_pos = 0; 266 | } 267 | 268 | k2 = tmp[innode_pos].key;; 269 | } else { 270 | out.push_back(in[incur]); 271 | 272 | incur += 1; 273 | k1 = in[incur].key; 274 | } 275 | } 276 | 277 | if(incur < insize) { 278 | for(int i = incur; i < insize; i++) 279 | out.push_back(in[i]); 280 | } 281 | 282 | if(cur_lfcnt < leaf_cnt_) { 283 | while(cur_lfcnt < leaf_cnt_) { 284 | out.push_back(tmp[innode_pos]); 285 | 286 | innode_pos += 1; 287 | if(innode_pos == LEAF_CARD || tmp[innode_pos].key == MAX_KEY) { 288 | cur_lfcnt += 1; 289 | load_node(tmp, &leaf_nodes_[cur_lfcnt]); 290 | innode_pos = 0; 291 | } 292 | } 293 | } 294 | } 295 | 296 | private: 297 | int inner_search(int node_idx, _key_t key) const{ 298 | INNode * cur_inner = inner_nodes_ + node_idx; 299 | for(int i = 0; i < INNER_CARD; i++) { 300 | if (cur_inner->keys[i] > key) { 301 | return i - 1; 302 | } 303 | } 304 | 305 | return INNER_CARD - 1; 306 | } 307 | 308 | char **leaf_search(int node_idx, _key_t key) const { 309 | LFNode * cur_leaf = leaf_nodes_ + node_idx; 310 | 311 | _key_t max_leqkey = cur_leaf->keys[0]; 312 | int8_t max_leqi = 0; 313 | for(int i = 1; i < LEAF_CARD; i++) { 314 | if (cur_leaf->keys[i] <= key && cur_leaf->keys[i] > max_leqkey) { 315 | max_leqkey = cur_leaf->keys[i]; 316 | max_leqi = i; 317 | } 318 | } 319 | 320 | return (char **) &(cur_leaf->vals[max_leqi]); 321 | } 322 | 323 | bool leaf_insert(int node_idx, int off, Record rec) { // TODO: should do it in a CAS way 324 | leaf_nodes_[node_idx].vals[off] = rec.val; 325 | clwb(&leaf_nodes_[node_idx].vals[off], 8); 326 | mfence(); 327 | 328 | leaf_nodes_[node_idx].keys[off] = rec.key; 329 | clwb(&leaf_nodes_[node_idx].keys[off], 8); 330 | mfence(); 331 | return true; 332 | } 333 | 334 | inline void inner_insert(int node_idx, int off, _key_t key) { 335 | inner_nodes_[node_idx].keys[off] = key; 336 | } 337 | 338 | void inner_print(int node_idx) { 339 | printf("("); 340 | for(int i = 0; i < INNER_CARD; i++) { 341 | printf("%lu ", inner_nodes_[node_idx].keys[i]); 342 | } 343 | printf(") "); 344 | } 345 | 346 | void leaf_print(int node_idx) { 347 | printf("("); 348 | for(int i = 0; i < LEAF_CARD; i++) { 349 | printf("[%lu, %lu] ", leaf_nodes_[node_idx].keys[i], (long unsigned int)leaf_nodes_[node_idx].vals[i]); 350 | } 351 | printf(") \n"); 352 | } 353 | 354 | static void load_node(Record * to, LFNode * from) { 355 | for(int i = 0; i < LEAF_CARD; i++) { 356 | to[i].key = from->keys[i]; 357 | to[i].val = from->vals[i]; 358 | } 359 | 360 | std::sort(to, to + LEAF_CARD); 361 | } 362 | }; 363 | 364 | inline entrance_t * get_entrance(Fixtree * tree) { 365 | return tree->entrance_; 366 | } 367 | 368 | inline void free(Fixtree * tree) { 369 | entrance_t * upent = get_entrance(tree); 370 | delete tree; 371 | 372 | galc->free(galc->absolute(upent->inner_buff)); 373 | galc->free(galc->absolute(upent->leaf_buff)); 374 | galc->free(upent); 375 | 376 | return ; 377 | } 378 | 379 | typedef Fixtree uptree_t; 380 | 381 | } // namespace fixtree 382 | 383 | #endif //__FIXTREE__ -------------------------------------------------------------------------------- /Single/src/flush.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | 6 | #ifndef __FLUSH_H__ 7 | #define __FLUSH_H__ 8 | 9 | #include 10 | 11 | #include "common.h" 12 | 13 | static inline void mfence() { 14 | asm volatile("sfence" ::: "memory"); 15 | } 16 | 17 | static inline void flush(void * ptr) { 18 | #ifdef CLWB 19 | _mm_clwb(ptr); 20 | #elif defined(CLFLUSHOPT) 21 | _mm_clflushopt(ptr); 22 | #else 23 | _mm_clflush(ptr); 24 | #endif 25 | } 26 | 27 | inline void clwb(void *data, int len) { 28 | #ifdef DOFLUSH 29 | volatile char *ptr = (char *)((unsigned long long)data &~(CACHE_LINE_SIZE-1)); 30 | for(; ptr < (char *)data + len; ptr += CACHE_LINE_SIZE) { 31 | flush((void *)ptr); 32 | } 33 | #endif //DOFLUSH 34 | } 35 | 36 | inline void clflush(void *data, int len, bool fence=true) 37 | { 38 | #ifdef DOFLUSH 39 | volatile char *ptr = (char *)((unsigned long long)data &~(CACHE_LINE_SIZE-1)); 40 | if(fence) mfence(); 41 | for(; ptr < (char *)data + len; ptr += CACHE_LINE_SIZE){ 42 | flush((void *)ptr); 43 | } 44 | if(fence) mfence(); 45 | #endif //DOFLUSH 46 | } 47 | 48 | template 49 | inline void persist_assign(T* addr, const T &v) { // To ensure atomicity, the size of T should be less equal than 8 50 | *addr = v; 51 | clwb(addr, sizeof(T)); 52 | } 53 | 54 | #endif // __FLUSH_H__ -------------------------------------------------------------------------------- /Single/src/pmallocator.h: -------------------------------------------------------------------------------- 1 | /* 2 | A wrapper for using PMDK allocator easily (refer to pmwcas) 3 | Copyright (c) Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 4 | USE AT YOUR OWN RISK! 5 | */ 6 | 7 | #ifndef __BLKALLOCATOR_H__ 8 | #define __BLKALLOCATOR_H__ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #include "common.h" 15 | #include "flush.h" 16 | 17 | POBJ_LAYOUT_BEGIN(pmallocator); 18 | POBJ_LAYOUT_TOID(pmallocator, char) 19 | POBJ_LAYOUT_END(pmallocator) 20 | 21 | /* 22 | Persistent Memory Allocator: a wrapper of PMDK allocation lib: https://pmem.io/pmdk/ 23 | 24 | PMAllocator allocates persistent memory from a pool file that resides on NVM file system. 25 | It uses malloc() and free() as the allocation and reclaiment interfaces. 26 | Other public interfaces like get_root(), absolute() and relative() are essential to memory 27 | management in persistent environment. 28 | */ 29 | class PMAllocator { 30 | private: 31 | static const int PEICE_CNT = 64; 32 | static const size_t ALIGN_SIZE = 256; 33 | 34 | struct MetaType { 35 | char * buffer[PEICE_CNT]; 36 | size_t blk_per_piece; 37 | size_t cur_blk; 38 | // entrance of DS in buffer 39 | void * entrance; 40 | }; 41 | MetaType * meta_; 42 | 43 | // volatile domain 44 | PMEMobjpool *pop_; 45 | 46 | char * buff_[PEICE_CNT]; 47 | char * buff_aligned_[PEICE_CNT]; 48 | size_t piece_size_; 49 | size_t cur_blk_; 50 | size_t max_blk_; 51 | 52 | public: 53 | /* 54 | * Construct a PM allocator, map a pool file into virtual memory 55 | * @param filename pool file name 56 | * @param recover if doing recover, false for the first time 57 | * @param layout_name ID of a group of allocations (in characters), each ID corresponding to a root entry 58 | * @param pool_size pool size of the pool file, vaild if the file doesn't exist 59 | */ 60 | PMAllocator(const char *file_name, bool recover, const char *layout_name, uint64_t pool_size) { 61 | PMEMobjpool *tmp_pool = nullptr; 62 | pool_size = pool_size + ((pool_size & ((1 << 23) - 1)) > 0 ? (1 << 23) : 0); // align to 8MB 63 | if(recover == false) { 64 | if(file_exist(file_name)) { 65 | printf("[CAUTIOUS]: The pool file already exists\n"); 66 | printf("Try (1) remove the pool file %s\nOr (2) set the recover parameter to be true\n", file_name); 67 | exit(-1); 68 | } 69 | pop_ = pmemobj_create(file_name, layout_name, pool_size, S_IWUSR | S_IRUSR); 70 | meta_ = (MetaType *)pmemobj_direct(pmemobj_root(pop_, sizeof(MetaType))); 71 | 72 | // maintain volatile domain 73 | uint64_t alloc_size = (pool_size >> 1) + (pool_size >> 2) + (pool_size >> 3); // 7/8 of the pool is used as block alloction 74 | for(int i = 0; i < PEICE_CNT; i++) { 75 | buff_[i] = (char *)mem_alloc(alloc_size / PEICE_CNT); 76 | buff_aligned_[i] = (char *) ((uint64_t)buff_[i] + ((uint64_t) buff_[i] % ALIGN_SIZE == 0 ? 0 : (ALIGN_SIZE - (uint64_t) buff_[i] % ALIGN_SIZE))); 77 | } 78 | piece_size_ = (alloc_size / PEICE_CNT) / ALIGN_SIZE - 1; 79 | cur_blk_ = 0; 80 | max_blk_ = piece_size_ * PEICE_CNT; 81 | 82 | // initialize meta_ 83 | for(int i = 0; i < PEICE_CNT; i++) 84 | meta_->buffer[i] = relative(buff_[i]); 85 | meta_->blk_per_piece = piece_size_; 86 | meta_->cur_blk = 0; 87 | meta_->entrance = NULL; 88 | clwb(meta_, sizeof(MetaType)); 89 | } else { 90 | if(!file_exist(file_name)) { 91 | printf("Pool File Not Exist\n"); 92 | exit(-1); 93 | } 94 | pop_ = pmemobj_open(file_name, layout_name); 95 | meta_ = (MetaType *)pmemobj_direct(pmemobj_root(pop_, sizeof(MetaType))); 96 | // maintain volatile domain 97 | for(int i = 0; i < PEICE_CNT; i++) { 98 | buff_[i] = absolute(meta_->buffer[i]); 99 | buff_aligned_[i] = (char *) ((uint64_t)buff_[i] + ((uint64_t) buff_[i] % ALIGN_SIZE == 0 ? 0 : (ALIGN_SIZE - (uint64_t) buff_[i] % ALIGN_SIZE))); 100 | } 101 | cur_blk_ = meta_->cur_blk; 102 | piece_size_ = meta_->blk_per_piece; 103 | max_blk_ = piece_size_ * PEICE_CNT; 104 | } 105 | } 106 | 107 | ~PMAllocator() { 108 | pmemobj_close(pop_); 109 | } 110 | 111 | public: 112 | /* 113 | * Get/allocate the root entry of the allocator. 114 | * 115 | * The root entry is the entrance of one group of allocation, each group is 116 | * identified by the layout_name when constructing it. 117 | * 118 | * Each group of allocations is a independent, self-contained in-memory structure in the pool 119 | * such as b-tree or link-list 120 | */ 121 | void * get_root(size_t nsize) { // the root of DS stored in buff_ is recorded at meta_->entrance 122 | if(meta_->entrance == NULL) { 123 | meta_->entrance = relative(malloc(nsize)); 124 | clwb(meta_, sizeof(MetaType)); 125 | } 126 | return absolute(meta_->entrance); 127 | } 128 | 129 | /* 130 | * Allocate a non-root piece of persistent memory from the mapped pool 131 | * return the virtual memory address 132 | */ 133 | void * malloc(size_t nsize) { 134 | if(nsize >= (1 << 12)) { // large than 4KB 135 | void * mem = mem_alloc(nsize + ALIGN_SIZE); // not aligned 136 | // | UNUSED |HEADER| memory you can use | 137 | // mem (mem + off) 138 | uint64_t offset = ALIGN_SIZE - (uint64_t)mem % ALIGN_SIZE; 139 | // store a header in the front 140 | uint64_t * header = (uint64_t *)((uint64_t)mem + offset - 8); 141 | *header = offset; 142 | 143 | return (void *)((uint64_t)mem + offset); 144 | } 145 | 146 | int blk_demand = (nsize + ALIGN_SIZE - 1) / ALIGN_SIZE; 147 | // case 1: not enough in the buffer 148 | if(blk_demand + cur_blk_ > max_blk_) { 149 | printf("run out of memory\n"); 150 | exit(-1); 151 | } 152 | // case 2: current piece can not accommdate this allocation 153 | int piece_id = cur_blk_ / piece_size_; 154 | if((cur_blk_ % piece_size_ + blk_demand) > piece_size_) { 155 | void * mem = buff_aligned_[piece_id + 1]; // allocate from a new peice 156 | 157 | cur_blk_ = piece_size_ * (piece_id + 1) + blk_demand; 158 | meta_->cur_blk = cur_blk_; 159 | clwb(&(meta_->cur_blk), 8); 160 | 161 | return mem; 162 | } 163 | // case 3: current piece has enough space 164 | else { 165 | void * mem = buff_aligned_[piece_id] + ALIGN_SIZE * (cur_blk_ % piece_size_); 166 | 167 | cur_blk_ = cur_blk_ + blk_demand; 168 | meta_->cur_blk = cur_blk_; 169 | clwb(&(meta_->cur_blk), 8); 170 | 171 | return mem; 172 | } 173 | } 174 | 175 | void free(void* addr) { 176 | for(int i = 0; i < PEICE_CNT; i++) { 177 | uint64_t offset = (uint64_t)addr - (uint64_t)buff_aligned_[i]; 178 | if(offset > 0 && offset < piece_size_ * ALIGN_SIZE) { 179 | // the addr is in this piece, do not reclaim it 180 | return ; 181 | } 182 | } 183 | 184 | // larger than 4KB, reclaim it 185 | uint64_t * header = (uint64_t *)((uint64_t)addr - 8); 186 | uint64_t offset = *header; 187 | 188 | auto oid_ptr = pmemobj_oid((void *)((uint64_t)addr - offset)); 189 | TOID(char) ptr_cpy; 190 | TOID_ASSIGN(ptr_cpy, oid_ptr); 191 | POBJ_FREE(&ptr_cpy); 192 | } 193 | 194 | /* 195 | * Distinguish from virtual memory address and offset in the pool 196 | * Each memory piece allocated from the pool has an in-pool offset, which remains unchanged 197 | * until reclaiment. We cannot ensure that the pool file is mapped at the same position at 198 | * any time, so it may locate at different virtual memory addresses next time. 199 | * 200 | * So the rule is that, using virtual memory when doing normal operations like to DRAM 201 | * space, using offset to store link relationship, for exmaple, next pointer in linklist 202 | * / 203 | 204 | /* 205 | * convert the virtual memory address to an offset 206 | */ 207 | template 208 | inline T *absolute(T *pmem_offset) { 209 | if(pmem_offset == NULL) 210 | return NULL; 211 | return reinterpret_cast(reinterpret_cast(pmem_offset) + reinterpret_cast(pop_)); 212 | } 213 | 214 | template 215 | inline T *relative(T *pmem_direct) { 216 | if(pmem_direct == NULL) 217 | return NULL; 218 | return reinterpret_cast(reinterpret_cast(pmem_direct) - reinterpret_cast(pop_)); 219 | } 220 | 221 | private: 222 | void * mem_alloc(size_t nsize) { 223 | PMEMoid tmp; 224 | pmemobj_alloc(pop_, &tmp, nsize, TOID_TYPE_NUM(char), NULL, NULL); 225 | 226 | void * mem = pmemobj_direct(tmp); 227 | assert(mem != nullptr); 228 | return mem; 229 | } 230 | }; 231 | 232 | extern PMAllocator * galc; 233 | 234 | #endif // __BLKALLOCATOR_H__ 235 | -------------------------------------------------------------------------------- /Single/src/spinlock.h: -------------------------------------------------------------------------------- 1 | /* Copyright(c): Guo Zhongming 2 | */ 3 | 4 | #ifndef __SPINLOCK_H__ 5 | #define __SPINLOCK_H__ 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | class Spinlock { 12 | public: 13 | Spinlock() { 14 | atomic_val.store(0, std::memory_order_relaxed); 15 | } 16 | 17 | Spinlock(const Spinlock &) = delete; 18 | Spinlock & operator = (const Spinlock &) = delete; 19 | 20 | public: 21 | inline void lock() { 22 | while(atomic_val.exchange(1, std::memory_order_acquire) == 1){ 23 | while(1) { 24 | _mm_pause(); // delay for 140 cycle 25 | 26 | if(atomic_val.load(std::memory_order_relaxed) == 0) // check the atomic_val 27 | break; 28 | 29 | std::this_thread::yield(); // delay for 113ns 30 | 31 | if(atomic_val.load(std::memory_order_relaxed) == 0) // check the atomic_val 32 | break; 33 | } 34 | 35 | // if at here, the atomic_val must be just be 0 36 | } 37 | 38 | return ; 39 | } 40 | 41 | inline void unlock() { 42 | atomic_val.exchange(0, std::memory_order_acquire); 43 | } 44 | 45 | inline bool trylock() { 46 | return atomic_val.exchange(1, std::memory_order_acquire) == 0; 47 | } 48 | 49 | private: 50 | std::atomic_short atomic_val; 51 | }; 52 | 53 | #endif // __SPINLOCK_H__ -------------------------------------------------------------------------------- /Single/src/tlbtree_impl.cc: -------------------------------------------------------------------------------- 1 | #include "tlbtree_impl.h" 2 | 3 | PMAllocator * galc; -------------------------------------------------------------------------------- /Single/src/tlbtree_impl.h: -------------------------------------------------------------------------------- 1 | /* tlbtree.h - A two level btree for persistent memory 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | 6 | #ifndef __TLBTREEIMPL_H__ 7 | #define __TLBTREEIMPL_H__ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "pmallocator.h" 15 | #include "fixtree.h" 16 | #include "spinlock.h" 17 | #include "wotree256.h" 18 | 19 | #define BACKGROUND_REBUILD true 20 | #define REBUILD_RECOVER false 21 | 22 | // choose uptree type, providing interfaces: insert, remove, update, find, merge, free_uptree 23 | #define UPTREE_NS fixtree 24 | // choose downtree type, providing interfaces: insert, find_lower, remove_lower 25 | #define DOWNTREE_NS wotree256 26 | 27 | namespace tlbtree { 28 | using std::string; 29 | using std::vector; 30 | using Node = DOWNTREE_NS::Node; 31 | 32 | template 33 | class TLBtreeImpl { 34 | private: 35 | typedef TLBtreeImpl SelfType; 36 | 37 | // the entrance of TLBtree that stores its persistent tree metadata 38 | struct tlbtree_entrance_t { 39 | UPTREE_NS::entrance_t * upent; // the entrance of the top layer 40 | Record * restore; // restore subroots that fails to insert into the top layer 41 | int restore_size; 42 | bool is_clean; // is TLBtree shutdown expectedly 43 | bool use_rebuild_recover; // whether to use recover rebuilding next time 44 | }; 45 | 46 | // volatile domain 47 | UPTREE_NS::uptree_t * uptree_; 48 | tlbtree_entrance_t * entrance_; 49 | vector * mutable_; 50 | Spinlock rebuild_mtx_; 51 | bool is_rebuilding_; 52 | 53 | public: 54 | TLBtreeImpl(string path, bool recover, uint64_t pool_size) { 55 | mutable_ = new vector(); 56 | mutable_->reserve(0xfff); 57 | bool is_rebuilding_ = false; 58 | 59 | if(recover == false) { 60 | galc = new PMAllocator(path.c_str(), false, "tlbtree", pool_size); 61 | // initialize entrance_ 62 | entrance_ = (tlbtree_entrance_t *) galc->get_root(sizeof(tlbtree_entrance_t)); 63 | entrance_->upent = NULL; 64 | entrance_->restore = NULL; 65 | entrance_->restore_size = 0; 66 | entrance_->is_clean = false; 67 | entrance_->use_rebuild_recover = true; 68 | clwb(entrance_, sizeof(tlbtree_entrance_t)); 69 | 70 | //allocate a entrance_ to the fixtree 71 | std::vector init = {Record(MIN_KEY, (char *)galc->relative(new Node()))}; 72 | uptree_ = new UPTREE_NS::uptree_t(init); 73 | persist_assign(&(entrance_->upent), galc->relative(UPTREE_NS::get_entrance(uptree_))); 74 | persist_assign(&(entrance_->use_rebuild_recover), REBUILD_RECOVER); // use fast rebuilding next time 75 | } else { 76 | galc = new PMAllocator(path.c_str(), true, "tlbtree", pool_size); 77 | 78 | entrance_ = (tlbtree_entrance_t *) galc->get_root(sizeof(tlbtree_entrance_t)); 79 | if(entrance_ == NULL || entrance_->upent == NULL) { // empty tree 80 | printf("the tree is empty\n"); 81 | exit(-1); 82 | } 83 | 84 | if(entrance_->is_clean == false) { // TLBtree crashed at last usage 85 | persist_assign(&(entrance_->use_rebuild_recover), true); // use recover rebuilding next time 86 | } else { // normal shutdown 87 | // recover all subroots from PM back to mutable_, within miliseconds 88 | if(entrance_->restore != NULL) { 89 | Record * rec = galc->absolute(entrance_->restore); 90 | for(int i = 0; i < entrance_->restore_size; i++) { 91 | mutable_->push_back(rec[i]); 92 | } 93 | entrance_->restore = NULL; 94 | entrance_->restore_size = 0; 95 | clwb(&entrance_->restore, 16); 96 | galc->free(rec); 97 | } 98 | } 99 | 100 | uptree_ = new UPTREE_NS::uptree_t (galc->absolute(entrance_->upent)); 101 | } 102 | 103 | persist_assign(&(entrance_->is_clean), false); // set the TLBtree state to be dirty 104 | } 105 | 106 | ~TLBtreeImpl() { 107 | if(entrance_->use_rebuild_recover == false) { // fast rebuilding next time 108 | // save all subroots in mutable_ into PM 109 | Record * rec = (Record *) galc->malloc(std::max((size_t)4096, mutable_->size() * sizeof(Record))); 110 | for(int i = 0; i < mutable_->size(); i++) { 111 | rec[i] = (*mutable_)[i]; 112 | } 113 | clwb(rec, mutable_->size() * sizeof(Record)); 114 | mfence(); 115 | entrance_->restore = galc->relative(rec); 116 | entrance_->restore_size = mutable_->size(); 117 | clwb(&entrance_->restore, 16); 118 | } 119 | 120 | 121 | persist_assign(&(entrance_->is_clean), true); // a intended shutdown 122 | 123 | delete uptree_; 124 | delete mutable_; 125 | delete galc; 126 | } 127 | 128 | public: // public interface 129 | void insert(const _key_t & k, uint64_t v) { 130 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 131 | Node * downroot = (Node *)galc->absolute(*root_ptr); 132 | 133 | // travese in sibling chain 134 | int8_t goes_steps = 0; 135 | _key_t splitkey; Node ** sibling_ptr; 136 | downroot->get_sibling(splitkey, sibling_ptr); 137 | while(splitkey < k) { // the splitkey 138 | root_ptr = sibling_ptr; // where is current root store 139 | downroot = (Node *)galc->absolute(*root_ptr); 140 | downroot->get_sibling(splitkey, sibling_ptr); 141 | goes_steps += 1; 142 | } 143 | res_t insert_res = DOWNTREE_NS::insert(root_ptr, k, v, DOWNLEVEL); 144 | 145 | // we rebuild if the searching in the linklist is too long 146 | if(goes_steps > REBUILD_THRESHOLD && rebuild_mtx_.trylock()) { 147 | if(entrance_->use_rebuild_recover == true) { 148 | #ifdef BACKGROUND_REBUILD 149 | std::thread rebuild_thread(&SelfType::rebuild_recover, this); 150 | rebuild_thread.detach(); 151 | #else 152 | rebuild_recover(); 153 | #endif 154 | } else { 155 | #ifdef BACKGROUND_REBUILD 156 | std::thread rebuild_thread(&SelfType::rebuild_fast, this); 157 | rebuild_thread.detach(); 158 | #else 159 | rebuild_fast(); 160 | #endif 161 | } 162 | } 163 | 164 | if(insert_res.flag == true) { // a sub-index tree is splitted 165 | // try save the sub-indices root into the top layer 166 | bool succ = uptree_->insert(insert_res.rec.key, (uint64_t)galc->relative(insert_res.rec.val)); 167 | 168 | // save these records into mutable_ 169 | if(is_rebuilding_ == true || succ == false) { 170 | mutable_->push_back({insert_res.rec.key, (char *)galc->relative(insert_res.rec.val)}); 171 | } 172 | } 173 | } 174 | 175 | bool find(const _key_t & k, uint64_t & v) { 176 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 177 | Node * downroot = (Node *)galc->absolute(*root_ptr); 178 | 179 | // traverse in sibling chain 180 | _key_t splitkey; Node ** sibling_ptr; 181 | downroot->get_sibling(splitkey, sibling_ptr); 182 | while(splitkey <= k) { // the splitkey 183 | root_ptr = sibling_ptr; // where is current root store 184 | downroot = (Node *)galc->absolute(*root_ptr); 185 | downroot->get_sibling(splitkey, sibling_ptr); 186 | } 187 | 188 | return DOWNTREE_NS::find(root_ptr, k, v); 189 | } 190 | 191 | bool remove(const _key_t & k) { 192 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 193 | Node ** last_root_ptr = NULL; // record the last root ptr for laster use 194 | Node *downroot = (Node *)galc->absolute(*root_ptr); 195 | 196 | // travese in sibling chain 197 | _key_t splitkey; Node ** sibling_ptr; 198 | downroot->get_sibling(splitkey, sibling_ptr); 199 | while(splitkey < k) { // the splitkey 200 | root_ptr = sibling_ptr; // where is current root store 201 | downroot = (Node *)galc->absolute(*root_ptr); 202 | downroot->get_sibling(splitkey, sibling_ptr); 203 | } 204 | 205 | bool emptyif = DOWNTREE_NS::remove(root_ptr, k); 206 | if(emptyif) { // the DOWNTREE_NS is empty now 207 | uptree_->try_remove(k); // TODO: rebuilding should also be triggered when the top layer is too empty 208 | } 209 | 210 | return true; 211 | } 212 | 213 | bool update(const _key_t & k, const uint64_t & v) { 214 | Node ** root_ptr = (Node **)uptree_->find_lower(k); 215 | Node * downroot = (Node *)galc->absolute(*root_ptr); 216 | 217 | // travese in sibling chain 218 | _key_t splitkey; Node ** sibling_ptr; 219 | downroot->get_sibling(splitkey, sibling_ptr); 220 | while(splitkey < k) { // the splitkey 221 | root_ptr = sibling_ptr; // where is current root store 222 | downroot = (Node *)galc->absolute(*root_ptr); 223 | downroot->get_sibling(splitkey, sibling_ptr); 224 | } 225 | 226 | return DOWNTREE_NS::update(root_ptr, k, v); 227 | } 228 | 229 | void printAll() { 230 | uptree_->printAll(); 231 | } 232 | 233 | private: 234 | void rebuild_fast() { // fast rebuilding function 235 | // switch the restore to be immutable 236 | vector * new_mutable = new vector; 237 | new_mutable->reserve(0xffff); 238 | vector * immutable = mutable_; // make the restore vector be immutable 239 | mutable_ = new_mutable; // before this line, the mutable_ is still the old one 240 | 241 | is_rebuilding_ = true; 242 | 243 | std::sort(immutable->begin(), immutable->end()); 244 | // get the snapshot of all sub-index trees by combining the top layer with immutable 245 | std::vector subroots; 246 | subroots.reserve(0x2ffff); 247 | uptree_->merge(*immutable, subroots); 248 | 249 | /* rebuild the top layer with immutable */ 250 | UPTREE_NS::uptree_t * old_tree = uptree_; 251 | UPTREE_NS::entrance_t * old_upent = galc->absolute(entrance_->upent); 252 | UPTREE_NS::uptree_t * new_tree = new UPTREE_NS::uptree_t(subroots); 253 | UPTREE_NS::entrance_t * new_upent = UPTREE_NS::get_entrance(new_tree); 254 | 255 | // install the new top layer 256 | persist_assign(&(entrance_->upent), galc->relative(new_upent)); 257 | uptree_ = new_tree; 258 | 259 | /* free the old top layer */ 260 | #ifdef BACKGROUND_REBUILD 261 | usleep(50); // TODO: wait until on-going readers finish 262 | #endif 263 | UPTREE_NS::free(old_tree); // free the old_tree 264 | 265 | is_rebuilding_ = false; 266 | rebuild_mtx_.unlock(); 267 | 268 | delete immutable; 269 | } 270 | 271 | void rebuild_recover() { // slow rebuilding function 272 | is_rebuilding_ = true; 273 | // get the snapshot of all sub-index trees by traverse in the down layer 274 | std::vector subroots; 275 | subroots.reserve(0x2fffff); 276 | 277 | _key_t split_key = 0; 278 | Node ** sibling_ptr = (Node **)uptree_->find_first(); 279 | Node * cur_root = (Node *)galc->absolute(*sibling_ptr); 280 | while (cur_root != NULL) { 281 | subroots.emplace_back(split_key, (char *)(*sibling_ptr)); 282 | // get next sibling 283 | cur_root->get_sibling(split_key, sibling_ptr); 284 | cur_root = galc->absolute(*sibling_ptr); 285 | } 286 | 287 | /* rebuild the top layer with immutable */ 288 | UPTREE_NS::uptree_t * old_tree = uptree_; 289 | UPTREE_NS::entrance_t * old_upent = galc->absolute(entrance_->upent); 290 | UPTREE_NS::uptree_t * new_tree = new UPTREE_NS::uptree_t(subroots); 291 | UPTREE_NS::entrance_t * new_upent = UPTREE_NS::get_entrance(new_tree); 292 | 293 | // install the new top layer 294 | persist_assign(&(entrance_->upent), galc->relative(new_upent)); 295 | uptree_ = new_tree; 296 | 297 | /* free the old top layer */ 298 | #ifdef BACKGROUND_REBUILD 299 | usleep(50); // TODO: wait until on-going readers finish 300 | #endif 301 | UPTREE_NS::free(old_tree); // free the old_tree 302 | 303 | is_rebuilding_ = false; 304 | rebuild_mtx_.unlock(); 305 | 306 | persist_assign(&(entrance_->use_rebuild_recover), REBUILD_RECOVER); // use fast rebuilding next time 307 | } 308 | }; 309 | 310 | } // tlbtree namespace 311 | 312 | #endif //__TLBTREEIMPL_H__ -------------------------------------------------------------------------------- /Single/src/wotree256.cc: -------------------------------------------------------------------------------- 1 | #include "wotree256.h" 2 | 3 | namespace wotree256 { 4 | 5 | bool insert_recursive(Node * n, _key_t k, uint64_t v, _key_t &split_k, Node * &split_node, int8_t &level) { 6 | if(n->leftmost_ptr_ == NULL) { 7 | return n->store(k, v, split_k, split_node); 8 | } else { 9 | level++; 10 | Node * child = (Node *) galc->absolute(n->get_child(k)); 11 | 12 | _key_t split_k_child; 13 | Node * split_node_child; 14 | bool splitIf = insert_recursive(child, k, v, split_k_child, split_node_child, level); 15 | 16 | if(splitIf) { 17 | return n->store(split_k_child, (uint64_t)galc->relative(split_node_child), split_k, split_node); 18 | } 19 | return false; 20 | } 21 | } 22 | 23 | bool remove_recursive(Node * n, _key_t k) { 24 | if(n->leftmost_ptr_ == NULL) { 25 | n->remove(k); 26 | return n->state_.unpack.count < UNDERFLOW_CARD; 27 | } 28 | else { 29 | Node * child = (Node *) galc->absolute(n->get_child(k)); 30 | 31 | bool shouldMrg = remove_recursive(child, k); 32 | 33 | if(shouldMrg) { 34 | Node *leftsib = NULL, *rightsib = NULL; 35 | n->get_lrchild(k, leftsib, rightsib); 36 | 37 | if(leftsib != NULL && (child->state_.unpack.count + leftsib->state_.unpack.count) < CARDINALITY) { 38 | // merge with left node 39 | int8_t slotid = child->state_.read(0); 40 | n->remove(child->recs_[slotid].key); 41 | Node::merge(leftsib, child); 42 | 43 | return n->state_.unpack.count < UNDERFLOW_CARD; 44 | } else if (rightsib != NULL && (child->state_.unpack.count + rightsib->state_.unpack.count) < CARDINALITY) { 45 | // merge with right node 46 | int8_t slotid = rightsib->state_.read(0); 47 | n->remove(rightsib->recs_[slotid].key); 48 | Node::merge(child, rightsib); 49 | 50 | return n->state_.unpack.count < UNDERFLOW_CARD; 51 | } 52 | } 53 | return false; 54 | } 55 | } 56 | 57 | bool find(Node ** rootPtr, _key_t key, uint64_t &val) { 58 | Node * cur = galc->absolute(*rootPtr); 59 | while(cur->leftmost_ptr_ != NULL) { // no prefetch here 60 | char * child_ptr = cur->get_child(key); 61 | cur = (Node *)galc->absolute(child_ptr); 62 | } 63 | 64 | val = (uint64_t) cur->get_child(key); 65 | 66 | if((char *)val == NULL) 67 | return false; 68 | else 69 | return true; 70 | } 71 | 72 | res_t insert(Node ** rootPtr, _key_t key, uint64_t val, int threshold) { 73 | Node *root_= galc->absolute(*rootPtr); 74 | 75 | int8_t level = 1; 76 | _key_t split_k; 77 | Node * split_node; 78 | bool splitIf = insert_recursive(root_, key, val, split_k, split_node, level); 79 | 80 | if(splitIf) { 81 | if(level < threshold) { 82 | Node *new_root = new Node; 83 | new_root->leftmost_ptr_ = (char *)galc->relative(root_); 84 | new_root->append({split_k, (char *)galc->relative(split_node)}, 0, 0); 85 | new_root->state_.unpack.count = 1; 86 | 87 | clwb(new_root, 64); 88 | 89 | mfence(); // a barrier to make sure the new node is persisted 90 | persist_assign(rootPtr, (Node *)galc->relative(new_root)); 91 | 92 | return res_t(false, {0, NULL}); 93 | } else { 94 | return res_t(true, {split_k, (char *)split_node}); 95 | } 96 | } 97 | else { 98 | return res_t(false, {0, NULL}); 99 | } 100 | } 101 | 102 | bool update(Node ** rootPtr, _key_t key, uint64_t val) { 103 | Node * cur = galc->absolute(*rootPtr); 104 | while(cur->leftmost_ptr_ != NULL) { // no prefetch here 105 | char * child_ptr = cur->get_child(key); 106 | cur = (Node *)galc->absolute(child_ptr); 107 | } 108 | 109 | val = (uint64_t) cur->update(key, val); 110 | return true; 111 | } 112 | 113 | bool remove(Node ** rootPtr, _key_t key) { 114 | Node *root_= galc->absolute(*rootPtr); 115 | if(root_->leftmost_ptr_ == NULL) { 116 | root_->remove(key); 117 | 118 | return root_->state_.unpack.count == 0; 119 | } 120 | else { 121 | Node * child = (Node *) galc->absolute(root_->get_child(key)); 122 | 123 | bool shouldMrg = remove_recursive(child, key); 124 | 125 | if(shouldMrg) { 126 | Node *leftsib = NULL, *rightsib = NULL; 127 | root_->get_lrchild(key, leftsib, rightsib); 128 | 129 | if(leftsib != NULL && (child->state_.unpack.count + leftsib->state_.unpack.count) < CARDINALITY) { 130 | // merge with left node 131 | int8_t slotid = child->state_.read(0); 132 | root_->remove(child->recs_[slotid].key); 133 | Node::merge(leftsib, child); 134 | } 135 | else if (rightsib != NULL && (child->state_.unpack.count + rightsib->state_.unpack.count) < CARDINALITY) { 136 | // merge with right node 137 | int8_t slotid = rightsib->state_.read(0); 138 | root_->remove(rightsib->recs_[slotid].key); 139 | Node::merge(child, rightsib); 140 | } 141 | 142 | if(root_->state_.unpack.count == 0) { // the root is empty 143 | Node * old_root = root_; 144 | 145 | persist_assign(rootPtr, (Node *)root_->leftmost_ptr_); 146 | 147 | galc->free(old_root); 148 | } 149 | } 150 | 151 | return false; 152 | } 153 | } 154 | 155 | void printAll(Node ** rootPtr) { 156 | Node *root= galc->absolute(*rootPtr); 157 | root->print("", true); 158 | } 159 | 160 | } // namespace wotree256 -------------------------------------------------------------------------------- /Single/src/wotree256.h: -------------------------------------------------------------------------------- 1 | /* 2 | log free wbtree with 256B nodesize, nonclass version of wbtree_slotonly 3 | Copyright(c) Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 4 | USE AT YOUR OWN RISK! 5 | */ 6 | 7 | #ifndef __WOTREE256__ 8 | #define __WOTREE256__ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "flush.h" 16 | #include "pmallocator.h" 17 | 18 | namespace wotree256 { 19 | using std::string; 20 | constexpr int CARDINALITY = 13; 21 | constexpr int UNDERFLOW_CARD = 4; 22 | 23 | struct state_t { 24 | struct statefield_t { // totally 8 bytes 25 | uint64_t slotArray : 52; 26 | uint64_t count : 4; 27 | uint64_t sibling_version : 1; 28 | uint64_t latch : 1; 29 | uint64_t node_version : 6; 30 | }; 31 | // the real data field of state 32 | union { 33 | uint64_t pack; // to do 8 bytes assignment 34 | statefield_t unpack;// to facilite accessing subfields 35 | }; 36 | 37 | public: 38 | state_t(uint64_t s = 0): pack(s) {} 39 | 40 | inline int8_t read(int8_t idx) const { 41 | uint64_t p = this->unpack.slotArray << 12; 42 | return (p & ((uint64_t)0xf << ((15 - idx) * 4))) >> ((15 - idx) * 4); 43 | } 44 | 45 | inline int8_t alloc() { 46 | int8_t occupy[CARDINALITY] = {0}; 47 | for(int64_t i = 0; i < unpack.count; i++) { 48 | occupy[read(i)] = 1; 49 | } 50 | for(int i = 0; i < CARDINALITY; i++) { 51 | if(occupy[i] == 0) return i; 52 | } 53 | #ifdef DEBUG 54 | assert(false); 55 | #endif 56 | return CARDINALITY; // never be here 57 | } 58 | 59 | inline uint64_t add(int8_t idx, int8_t slot) { 60 | state_t new_state(this->pack); 61 | 62 | // update bit fields 63 | uint64_t p = this->unpack.slotArray << 12; 64 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 65 | uint64_t add_value = (uint64_t)slot << ((15 - idx) * 4); 66 | new_state.unpack.slotArray = ((p & (~mask)) + add_value + ((p & mask) >> 4)) >> 12; 67 | new_state.unpack.count++; 68 | 69 | return new_state.pack; 70 | } 71 | 72 | inline uint64_t remove(int idx) { // delete a slot id at position idx 73 | state_t new_state(this->pack); 74 | // update bit fields 75 | uint64_t p = this->unpack.slotArray << 12; 76 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 77 | new_state.unpack.slotArray = ((p & ~mask) + ((p & (mask>>4)) << 4)) >> 12; 78 | new_state.unpack.count--; 79 | 80 | return new_state.pack; 81 | } 82 | 83 | inline uint64_t append(int8_t idx, int8_t slot) { 84 | // Append the record at slotid, append the slotArray entry, but DO NOT modify the count 85 | state_t new_state(this->pack); 86 | 87 | // update bit fields 88 | uint64_t p = this->unpack.slotArray << 12; 89 | uint64_t mask = 0xffffffffffffffff >> (idx * 4); 90 | uint64_t add_value = (uint64_t)slot << ((15 - idx) * 4); 91 | new_state.unpack.slotArray = ((p & (~mask)) + add_value + ((p & mask) >> 4)) >> 12; 92 | 93 | return new_state.pack; 94 | } 95 | }; 96 | 97 | class Node { 98 | public: 99 | // First Cache Line 100 | state_t state_; // a very complex and compact state field 101 | char * leftmost_ptr_;// the left most child of current node 102 | Record siblings_[2]; // shadow sibling of current node 103 | // Slots 104 | Record recs_[CARDINALITY]; 105 | 106 | friend class wbtree; 107 | 108 | public: 109 | Node(bool isleaf = false): state_(0), leftmost_ptr_(NULL) { 110 | siblings_[0] = {MAX_KEY, NULL}; 111 | siblings_[1] = {MAX_KEY, NULL}; 112 | } 113 | 114 | void *operator new(size_t size) { 115 | void * ret = galc->malloc(size); 116 | return ret; 117 | } 118 | 119 | bool store(_key_t k, uint64_t v, _key_t & split_k, Node * & split_node) { 120 | if(state_.unpack.count == CARDINALITY) { // should split the node 121 | uint64_t m = state_.unpack.count / 2; 122 | split_k = recs_[state_.read(m)].key; 123 | 124 | // copy half of the records into split node 125 | int8_t j = 0; 126 | state_t new_state = state_; 127 | if(leftmost_ptr_ == NULL) { 128 | split_node = new Node(); 129 | for(int i = m; i < state_.unpack.count; i++) { 130 | int8_t slotid = state_.read(i); 131 | split_node->append(recs_[slotid], j, j); 132 | j += 1; 133 | } 134 | 135 | new_state.unpack.count -= j; 136 | } else { 137 | int8_t slotid = state_.read(m); 138 | split_node = new Node(); 139 | split_node->leftmost_ptr_ = recs_[slotid].val; 140 | 141 | for(int i = m + 1; i < state_.unpack.count; i++) { 142 | slotid = state_.read(i); 143 | split_node->append(recs_[slotid], j, j); 144 | j += 1; 145 | } 146 | 147 | new_state.unpack.count -= (j + 1); 148 | } 149 | split_node->state_.unpack.count = j; 150 | split_node->state_.unpack.sibling_version = 0; 151 | // the sibling node of current node pointed by split_node 152 | split_node->siblings_[0] = siblings_[state_.unpack.sibling_version]; 153 | clwb(split_node, 64); // persist header 154 | clwb(&split_node->recs_[1], sizeof(Record) * (j - 1)); // persist all the inserted records 155 | 156 | // the split node is installed as the shadow sibling of current node 157 | siblings_[(state_.unpack.sibling_version + 1) % 2] = {split_k, (char *)galc->relative(split_node)}; 158 | // persist_assign the state field 159 | new_state.unpack.sibling_version = (state_.unpack.sibling_version + 1) % 2; 160 | 161 | mfence(); // a barrier here to make sure all the update is persisted to storage 162 | 163 | persist_assign(&(state_.pack), new_state.pack); 164 | 165 | // go on the insertion 166 | if(k < split_k) { 167 | insertone(k, (char *)v); 168 | } else { 169 | split_node->insertone(k, (char *)v); 170 | } 171 | return true; 172 | } else { 173 | insertone(k, (char *)v); 174 | return false; 175 | } 176 | } 177 | 178 | char * get_child(_key_t k) { 179 | Record &sibling = siblings_[state_.unpack.sibling_version]; 180 | 181 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 182 | Node * sib_node = (Node *)galc->absolute(sibling.val); 183 | return sib_node->get_child(k); 184 | } 185 | 186 | if(leftmost_ptr_ == NULL) { 187 | int8_t slotid = 0; 188 | for(int i = 0; i < state_.unpack.count; i++) { 189 | slotid = state_.read(i); 190 | if(recs_[slotid].key >= k) { 191 | break; 192 | } 193 | } 194 | 195 | if (recs_[slotid].key == k && state_.unpack.count > 0) 196 | return recs_[slotid].val; 197 | else 198 | return NULL; 199 | } else { 200 | int8_t slotid = 0, pos = state_.unpack.count; 201 | for(int i = 0; i < state_.unpack.count; i++) { 202 | slotid = state_.read(i); 203 | if(recs_[slotid].key > k) { 204 | pos = i; 205 | break; 206 | } 207 | } 208 | 209 | if (pos == 0) // all the key is bigger than k 210 | return leftmost_ptr_; 211 | else 212 | return recs_[state_.read(pos - 1)].val; 213 | } 214 | } 215 | 216 | bool update(_key_t k, uint64_t v) { 217 | uint64_t slotid = 0; 218 | for(int i = 0; i < state_.unpack.count; i++) { 219 | slotid = state_.read(i); 220 | if(recs_[slotid].key >= k) { 221 | break; 222 | } 223 | } 224 | 225 | if (recs_[slotid].key == k) { 226 | recs_[slotid].val = (char *)v; 227 | clwb(&recs_[slotid], sizeof(Record)); 228 | return true; 229 | } else { 230 | return false; 231 | } 232 | } 233 | 234 | bool remove(_key_t k) { 235 | // Non-SMO delete takes only one clwb 236 | Record &sibling = siblings_[state_.unpack.sibling_version]; 237 | if(k >= sibling.key) { // if the node has splitted and k to find is in next node 238 | Node * sib_node = (Node *)galc->absolute(sibling.val); 239 | return sib_node->remove(k); 240 | } 241 | 242 | if(leftmost_ptr_ == NULL) { 243 | int8_t idx, slotid; 244 | for(idx = 0; idx < state_.unpack.count; idx++) { 245 | slotid = state_.read(idx); 246 | if(recs_[slotid].key >= k) 247 | break; 248 | } 249 | 250 | if(recs_[slotid].key == k) { 251 | uint64_t newpack = state_.remove(idx); 252 | persist_assign(&(state_.pack), newpack); 253 | return true; 254 | } else { 255 | return false; 256 | } 257 | } else { 258 | int8_t idx; 259 | for(idx = 0; idx < state_.unpack.count; idx++) { 260 | int8_t slotid = state_.read(idx); 261 | if(recs_[slotid].key > k) 262 | break; 263 | } 264 | /* NOTICE: 265 | * We will never remove the leftmost child in our wbtree design 266 | * So the idx here must be larger than 0 267 | */ 268 | uint64_t newpack = state_.remove(idx - 1); 269 | persist_assign(&(state_.pack), newpack); 270 | 271 | return true; 272 | } 273 | } 274 | 275 | void print(string prefix, bool recursively) const { 276 | printf("%s[%lx(%ld) ", prefix.c_str(), state_.unpack.slotArray, state_.unpack.count); 277 | 278 | for(int i = 0; i < state_.unpack.count; i++) { 279 | printf("%d ", state_.read(i)); 280 | } 281 | 282 | for(int i = 0; i < state_.unpack.count; i++) { 283 | int8_t slotid = state_.read(i); 284 | printf("(%ld 0x%lx) ", recs_[slotid].key, (uint64_t)recs_[slotid].val); 285 | } 286 | printf("]\n"); 287 | 288 | if(recursively && leftmost_ptr_ != NULL) { 289 | Node * child = (Node *)galc->absolute(leftmost_ptr_); 290 | child->print(prefix + " ", recursively); 291 | 292 | for(int i = 0; i < state_.unpack.count; i++) { 293 | Node * child = (Node *)galc->absolute(recs_[state_.read(i)].val); 294 | child->print(prefix + " ", recursively); 295 | } 296 | } 297 | } 298 | 299 | void get_sibling(_key_t & k, Node ** &sibling) { 300 | Record &sib = siblings_[state_.unpack.sibling_version]; 301 | k = sib.key; 302 | sibling = (Node **)&(sib.val); 303 | } 304 | 305 | public: 306 | void insertone(_key_t key, char * right) { 307 | int8_t idx; 308 | for(idx = 0; idx < state_.unpack.count; idx++) { 309 | int8_t slotid = state_.read(idx); 310 | if(key < recs_[slotid].key) { 311 | break; 312 | } 313 | } 314 | 315 | // insert and flush the kv 316 | int8_t slotid = state_.alloc(); // alloc a slot in the node 317 | recs_[slotid] = {key, (char *) right}; 318 | clwb(&recs_[slotid], sizeof(Record)); 319 | mfence(); 320 | 321 | //write_version++; 322 | 323 | // atomically update the state 324 | uint64_t new_pack = state_.add(idx, slotid); 325 | persist_assign(&(state_.pack), new_pack); 326 | } 327 | 328 | void append(Record r, int8_t slotid, int8_t pos) { 329 | recs_[slotid] = r; 330 | state_.pack = state_.append(pos, slotid); 331 | } 332 | 333 | static void merge(Node * left, Node * right) { 334 | Record & sibling = left->siblings_[left->state_.unpack.sibling_version]; 335 | 336 | state_t new_state = left->state_; 337 | if(left->leftmost_ptr_ != NULL) { // insert the leftmost_ptr of the right node 338 | int8_t slotid = new_state.alloc(); 339 | left->append({sibling.key, right->leftmost_ptr_}, slotid, new_state.unpack.count); 340 | new_state.pack = new_state.add(new_state.unpack.count, slotid); 341 | } 342 | for(int i = 0; i < right->state_.unpack.count; i++) { 343 | int8_t slotid = new_state.alloc(); 344 | left->append(right->recs_[right->state_.read(i)], slotid, new_state.unpack.count); 345 | new_state.pack = new_state.add(new_state.unpack.count, slotid);; 346 | } 347 | 348 | Record tmp = right->siblings_[right->state_.unpack.sibling_version]; 349 | left->siblings_[(left->state_.unpack.sibling_version + 1) % 2] = tmp; 350 | new_state.unpack.sibling_version = (left->state_.unpack.sibling_version + 1) % 2; 351 | 352 | clwb(left, sizeof(Node)); // persist the whole leaf node 353 | 354 | // persist_assign the state_ field 355 | mfence(); 356 | left->state_.pack = new_state.pack; 357 | clwb(left, 64); 358 | 359 | galc->free(right); // WARNING: persistent memory leak here 360 | } 361 | 362 | void get_lrchild(_key_t k, Node * & left, Node * & right) { 363 | int16_t i = 0; 364 | for( ; i < state_.unpack.count; i++) { 365 | int8_t slotid = state_.read(i); 366 | if(recs_[slotid].key > k) 367 | break; 368 | } 369 | 370 | if(i == 0) { 371 | left = NULL; 372 | } else if(i == 1) { 373 | left = (Node *)galc->absolute(leftmost_ptr_); 374 | } else { 375 | left = (Node *)galc->absolute(recs_[state_.read(i - 2)].val); 376 | } 377 | 378 | if(i == state_.unpack.count) { 379 | right = NULL; 380 | } else { 381 | right = (Node *)galc->absolute(recs_[state_.read(i)].val); 382 | } 383 | } 384 | }; 385 | 386 | extern bool insert_recursive(Node * n, _key_t k, uint64_t v, _key_t &split_k, 387 | Node * &split_node, int8_t &level); 388 | extern bool remove_recursive(Node * n, _key_t k); 389 | extern bool find(Node ** rootPtr, _key_t key, uint64_t &val); 390 | extern res_t insert(Node ** rootPtr, _key_t key, uint64_t val, int threshold); 391 | extern bool update(Node ** rootPtr, _key_t key, uint64_t val); 392 | extern bool remove(Node ** rootPtr, _key_t key); 393 | extern void printAll(Node ** rootPtr); 394 | 395 | } 396 | #endif // __WOTREE256__ -------------------------------------------------------------------------------- /Single/test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(datagen "datagen.cc") 2 | 3 | add_executable(main "main.cc") 4 | target_link_libraries(main tlbtree) 5 | 6 | add_executable(preload "preload.cc") 7 | target_link_libraries(preload tlbtree) -------------------------------------------------------------------------------- /Single/test/datagen.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "common.h" 14 | #include "zipfian.h" 15 | 16 | using std::cout; 17 | using std::endl; 18 | using std::string; 19 | using std::ofstream; 20 | using std::ifstream; 21 | 22 | enum DistributionType {RAND = 0, ZIPFIAN}; 23 | 24 | struct WorkloadType { 25 | int operations = KILO; 26 | float read = 1.0; 27 | float insert = 0; 28 | float update = 0; 29 | float remove = 0; 30 | DistributionType dist = RAND; 31 | float skewness = 0.8; 32 | bool valid() { 33 | return read + insert + update + remove == 1.0 && skewness > 0 && skewness < 1.0; 34 | } 35 | void print() { 36 | cout << "=========WORKLOAD TYPE=========" << endl; 37 | cout << "Operations : " << operations << endl; 38 | cout << "Read Ratio : " << read << endl; 39 | cout << "Insert Ratio: " << insert << endl; 40 | cout << "Update Ratio: " << update << endl; 41 | cout << "Remove Ratio: " << remove << endl; 42 | cout << "Distribution: " << (dist == RAND ? "random" : "Zipfian") << endl; 43 | if (dist == ZIPFIAN) { 44 | cout << "Skewness " << skewness << endl; 45 | } 46 | cout << "===============================" << endl; 47 | } 48 | }; 49 | 50 | struct QueryType { 51 | OperationType op; 52 | int64_t key; 53 | }; 54 | 55 | class OperationGenerator { 56 | public : 57 | OperationType mappings_[100]; 58 | std::default_random_engine gen_; 59 | std::uniform_int_distribution dist_; 60 | 61 | OperationGenerator(WorkloadType &w) : gen_(getRandom()) { 62 | int read_end = 100 * w.read; 63 | int insert_end = read_end + 100 * w.insert; 64 | int update_end = insert_end + 100 * w.update; 65 | int remove_end = update_end + 100 * w.remove; 66 | 67 | for(int i = 0; i < read_end; i++) 68 | mappings_[i] = OperationType::READ; 69 | 70 | for(int i = read_end; i < insert_end; i++) 71 | mappings_[i] = OperationType::INSERT; 72 | 73 | for(int i = insert_end; i < update_end; i++) 74 | mappings_[i] = OperationType::UPDATE; 75 | 76 | for(int i = update_end; i < remove_end; i++) 77 | mappings_[i] = OperationType::DELETE; 78 | } 79 | 80 | OperationType next() { 81 | return mappings_[dist_(gen_) % 100]; 82 | } 83 | }; 84 | 85 | // try not to generate duplicate keys, because some tree indices may not get used to it 86 | 87 | void gen_dataset(int64_t *arr, int64_t scale, bool random) { 88 | std::mt19937 gen(10007); 89 | if(random) { 90 | uint64_t step = MAX_KEY / scale; 91 | std::uniform_int_distribution dist(0, MAX_KEY); 92 | for(int64_t i = 0; i < scale; i++) { 93 | #ifdef DEBUG 94 | arr[i] = i + 1; 95 | #else 96 | arr[i] = i * step + 1; // non duplicated keys, and no zero key 97 | #endif 98 | } 99 | std::shuffle(arr, arr + scale - 1, gen); 100 | } else { 101 | std::normal_distribution dist(MAX_KEY / 2, MAX_KEY / 8); 102 | int64_t i = 0; 103 | while (i < scale) { 104 | double val = (int64_t)dist(gen); 105 | if(val < 0 || val > (double) MAX_KEY) { 106 | continue; 107 | } else { 108 | arr[i++] = (int64_t)std::round(val); 109 | } 110 | } 111 | } 112 | return ; 113 | } 114 | 115 | void gen_workload(int64_t *arr, int64_t scale, QueryType * querys, WorkloadType w) { 116 | std::mt19937 gen(getRandom()); 117 | std::uniform_int_distribution idx1_dist(0, scale - 1); 118 | zipfian_int_distribution idx2_dist(0, scale - 1, w.skewness); 119 | OperationGenerator op_gen(w); 120 | 121 | for(int i = 0; i < w.operations; i++) { 122 | OperationType op = op_gen.next(); 123 | int idx = (w.dist == RAND ? idx1_dist(gen) : idx2_dist(gen)); 124 | // for insert operations, we should make sure the key does not exist in the dataset 125 | int64_t key = (op == OperationType::INSERT ? arr[idx] + getRandom(): arr[idx]); 126 | 127 | querys[i] = {op, key}; 128 | } 129 | } 130 | 131 | int main(int argc, char ** argv) { 132 | static const bool DATASET_RANDOM = true; 133 | bool opt_zipfian = false; 134 | WorkloadType w; 135 | 136 | static const char * optstr = "r:i:u:d:o:s:hz"; 137 | opterr = 0; 138 | char opt; 139 | while((opt = getopt(argc, argv, optstr)) != -1) { 140 | switch(opt) { 141 | case 'o': 142 | w.operations = atoi(optarg); 143 | break; 144 | case 's': 145 | w.skewness = atof(optarg); 146 | break; 147 | case 'r': 148 | w.read = atof(optarg); 149 | break; 150 | case 'i': 151 | w.insert = atof(optarg); 152 | break; 153 | case 'd': 154 | w.remove = atof(optarg); 155 | break; 156 | case 'u': 157 | w.update = atof(optarg); 158 | break; 159 | case 'z': 160 | opt_zipfian = true; 161 | break; 162 | case '?': 163 | case 'h': 164 | default: 165 | cout << "USAGE: "<< argv[0] << "[option]" << endl; 166 | cout << "\t -h: " << "Print the USAGE" << endl; 167 | cout << "\t -z: " << "Use zipfian distribution (Not specified: random distribution)" << endl; 168 | cout << "\t -o: " << "The number of operations" << endl; 169 | cout << "\t -s: " << "The skewness of query workload(0 - 1)" << endl; 170 | cout << "\t -r: " << "Read ratio" << endl; 171 | cout << "\t -i: " << "Insert ratio" << endl; 172 | cout << "\t -u: " << "update ratio" << endl; 173 | cout << "\t -d: " << "Delete ratio" << endl; 174 | exit(-1); 175 | } 176 | } 177 | 178 | if(!w.valid()) { 179 | cout << "Invalid workload configuration" << endl; 180 | exit(-1); 181 | } 182 | if(opt_zipfian == true) { 183 | w.dist = ZIPFIAN; 184 | } 185 | 186 | w.print(); 187 | 188 | #ifdef DEBUG 189 | uint64_t scale = LOADSCALE * KILO; 190 | #else 191 | uint64_t scale = LOADSCALE * MILLION; 192 | #endif 193 | 194 | int64_t * arr = new int64_t[scale]; 195 | if(!file_exist("dataset.dat")) { 196 | gen_dataset(arr, scale, DATASET_RANDOM); 197 | ofstream fout("dataset.dat", std::ios::binary); 198 | fout.write((char *) arr, sizeof(int64_t) * scale); 199 | fout.close(); 200 | cout << "generate a dataset file" << endl; 201 | } else { 202 | ifstream fin("dataset.dat", std::ios::binary); 203 | fin.read((char *)arr, sizeof(int64_t) * scale); 204 | fin.close(); 205 | } 206 | 207 | QueryType * querys = new QueryType[w.operations]; 208 | gen_workload(arr, scale, querys, w); 209 | 210 | ofstream fout("workload.txt"); 211 | for(int i = 0; i < w.operations; i++) { 212 | fout << querys[i].op << " " << querys[i].key << endl; 213 | } 214 | fout.close(); 215 | cout << "generate a query workload file" << endl; 216 | 217 | delete [] arr; 218 | delete [] querys; 219 | return 0; 220 | } -------------------------------------------------------------------------------- /Single/test/gen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | scale=$1 4 | if [ $# -lt 1 ]; then 5 | scale=10000 6 | fi 7 | 8 | # Random RO 9 | ./datagen -o $scale -r 1 -i 0 10 | mv workload.txt workload1.txt 11 | 12 | # Random RW 13 | ./datagen -o $scale -r 0.5 -i 0.5 14 | mv workload.txt workload2.txt 15 | 16 | # Random WO 17 | ./datagen -o $scale -r 0 -i 1 18 | mv workload.txt workload3.txt 19 | 20 | # Zipfian RO 21 | ./datagen -o $scale -r 1 -i 0 -z -s 0.7 22 | mv workload.txt workload4.txt 23 | 24 | # Zipfian RW 25 | ./datagen -o $scale -r 0.5 -i 0.5 -z -s 0.7 26 | mv workload.txt workload5.txt 27 | 28 | # Zipfian WO 29 | ./datagen -o $scale -r 0 -i 1 -z -s 0.7 30 | mv workload.txt workload6.txt -------------------------------------------------------------------------------- /Single/test/main.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "tlbtree.h" 14 | 15 | using std::cout; 16 | using std::endl; 17 | using std::ifstream; 18 | using std::string; 19 | 20 | template 21 | double run_test(ifstream & fin) { 22 | int small_noise = getRandom() & 0x3ff; // each time we run, we will insert different keys 23 | 24 | auto start = seconds(); 25 | 26 | BTreeType tree("/mnt/pmem/tlbtree.pool"); 27 | int op_id, notfound = 0; 28 | _key_t key; 29 | uint64_t val; 30 | for(int i = 0; fin >> op_id >> key; i++) { 31 | switch (op_id) { 32 | case OperationType::INSERT: 33 | tree.insert(key + small_noise, uint64_t(key + small_noise)); 34 | break; 35 | case OperationType::READ: 36 | val = tree.lookup(key); 37 | if(val == 0) 38 | notfound++; // optimizer killer 39 | break; 40 | case OperationType::UPDATE: 41 | tree.update(key, uint64_t(key * 2)); 42 | break; 43 | case OperationType::DELETE: 44 | tree.remove(key); 45 | break; 46 | default: 47 | cout << "wrong operation id" << endl; 48 | break; 49 | } 50 | } 51 | if(notfound > 0) cout << "somthing not found" << endl; // optimizer killer 52 | 53 | auto end = seconds(); 54 | return double(end - start); 55 | } 56 | 57 | int main(int argc, char ** argv) { 58 | int opt_testid = 1; 59 | string opt_fname = "workload.txt"; 60 | 61 | if(argc > 1) { 62 | if(file_exist(argv[1])) 63 | opt_fname = argv[1]; 64 | else 65 | cout << "workload file "<< argv[1] << " not exist" << endl; 66 | } 67 | 68 | ifstream fin(opt_fname.c_str()); 69 | double time = 0; 70 | time = run_test(fin); 71 | 72 | cout << time << endl; 73 | fin.close(); 74 | return 0; 75 | } -------------------------------------------------------------------------------- /Single/test/preload.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "tlbtree.h" 12 | 13 | using std::cout; 14 | using std::endl; 15 | using std::ifstream; 16 | 17 | typedef double mytime_t; 18 | 19 | _key_t *keys; 20 | PMAllocator * galc; 21 | 22 | template 23 | void preload(BTreeType &tree, uint64_t load_size, ifstream & fin) { 24 | #ifdef DEBUG 25 | fin.read((char *)keys, sizeof(_key_t) * MILLION); 26 | for(int i = 0; i < LOADSCALE * KILO; i++) { 27 | _key_t key = keys[i]; 28 | cout << key << endl; 29 | tree.insert((_key_t)key, key); 30 | } 31 | //tree.printAll(); 32 | #else 33 | for(uint64_t t = 0; t < load_size; t++) { 34 | fin.read((char *)keys, sizeof(_key_t) * MILLION); 35 | 36 | for(int i = 0; i < MILLION; i++) { 37 | _key_t key = keys[i]; 38 | tree.insert((_key_t)key, uint64_t(key)); 39 | } 40 | } 41 | #endif 42 | 43 | return ; 44 | } 45 | 46 | int main(int argc, char ** argv) { 47 | // open the data file 48 | std::string filename = "dataset.dat"; 49 | std::ifstream fin(filename.c_str(), std::ios::binary); 50 | if(!fin) { 51 | cout << "File not exists or Open error\n"; 52 | exit(-1); 53 | } 54 | 55 | // read all the key into vector keys 56 | keys = new _key_t[sizeof(_key_t) * MILLION]; 57 | 58 | cout << "tlbtree" << endl; 59 | TLBtree tree("/mnt/pmem/tlbtree.pool"); 60 | preload(tree, LOADSCALE, fin); 61 | 62 | delete keys; 63 | fin.close(); 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Single/test/test.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright(c) 2020 Luo Yongping. THIS SOFTWARE COMES WITH NO WARRANTIES, 3 | USE AT YOUR OWN RISK! 4 | */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "tlbtree.h" 15 | 16 | using std::cout; 17 | using std::endl; 18 | using std::ifstream; 19 | using std::string; 20 | 21 | _key_t * keys; 22 | uint32_t seed; 23 | 24 | template 25 | double put_throughput(BTreeType &tree, uint32_t req_cnt) { 26 | auto start = seconds(); 27 | for(int i = 0; i < req_cnt; i++) { 28 | _key_t key = keys[i]; 29 | int64_t val = key; 30 | //cout << "insert " << key + seed << endl; 31 | tree.insert(key + seed, val); 32 | } 33 | auto end = seconds(); 34 | return double(end - start); 35 | } 36 | 37 | template 38 | double get_throughput(BTreeType &tree, uint32_t req_cnt) { 39 | auto start = seconds(); 40 | int64_t val; 41 | for(int i = 0; i < req_cnt; i++) { 42 | _key_t key = keys[i]; 43 | bool foundif = tree.find(key, val); 44 | //cout << key << " " << val << endl; 45 | if(foundif == false) { 46 | cout << "Not Found " << key << endl; 47 | } 48 | } 49 | auto end = seconds(); 50 | return double(end - start); 51 | } 52 | 53 | template 54 | double del_throughput(BTreeType &tree, uint32_t req_cnt) { 55 | auto start = seconds(); 56 | int64_t val; 57 | for(int i = 0; i < req_cnt; i++) { 58 | cout << "delete " << keys[i] << endl; 59 | tree.remove(keys[i]); 60 | } 61 | auto end = seconds(); 62 | return double(end - start); 63 | } 64 | 65 | template 66 | double update_throughput(BTreeType &tree, uint32_t req_cnt) { 67 | auto start = seconds(); 68 | for(int i = 0; i < req_cnt; i++) { 69 | _key_t key = keys[i]; 70 | //cout << "update " << key << endl; 71 | bool foundif = tree.update(key, (key * 2)); 72 | } 73 | auto end = seconds(); 74 | return double(end - start); 75 | } 76 | 77 | template 78 | void run_test(int opt_loadid, int opt_scale){ 79 | switch(opt_loadid) { 80 | case 1: { // test insert 81 | BtreeType tree(true); 82 | double dur1 = put_throughput(tree, opt_scale); 83 | cout << dur1 << endl; 84 | break; 85 | } 86 | case 2: { // test read 87 | BtreeType tree(true); 88 | double dur1 = get_throughput(tree, opt_scale); 89 | cout << dur1 << endl; 90 | break; 91 | } 92 | case 3: { // test update 93 | BtreeType tree(true); 94 | double dur1 = update_throughput(tree, opt_scale); 95 | cout << dur1 << endl; 96 | break; 97 | } 98 | case 4: { // test delete 99 | BtreeType tree(true); 100 | double dur1 = del_throughput(tree, opt_scale); 101 | cout << dur1 << endl; 102 | break; 103 | } 104 | default : { // basic test 105 | seed = 0; // the tree is empty 106 | BtreeType tree(false); 107 | put_throughput(tree, opt_scale); 108 | get_throughput(tree, opt_scale); 109 | //del_throughput(tree, opt_scale); 110 | //get_throughput(tree, opt_scale); 111 | break; 112 | } 113 | } 114 | } 115 | 116 | void print_help(const char * name) { 117 | cout << "USAGE: "<< name << "[option]" << endl; 118 | cout << "\t -h: " << "Print the USAGE" << endl; 119 | cout << "\t -s: " << "scale of the test" << endl; 120 | cout << "\t -l: " << "The workload of the test (1:input 2:get: 3:update 4:delete other: multiple test)" << endl; 121 | } 122 | 123 | int main(int argc, char ** argv) { 124 | int opt_loadid = 2; 125 | int opt_scale = KILO; 126 | 127 | static const char * optstr = "s:t:l:dh"; 128 | opterr = 0; 129 | char opt; 130 | 131 | while((opt = getopt(argc, argv, optstr)) != -1) { 132 | switch(opt) { 133 | case 's': 134 | if(atoi(optarg) > 0) 135 | opt_scale = KILO * atoi(optarg); 136 | break; 137 | case 'l': 138 | if(atoi(optarg) > 0) 139 | opt_loadid = atoi(optarg); 140 | break; 141 | case '?': 142 | case 'h': 143 | default: 144 | print_help(argv[0]); 145 | exit(-1); 146 | break; 147 | } 148 | } 149 | 150 | if(argc == 1) { 151 | print_help(argv[0]); 152 | exit(-1); 153 | } 154 | 155 | // open the data file 156 | std::string data_name = "dataset.dat"; 157 | std::ifstream fin(data_name.c_str(), std::ios::binary); 158 | if(!fin) { 159 | cout << "File not exists or Open error\n"; 160 | exit(-1); 161 | } 162 | // initialization of the test 163 | keys = new _key_t[opt_scale]; 164 | seed = getRandom(); 165 | std::default_random_engine rd(seed); 166 | std::uniform_int_distribution dist(0, LOADSCALE * MILLION - opt_scale); 167 | #ifdef DEBUG 168 | // seek to the start of the file 169 | fin.seekg(0, std::ios_base::beg); 170 | #else 171 | // seek to a random position in the file 172 | fin.seekg(dist(rd) * sizeof(_key_t), std::ios_base::beg); 173 | #endif 174 | // read data from data file 175 | fin.read((char *)keys, sizeof(_key_t) * opt_scale); 176 | 177 | cout << "tlbtree" << endl; 178 | run_test("/mnt/pmem/tlbtree.pool", opt_loadid, opt_scale); 179 | 180 | fin.close(); 181 | delete keys; 182 | return 0; 183 | } -------------------------------------------------------------------------------- /Single/test/zipfian.h: -------------------------------------------------------------------------------- 1 | /* Implementation derived from: 2 | * "Quickly Generating Billion-Record Synthetic Databases", Jim Gray et al, 3 | * SIGMOD 1994 4 | * 5 | * The zipfian_int_distribution class is intended to be compatible with other 6 | * distributions introduced in #include by the C++11 standard. 7 | * 8 | * Usage example: 9 | * #include 10 | * #include "zipfian_int_distribution.h" 11 | * int main() 12 | * { 13 | * std::default_random_engine generator; 14 | * zipfian_int_distribution distribution(1, 10, 0.99); 15 | * int i = distribution(generator); 16 | * } 17 | */ 18 | 19 | /* 20 | * IMPORTANT: constructing the distribution object requires calculating the zeta 21 | * value which becomes prohibetively expensive for very large ranges. As an 22 | * alternative for such cases, the user can pass the pre-calculated values and 23 | * avoid the calculation every time. 24 | * 25 | * Usage example: 26 | * #include 27 | * #include "zipfian_int_distribution.h" 28 | * int main() 29 | * { 30 | * std::default_random_engine generator; 31 | * zipfian_int_distribution::param_type p(1, 1e6, 0.99, 27.000); 32 | * zipfian_int_distribution distribution(p); 33 | * int i = distribution(generator); 34 | * } 35 | */ 36 | 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | template 43 | class zipfian_int_distribution 44 | { 45 | static_assert(std::is_integral<_IntType>::value, "Template argument not an integral type."); 46 | 47 | public: 48 | /** The type of the range of the distribution. */ 49 | typedef _IntType result_type; 50 | /** Parameter type. */ 51 | struct param_type 52 | { 53 | typedef zipfian_int_distribution<_IntType> distribution_type; 54 | 55 | explicit param_type(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max(), double __theta = 0.99) 56 | : _M_a(__a), _M_b(__b), _M_theta(__theta), 57 | _M_zeta(zeta(_M_b - _M_a + 1, __theta)), _M_zeta2theta(zeta(2, __theta)) 58 | { 59 | assert(_M_a <= _M_b && _M_theta > 0.0 && _M_theta < 1.0); 60 | } 61 | 62 | explicit param_type(_IntType __a, _IntType __b, double __theta, double __zeta) 63 | : _M_a(__a), _M_b(__b), _M_theta(__theta), _M_zeta(__zeta), 64 | _M_zeta2theta(zeta(2, __theta)) 65 | { 66 | __glibcxx_assert(_M_a <= _M_b && _M_theta > 0.0 && _M_theta < 1.0); 67 | } 68 | 69 | result_type a() const { return _M_a; } 70 | 71 | result_type b() const { return _M_b; } 72 | 73 | double theta() const { return _M_theta; } 74 | 75 | double zeta() const { return _M_zeta; } 76 | 77 | double zeta2theta() const { return _M_zeta2theta; } 78 | 79 | friend bool operator==(const param_type& __p1, const param_type& __p2) 80 | { 81 | return __p1._M_a == __p2._M_a 82 | && __p1._M_b == __p2._M_b 83 | && __p1._M_theta == __p2._M_theta 84 | && __p1._M_zeta == __p2._M_zeta 85 | && __p1._M_zeta2theta == __p2._M_zeta2theta; 86 | } 87 | 88 | private: 89 | _IntType _M_a; 90 | _IntType _M_b; 91 | double _M_theta; 92 | double _M_zeta; 93 | double _M_zeta2theta; 94 | 95 | /** 96 | * @brief Calculates zeta. 97 | * 98 | * @param __n [IN] The size of the domain. 99 | * @param __theta [IN] The skew factor of the distribution. 100 | */ 101 | double zeta(unsigned long __n, double __theta) 102 | { 103 | double ans = 0.0; 104 | for (unsigned long i=1; i<=__n; ++i) 105 | ans += std::pow(1.0 / i, __theta); 106 | return ans; 107 | } 108 | }; 109 | 110 | public: 111 | /** 112 | * @brief Constructs a zipfian_int_distribution object. 113 | * 114 | * @param __a [IN] The lower bound of the distribution. 115 | * @param __b [IN] The upper bound of the distribution. 116 | * @param __theta [IN] The skew factor of the distribution. 117 | */ 118 | explicit zipfian_int_distribution(_IntType __a = _IntType(0), _IntType __b = _IntType(1), double __theta = 0.99) 119 | : _M_param(__a, __b, __theta) 120 | { 121 | } 122 | 123 | explicit zipfian_int_distribution(const param_type& __p) : _M_param(__p) 124 | { 125 | } 126 | 127 | /** 128 | * @brief Resets the distribution state. 129 | * 130 | * Does nothing for the zipfian int distribution. 131 | */ 132 | void reset() {} 133 | 134 | result_type a() const { return _M_param.a(); } 135 | 136 | result_type b() const { return _M_param.b(); } 137 | 138 | double theta() const { return _M_param.theta(); } 139 | 140 | /** 141 | * @brief Returns the parameter set of the distribution. 142 | */ 143 | param_type param() const { return _M_param; } 144 | 145 | /** 146 | * @brief Sets the parameter set of the distribution. 147 | * @param __param The new parameter set of the distribution. 148 | */ 149 | void param(const param_type& __param) { _M_param = __param; } 150 | 151 | /** 152 | * @brief Returns the inclusive lower bound of the distribution range. 153 | */ 154 | result_type min() const { return this->a(); } 155 | 156 | /** 157 | * @brief Returns the inclusive upper bound of the distribution range. 158 | */ 159 | result_type max() const { return this->b(); } 160 | 161 | /** 162 | * @brief Generating functions. 163 | */ 164 | template 165 | result_type operator()(_UniformRandomNumberGenerator& __urng) 166 | { 167 | return this->operator()(__urng, _M_param); 168 | } 169 | 170 | template 171 | result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) 172 | { 173 | double alpha = 1 / (1 - __p.theta()); 174 | double eta = (1 - std::pow(2.0 / (__p.b() - __p.a() + 1), 1 - __p.theta())) / (1 - __p.zeta2theta() / __p.zeta()); 175 | 176 | double u = std::generate_canonical::digits, _UniformRandomNumberGenerator>(__urng); 177 | 178 | double uz = u * __p.zeta(); 179 | if (uz < 1.0) 180 | return __p.a(); 181 | if (uz < 1.0 + std::pow(0.5, __p.theta())) 182 | return __p.a() + 1; 183 | 184 | return __p.a() + ((__p.b() - __p.a() + 1) * std::pow(eta * u - eta + 1, alpha)); 185 | } 186 | 187 | /** 188 | * @brief Return true if two zipfian int distributions have 189 | * the same parameters. 190 | */ 191 | friend bool operator==(const zipfian_int_distribution& __d1, const zipfian_int_distribution& __d2) 192 | { 193 | return __d1._M_param == __d2._M_param; 194 | } 195 | 196 | private: 197 | param_type _M_param; 198 | }; --------------------------------------------------------------------------------