skl.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. * Copyright 2017 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. Adapted from RocksDB inline skiplist.
  18. Key differences:
  19. - No optimization for sequential inserts (no "prev").
  20. - No custom comparator.
  21. - Support overwrites. This requires care when we see the same key when inserting.
  22. For RocksDB or LevelDB, overwrites are implemented as a newer sequence number in the key, so
  23. there is no need for values. We don't intend to support versioning. In-place updates of values
  24. would be more efficient.
  25. - We discard all non-concurrent code.
  26. - We do not support Splices. This simplifies the code a lot.
  27. - No AllocateNode or other pointer arithmetic.
  28. - We combine the findLessThan, findGreaterOrEqual, etc into one function.
  29. */
  30. package skl
  31. import (
  32. "math"
  33. "math/rand"
  34. "sync/atomic"
  35. "unsafe"
  36. "github.com/dgraph-io/badger/y"
  37. )
  38. const (
  39. maxHeight = 20
  40. heightIncrease = math.MaxUint32 / 3
  41. )
  42. // MaxNodeSize is the memory footprint of a node of maximum height.
  43. const MaxNodeSize = int(unsafe.Sizeof(node{}))
  44. type node struct {
  45. // Multiple parts of the value are encoded as a single uint64 so that it
  46. // can be atomically loaded and stored:
  47. // value offset: uint32 (bits 0-31)
  48. // value size : uint16 (bits 32-47)
  49. value uint64
  50. // A byte slice is 24 bytes. We are trying to save space here.
  51. keyOffset uint32 // Immutable. No need to lock to access key.
  52. keySize uint16 // Immutable. No need to lock to access key.
  53. // Height of the tower.
  54. height uint16
  55. // Most nodes do not need to use the full height of the tower, since the
  56. // probability of each successive level decreases exponentially. Because
  57. // these elements are never accessed, they do not need to be allocated.
  58. // Therefore, when a node is allocated in the arena, its memory footprint
  59. // is deliberately truncated to not include unneeded tower elements.
  60. //
  61. // All accesses to elements should use CAS operations, with no need to lock.
  62. tower [maxHeight]uint32
  63. }
  64. // Skiplist maps keys to values (in memory)
  65. type Skiplist struct {
  66. height int32 // Current height. 1 <= height <= kMaxHeight. CAS.
  67. head *node
  68. ref int32
  69. arena *Arena
  70. }
  71. // IncrRef increases the refcount
  72. func (s *Skiplist) IncrRef() {
  73. atomic.AddInt32(&s.ref, 1)
  74. }
  75. // DecrRef decrements the refcount, deallocating the Skiplist when done using it
  76. func (s *Skiplist) DecrRef() {
  77. newRef := atomic.AddInt32(&s.ref, -1)
  78. if newRef > 0 {
  79. return
  80. }
  81. s.arena.reset()
  82. // Indicate we are closed. Good for testing. Also, lets GC reclaim memory. Race condition
  83. // here would suggest we are accessing skiplist when we are supposed to have no reference!
  84. s.arena = nil
  85. }
  86. func (s *Skiplist) valid() bool { return s.arena != nil }
  87. func newNode(arena *Arena, key []byte, v y.ValueStruct, height int) *node {
  88. // The base level is already allocated in the node struct.
  89. offset := arena.putNode(height)
  90. node := arena.getNode(offset)
  91. node.keyOffset = arena.putKey(key)
  92. node.keySize = uint16(len(key))
  93. node.height = uint16(height)
  94. node.value = encodeValue(arena.putVal(v), v.EncodedSize())
  95. return node
  96. }
  97. func encodeValue(valOffset uint32, valSize uint16) uint64 {
  98. return uint64(valSize)<<32 | uint64(valOffset)
  99. }
  100. func decodeValue(value uint64) (valOffset uint32, valSize uint16) {
  101. valOffset = uint32(value)
  102. valSize = uint16(value >> 32)
  103. return
  104. }
  105. // NewSkiplist makes a new empty skiplist, with a given arena size
  106. func NewSkiplist(arenaSize int64) *Skiplist {
  107. arena := newArena(arenaSize)
  108. head := newNode(arena, nil, y.ValueStruct{}, maxHeight)
  109. return &Skiplist{
  110. height: 1,
  111. head: head,
  112. arena: arena,
  113. ref: 1,
  114. }
  115. }
  116. func (s *node) getValueOffset() (uint32, uint16) {
  117. value := atomic.LoadUint64(&s.value)
  118. return decodeValue(value)
  119. }
  120. func (s *node) key(arena *Arena) []byte {
  121. return arena.getKey(s.keyOffset, s.keySize)
  122. }
  123. func (s *node) setValue(arena *Arena, v y.ValueStruct) {
  124. valOffset := arena.putVal(v)
  125. value := encodeValue(valOffset, v.EncodedSize())
  126. atomic.StoreUint64(&s.value, value)
  127. }
  128. func (s *node) getNextOffset(h int) uint32 {
  129. return atomic.LoadUint32(&s.tower[h])
  130. }
  131. func (s *node) casNextOffset(h int, old, val uint32) bool {
  132. return atomic.CompareAndSwapUint32(&s.tower[h], old, val)
  133. }
  134. // Returns true if key is strictly > n.key.
  135. // If n is nil, this is an "end" marker and we return false.
  136. //func (s *Skiplist) keyIsAfterNode(key []byte, n *node) bool {
  137. // y.AssertTrue(n != s.head)
  138. // return n != nil && y.CompareKeys(key, n.key) > 0
  139. //}
  140. func randomHeight() int {
  141. h := 1
  142. for h < maxHeight && rand.Uint32() <= heightIncrease {
  143. h++
  144. }
  145. return h
  146. }
  147. func (s *Skiplist) getNext(nd *node, height int) *node {
  148. return s.arena.getNode(nd.getNextOffset(height))
  149. }
  150. // findNear finds the node near to key.
  151. // If less=true, it finds rightmost node such that node.key < key (if allowEqual=false) or
  152. // node.key <= key (if allowEqual=true).
  153. // If less=false, it finds leftmost node such that node.key > key (if allowEqual=false) or
  154. // node.key >= key (if allowEqual=true).
  155. // Returns the node found. The bool returned is true if the node has key equal to given key.
  156. func (s *Skiplist) findNear(key []byte, less bool, allowEqual bool) (*node, bool) {
  157. x := s.head
  158. level := int(s.getHeight() - 1)
  159. for {
  160. // Assume x.key < key.
  161. next := s.getNext(x, level)
  162. if next == nil {
  163. // x.key < key < END OF LIST
  164. if level > 0 {
  165. // Can descend further to iterate closer to the end.
  166. level--
  167. continue
  168. }
  169. // Level=0. Cannot descend further. Let's return something that makes sense.
  170. if !less {
  171. return nil, false
  172. }
  173. // Try to return x. Make sure it is not a head node.
  174. if x == s.head {
  175. return nil, false
  176. }
  177. return x, false
  178. }
  179. nextKey := next.key(s.arena)
  180. cmp := y.CompareKeys(key, nextKey)
  181. if cmp > 0 {
  182. // x.key < next.key < key. We can continue to move right.
  183. x = next
  184. continue
  185. }
  186. if cmp == 0 {
  187. // x.key < key == next.key.
  188. if allowEqual {
  189. return next, true
  190. }
  191. if !less {
  192. // We want >, so go to base level to grab the next bigger note.
  193. return s.getNext(next, 0), false
  194. }
  195. // We want <. If not base level, we should go closer in the next level.
  196. if level > 0 {
  197. level--
  198. continue
  199. }
  200. // On base level. Return x.
  201. if x == s.head {
  202. return nil, false
  203. }
  204. return x, false
  205. }
  206. // cmp < 0. In other words, x.key < key < next.
  207. if level > 0 {
  208. level--
  209. continue
  210. }
  211. // At base level. Need to return something.
  212. if !less {
  213. return next, false
  214. }
  215. // Try to return x. Make sure it is not a head node.
  216. if x == s.head {
  217. return nil, false
  218. }
  219. return x, false
  220. }
  221. }
  222. // findSpliceForLevel returns (outBefore, outAfter) with outBefore.key <= key <= outAfter.key.
  223. // The input "before" tells us where to start looking.
  224. // If we found a node with the same key, then we return outBefore = outAfter.
  225. // Otherwise, outBefore.key < key < outAfter.key.
  226. func (s *Skiplist) findSpliceForLevel(key []byte, before *node, level int) (*node, *node) {
  227. for {
  228. // Assume before.key < key.
  229. next := s.getNext(before, level)
  230. if next == nil {
  231. return before, next
  232. }
  233. nextKey := next.key(s.arena)
  234. cmp := y.CompareKeys(key, nextKey)
  235. if cmp == 0 {
  236. // Equality case.
  237. return next, next
  238. }
  239. if cmp < 0 {
  240. // before.key < key < next.key. We are done for this level.
  241. return before, next
  242. }
  243. before = next // Keep moving right on this level.
  244. }
  245. }
  246. func (s *Skiplist) getHeight() int32 {
  247. return atomic.LoadInt32(&s.height)
  248. }
  249. // Put inserts the key-value pair.
  250. func (s *Skiplist) Put(key []byte, v y.ValueStruct) {
  251. // Since we allow overwrite, we may not need to create a new node. We might not even need to
  252. // increase the height. Let's defer these actions.
  253. listHeight := s.getHeight()
  254. var prev [maxHeight + 1]*node
  255. var next [maxHeight + 1]*node
  256. prev[listHeight] = s.head
  257. next[listHeight] = nil
  258. for i := int(listHeight) - 1; i >= 0; i-- {
  259. // Use higher level to speed up for current level.
  260. prev[i], next[i] = s.findSpliceForLevel(key, prev[i+1], i)
  261. if prev[i] == next[i] {
  262. prev[i].setValue(s.arena, v)
  263. return
  264. }
  265. }
  266. // We do need to create a new node.
  267. height := randomHeight()
  268. x := newNode(s.arena, key, v, height)
  269. // Try to increase s.height via CAS.
  270. listHeight = s.getHeight()
  271. for height > int(listHeight) {
  272. if atomic.CompareAndSwapInt32(&s.height, listHeight, int32(height)) {
  273. // Successfully increased skiplist.height.
  274. break
  275. }
  276. listHeight = s.getHeight()
  277. }
  278. // We always insert from the base level and up. After you add a node in base level, we cannot
  279. // create a node in the level above because it would have discovered the node in the base level.
  280. for i := 0; i < height; i++ {
  281. for {
  282. if prev[i] == nil {
  283. y.AssertTrue(i > 1) // This cannot happen in base level.
  284. // We haven't computed prev, next for this level because height exceeds old listHeight.
  285. // For these levels, we expect the lists to be sparse, so we can just search from head.
  286. prev[i], next[i] = s.findSpliceForLevel(key, s.head, i)
  287. // Someone adds the exact same key before we are able to do so. This can only happen on
  288. // the base level. But we know we are not on the base level.
  289. y.AssertTrue(prev[i] != next[i])
  290. }
  291. nextOffset := s.arena.getNodeOffset(next[i])
  292. x.tower[i] = nextOffset
  293. if prev[i].casNextOffset(i, nextOffset, s.arena.getNodeOffset(x)) {
  294. // Managed to insert x between prev[i] and next[i]. Go to the next level.
  295. break
  296. }
  297. // CAS failed. We need to recompute prev and next.
  298. // It is unlikely to be helpful to try to use a different level as we redo the search,
  299. // because it is unlikely that lots of nodes are inserted between prev[i] and next[i].
  300. prev[i], next[i] = s.findSpliceForLevel(key, prev[i], i)
  301. if prev[i] == next[i] {
  302. y.AssertTruef(i == 0, "Equality can happen only on base level: %d", i)
  303. prev[i].setValue(s.arena, v)
  304. return
  305. }
  306. }
  307. }
  308. }
  309. // Empty returns if the Skiplist is empty.
  310. func (s *Skiplist) Empty() bool {
  311. return s.findLast() == nil
  312. }
  313. // findLast returns the last element. If head (empty list), we return nil. All the find functions
  314. // will NEVER return the head nodes.
  315. func (s *Skiplist) findLast() *node {
  316. n := s.head
  317. level := int(s.getHeight()) - 1
  318. for {
  319. next := s.getNext(n, level)
  320. if next != nil {
  321. n = next
  322. continue
  323. }
  324. if level == 0 {
  325. if n == s.head {
  326. return nil
  327. }
  328. return n
  329. }
  330. level--
  331. }
  332. }
  333. // Get gets the value associated with the key. It returns a valid value if it finds equal or earlier
  334. // version of the same key.
  335. func (s *Skiplist) Get(key []byte) y.ValueStruct {
  336. n, _ := s.findNear(key, false, true) // findGreaterOrEqual.
  337. if n == nil {
  338. return y.ValueStruct{}
  339. }
  340. nextKey := s.arena.getKey(n.keyOffset, n.keySize)
  341. if !y.SameKey(key, nextKey) {
  342. return y.ValueStruct{}
  343. }
  344. valOffset, valSize := n.getValueOffset()
  345. vs := s.arena.getVal(valOffset, valSize)
  346. vs.Version = y.ParseTs(nextKey)
  347. return vs
  348. }
  349. // NewIterator returns a skiplist iterator. You have to Close() the iterator.
  350. func (s *Skiplist) NewIterator() *Iterator {
  351. s.IncrRef()
  352. return &Iterator{list: s}
  353. }
  354. // MemSize returns the size of the Skiplist in terms of how much memory is used within its internal
  355. // arena.
  356. func (s *Skiplist) MemSize() int64 { return s.arena.size() }
  357. // Iterator is an iterator over skiplist object. For new objects, you just
  358. // need to initialize Iterator.list.
  359. type Iterator struct {
  360. list *Skiplist
  361. n *node
  362. }
  363. // Close frees the resources held by the iterator
  364. func (s *Iterator) Close() error {
  365. s.list.DecrRef()
  366. return nil
  367. }
  368. // Valid returns true iff the iterator is positioned at a valid node.
  369. func (s *Iterator) Valid() bool { return s.n != nil }
  370. // Key returns the key at the current position.
  371. func (s *Iterator) Key() []byte {
  372. return s.list.arena.getKey(s.n.keyOffset, s.n.keySize)
  373. }
  374. // Value returns value.
  375. func (s *Iterator) Value() y.ValueStruct {
  376. valOffset, valSize := s.n.getValueOffset()
  377. return s.list.arena.getVal(valOffset, valSize)
  378. }
  379. // Next advances to the next position.
  380. func (s *Iterator) Next() {
  381. y.AssertTrue(s.Valid())
  382. s.n = s.list.getNext(s.n, 0)
  383. }
  384. // Prev advances to the previous position.
  385. func (s *Iterator) Prev() {
  386. y.AssertTrue(s.Valid())
  387. s.n, _ = s.list.findNear(s.Key(), true, false) // find <. No equality allowed.
  388. }
  389. // Seek advances to the first entry with a key >= target.
  390. func (s *Iterator) Seek(target []byte) {
  391. s.n, _ = s.list.findNear(target, false, true) // find >=.
  392. }
  393. // SeekForPrev finds an entry with key <= target.
  394. func (s *Iterator) SeekForPrev(target []byte) {
  395. s.n, _ = s.list.findNear(target, true, true) // find <=.
  396. }
  397. // SeekToFirst seeks position at the first entry in list.
  398. // Final state of iterator is Valid() iff list is not empty.
  399. func (s *Iterator) SeekToFirst() {
  400. s.n = s.list.getNext(s.list.head, 0)
  401. }
  402. // SeekToLast seeks position at the last entry in list.
  403. // Final state of iterator is Valid() iff list is not empty.
  404. func (s *Iterator) SeekToLast() {
  405. s.n = s.list.findLast()
  406. }
  407. // UniIterator is a unidirectional memtable iterator. It is a thin wrapper around
  408. // Iterator. We like to keep Iterator as before, because it is more powerful and
  409. // we might support bidirectional iterators in the future.
  410. type UniIterator struct {
  411. iter *Iterator
  412. reversed bool
  413. }
  414. // NewUniIterator returns a UniIterator.
  415. func (s *Skiplist) NewUniIterator(reversed bool) *UniIterator {
  416. return &UniIterator{
  417. iter: s.NewIterator(),
  418. reversed: reversed,
  419. }
  420. }
  421. // Next implements y.Interface
  422. func (s *UniIterator) Next() {
  423. if !s.reversed {
  424. s.iter.Next()
  425. } else {
  426. s.iter.Prev()
  427. }
  428. }
  429. // Rewind implements y.Interface
  430. func (s *UniIterator) Rewind() {
  431. if !s.reversed {
  432. s.iter.SeekToFirst()
  433. } else {
  434. s.iter.SeekToLast()
  435. }
  436. }
  437. // Seek implements y.Interface
  438. func (s *UniIterator) Seek(key []byte) {
  439. if !s.reversed {
  440. s.iter.Seek(key)
  441. } else {
  442. s.iter.SeekForPrev(key)
  443. }
  444. }
  445. // Key implements y.Interface
  446. func (s *UniIterator) Key() []byte { return s.iter.Key() }
  447. // Value implements y.Interface
  448. func (s *UniIterator) Value() y.ValueStruct { return s.iter.Value() }
  449. // Valid implements y.Interface
  450. func (s *UniIterator) Valid() bool { return s.iter.Valid() }
  451. // Close implements y.Interface (and frees up the iter's resources)
  452. func (s *UniIterator) Close() error { return s.iter.Close() }