skl.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. "sync/atomic"
  34. "unsafe"
  35. "github.com/dgraph-io/badger/v4/y"
  36. "github.com/dgraph-io/ristretto/v2/z"
  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-63)
  49. value atomic.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]atomic.Uint32
  63. }
  64. type Skiplist struct {
  65. height atomic.Int32 // Current height. 1 <= height <= kMaxHeight. CAS.
  66. head *node
  67. ref atomic.Int32
  68. arena *Arena
  69. OnClose func()
  70. }
  71. // IncrRef increases the refcount
  72. func (s *Skiplist) IncrRef() {
  73. s.ref.Add(1)
  74. }
  75. // DecrRef decrements the refcount, deallocating the Skiplist when done using it
  76. func (s *Skiplist) DecrRef() {
  77. newRef := s.ref.Add(-1)
  78. if newRef > 0 {
  79. return
  80. }
  81. if s.OnClose != nil {
  82. s.OnClose()
  83. }
  84. // Indicate we are closed. Good for testing. Also, lets GC reclaim memory. Race condition
  85. // here would suggest we are accessing skiplist when we are supposed to have no reference!
  86. s.arena = nil
  87. // Since the head references the arena's buf, as long as the head is kept around
  88. // GC can't release the buf.
  89. s.head = nil
  90. }
  91. func newNode(arena *Arena, key []byte, v y.ValueStruct, height int) *node {
  92. // The base level is already allocated in the node struct.
  93. offset := arena.putNode(height)
  94. node := arena.getNode(offset)
  95. node.keyOffset = arena.putKey(key)
  96. node.keySize = uint16(len(key))
  97. node.height = uint16(height)
  98. node.value.Store(encodeValue(arena.putVal(v), v.EncodedSize()))
  99. return node
  100. }
  101. func encodeValue(valOffset uint32, valSize uint32) uint64 {
  102. return uint64(valSize)<<32 | uint64(valOffset)
  103. }
  104. func decodeValue(value uint64) (valOffset uint32, valSize uint32) {
  105. valOffset = uint32(value)
  106. valSize = uint32(value >> 32)
  107. return
  108. }
  109. // NewSkiplist makes a new empty skiplist, with a given arena size
  110. func NewSkiplist(arenaSize int64) *Skiplist {
  111. arena := newArena(arenaSize)
  112. head := newNode(arena, nil, y.ValueStruct{}, maxHeight)
  113. s := &Skiplist{head: head, arena: arena}
  114. s.height.Store(1)
  115. s.ref.Store(1)
  116. return s
  117. }
  118. func (s *node) getValueOffset() (uint32, uint32) {
  119. value := s.value.Load()
  120. return decodeValue(value)
  121. }
  122. func (s *node) key(arena *Arena) []byte {
  123. return arena.getKey(s.keyOffset, s.keySize)
  124. }
  125. func (s *node) setValue(arena *Arena, v y.ValueStruct) {
  126. valOffset := arena.putVal(v)
  127. value := encodeValue(valOffset, v.EncodedSize())
  128. s.value.Store(value)
  129. }
  130. func (s *node) getNextOffset(h int) uint32 {
  131. return s.tower[h].Load()
  132. }
  133. func (s *node) casNextOffset(h int, old, val uint32) bool {
  134. return s.tower[h].CompareAndSwap(old, val)
  135. }
  136. // Returns true if key is strictly > n.key.
  137. // If n is nil, this is an "end" marker and we return false.
  138. //func (s *Skiplist) keyIsAfterNode(key []byte, n *node) bool {
  139. // y.AssertTrue(n != s.head)
  140. // return n != nil && y.CompareKeys(key, n.key) > 0
  141. //}
  142. func (s *Skiplist) randomHeight() int {
  143. h := 1
  144. for h < maxHeight && z.FastRand() <= heightIncrease {
  145. h++
  146. }
  147. return h
  148. }
  149. func (s *Skiplist) getNext(nd *node, height int) *node {
  150. return s.arena.getNode(nd.getNextOffset(height))
  151. }
  152. // findNear finds the node near to key.
  153. // If less=true, it finds rightmost node such that node.key < key (if allowEqual=false) or
  154. // node.key <= key (if allowEqual=true).
  155. // If less=false, it finds leftmost node such that node.key > key (if allowEqual=false) or
  156. // node.key >= key (if allowEqual=true).
  157. // Returns the node found. The bool returned is true if the node has key equal to given key.
  158. func (s *Skiplist) findNear(key []byte, less bool, allowEqual bool) (*node, bool) {
  159. x := s.head
  160. level := int(s.getHeight() - 1)
  161. for {
  162. // Assume x.key < key.
  163. next := s.getNext(x, level)
  164. if next == nil {
  165. // x.key < key < END OF LIST
  166. if level > 0 {
  167. // Can descend further to iterate closer to the end.
  168. level--
  169. continue
  170. }
  171. // Level=0. Cannot descend further. Let's return something that makes sense.
  172. if !less {
  173. return nil, false
  174. }
  175. // Try to return x. Make sure it is not a head node.
  176. if x == s.head {
  177. return nil, false
  178. }
  179. return x, false
  180. }
  181. nextKey := next.key(s.arena)
  182. cmp := y.CompareKeys(key, nextKey)
  183. if cmp > 0 {
  184. // x.key < next.key < key. We can continue to move right.
  185. x = next
  186. continue
  187. }
  188. if cmp == 0 {
  189. // x.key < key == next.key.
  190. if allowEqual {
  191. return next, true
  192. }
  193. if !less {
  194. // We want >, so go to base level to grab the next bigger note.
  195. return s.getNext(next, 0), false
  196. }
  197. // We want <. If not base level, we should go closer in the next level.
  198. if level > 0 {
  199. level--
  200. continue
  201. }
  202. // On base level. Return x.
  203. if x == s.head {
  204. return nil, false
  205. }
  206. return x, false
  207. }
  208. // cmp < 0. In other words, x.key < key < next.
  209. if level > 0 {
  210. level--
  211. continue
  212. }
  213. // At base level. Need to return something.
  214. if !less {
  215. return next, false
  216. }
  217. // Try to return x. Make sure it is not a head node.
  218. if x == s.head {
  219. return nil, false
  220. }
  221. return x, false
  222. }
  223. }
  224. // findSpliceForLevel returns (outBefore, outAfter) with outBefore.key <= key <= outAfter.key.
  225. // The input "before" tells us where to start looking.
  226. // If we found a node with the same key, then we return outBefore = outAfter.
  227. // Otherwise, outBefore.key < key < outAfter.key.
  228. func (s *Skiplist) findSpliceForLevel(key []byte, before *node, level int) (*node, *node) {
  229. for {
  230. // Assume before.key < key.
  231. next := s.getNext(before, level)
  232. if next == nil {
  233. return before, next
  234. }
  235. nextKey := next.key(s.arena)
  236. cmp := y.CompareKeys(key, nextKey)
  237. if cmp == 0 {
  238. // Equality case.
  239. return next, next
  240. }
  241. if cmp < 0 {
  242. // before.key < key < next.key. We are done for this level.
  243. return before, next
  244. }
  245. before = next // Keep moving right on this level.
  246. }
  247. }
  248. func (s *Skiplist) getHeight() int32 {
  249. return s.height.Load()
  250. }
  251. // Put inserts the key-value pair.
  252. func (s *Skiplist) Put(key []byte, v y.ValueStruct) {
  253. // Since we allow overwrite, we may not need to create a new node. We might not even need to
  254. // increase the height. Let's defer these actions.
  255. listHeight := s.getHeight()
  256. var prev [maxHeight + 1]*node
  257. var next [maxHeight + 1]*node
  258. prev[listHeight] = s.head
  259. next[listHeight] = nil
  260. for i := int(listHeight) - 1; i >= 0; i-- {
  261. // Use higher level to speed up for current level.
  262. prev[i], next[i] = s.findSpliceForLevel(key, prev[i+1], i)
  263. if prev[i] == next[i] {
  264. prev[i].setValue(s.arena, v)
  265. return
  266. }
  267. }
  268. // We do need to create a new node.
  269. height := s.randomHeight()
  270. x := newNode(s.arena, key, v, height)
  271. // Try to increase s.height via CAS.
  272. listHeight = s.getHeight()
  273. for height > int(listHeight) {
  274. if s.height.CompareAndSwap(listHeight, int32(height)) {
  275. // Successfully increased skiplist.height.
  276. break
  277. }
  278. listHeight = s.getHeight()
  279. }
  280. // We always insert from the base level and up. After you add a node in base level, we cannot
  281. // create a node in the level above because it would have discovered the node in the base level.
  282. for i := 0; i < height; i++ {
  283. for {
  284. if prev[i] == nil {
  285. y.AssertTrue(i > 1) // This cannot happen in base level.
  286. // We haven't computed prev, next for this level because height exceeds old listHeight.
  287. // For these levels, we expect the lists to be sparse, so we can just search from head.
  288. prev[i], next[i] = s.findSpliceForLevel(key, s.head, i)
  289. // Someone adds the exact same key before we are able to do so. This can only happen on
  290. // the base level. But we know we are not on the base level.
  291. y.AssertTrue(prev[i] != next[i])
  292. }
  293. nextOffset := s.arena.getNodeOffset(next[i])
  294. x.tower[i].Store(nextOffset)
  295. if prev[i].casNextOffset(i, nextOffset, s.arena.getNodeOffset(x)) {
  296. // Managed to insert x between prev[i] and next[i]. Go to the next level.
  297. break
  298. }
  299. // CAS failed. We need to recompute prev and next.
  300. // It is unlikely to be helpful to try to use a different level as we redo the search,
  301. // because it is unlikely that lots of nodes are inserted between prev[i] and next[i].
  302. prev[i], next[i] = s.findSpliceForLevel(key, prev[i], i)
  303. if prev[i] == next[i] {
  304. y.AssertTruef(i == 0, "Equality can happen only on base level: %d", i)
  305. prev[i].setValue(s.arena, v)
  306. return
  307. }
  308. }
  309. }
  310. }
  311. // Empty returns if the Skiplist is empty.
  312. func (s *Skiplist) Empty() bool {
  313. return s.findLast() == nil
  314. }
  315. // findLast returns the last element. If head (empty list), we return nil. All the find functions
  316. // will NEVER return the head nodes.
  317. func (s *Skiplist) findLast() *node {
  318. n := s.head
  319. level := int(s.getHeight()) - 1
  320. for {
  321. next := s.getNext(n, level)
  322. if next != nil {
  323. n = next
  324. continue
  325. }
  326. if level == 0 {
  327. if n == s.head {
  328. return nil
  329. }
  330. return n
  331. }
  332. level--
  333. }
  334. }
  335. // Get gets the value associated with the key. It returns a valid value if it finds equal or earlier
  336. // version of the same key.
  337. func (s *Skiplist) Get(key []byte) y.ValueStruct {
  338. n, _ := s.findNear(key, false, true) // findGreaterOrEqual.
  339. if n == nil {
  340. return y.ValueStruct{}
  341. }
  342. nextKey := s.arena.getKey(n.keyOffset, n.keySize)
  343. if !y.SameKey(key, nextKey) {
  344. return y.ValueStruct{}
  345. }
  346. valOffset, valSize := n.getValueOffset()
  347. vs := s.arena.getVal(valOffset, valSize)
  348. vs.Version = y.ParseTs(nextKey)
  349. return vs
  350. }
  351. // NewIterator returns a skiplist iterator. You have to Close() the iterator.
  352. func (s *Skiplist) NewIterator() *Iterator {
  353. s.IncrRef()
  354. return &Iterator{list: s}
  355. }
  356. // MemSize returns the size of the Skiplist in terms of how much memory is used within its internal
  357. // arena.
  358. func (s *Skiplist) MemSize() int64 { return s.arena.size() }
  359. // Iterator is an iterator over skiplist object. For new objects, you just
  360. // need to initialize Iterator.list.
  361. type Iterator struct {
  362. list *Skiplist
  363. n *node
  364. }
  365. // Close frees the resources held by the iterator
  366. func (s *Iterator) Close() error {
  367. s.list.DecrRef()
  368. return nil
  369. }
  370. // Valid returns true iff the iterator is positioned at a valid node.
  371. func (s *Iterator) Valid() bool { return s.n != nil }
  372. // Key returns the key at the current position.
  373. func (s *Iterator) Key() []byte {
  374. return s.list.arena.getKey(s.n.keyOffset, s.n.keySize)
  375. }
  376. // Value returns value.
  377. func (s *Iterator) Value() y.ValueStruct {
  378. valOffset, valSize := s.n.getValueOffset()
  379. return s.list.arena.getVal(valOffset, valSize)
  380. }
  381. // ValueUint64 returns the uint64 value of the current node.
  382. func (s *Iterator) ValueUint64() uint64 {
  383. return s.n.value.Load()
  384. }
  385. // Next advances to the next position.
  386. func (s *Iterator) Next() {
  387. y.AssertTrue(s.Valid())
  388. s.n = s.list.getNext(s.n, 0)
  389. }
  390. // Prev advances to the previous position.
  391. func (s *Iterator) Prev() {
  392. y.AssertTrue(s.Valid())
  393. s.n, _ = s.list.findNear(s.Key(), true, false) // find <. No equality allowed.
  394. }
  395. // Seek advances to the first entry with a key >= target.
  396. func (s *Iterator) Seek(target []byte) {
  397. s.n, _ = s.list.findNear(target, false, true) // find >=.
  398. }
  399. // SeekForPrev finds an entry with key <= target.
  400. func (s *Iterator) SeekForPrev(target []byte) {
  401. s.n, _ = s.list.findNear(target, true, true) // find <=.
  402. }
  403. // SeekToFirst seeks position at the first entry in list.
  404. // Final state of iterator is Valid() iff list is not empty.
  405. func (s *Iterator) SeekToFirst() {
  406. s.n = s.list.getNext(s.list.head, 0)
  407. }
  408. // SeekToLast seeks position at the last entry in list.
  409. // Final state of iterator is Valid() iff list is not empty.
  410. func (s *Iterator) SeekToLast() {
  411. s.n = s.list.findLast()
  412. }
  413. // UniIterator is a unidirectional memtable iterator. It is a thin wrapper around
  414. // Iterator. We like to keep Iterator as before, because it is more powerful and
  415. // we might support bidirectional iterators in the future.
  416. type UniIterator struct {
  417. iter *Iterator
  418. reversed bool
  419. }
  420. // NewUniIterator returns a UniIterator.
  421. func (s *Skiplist) NewUniIterator(reversed bool) *UniIterator {
  422. return &UniIterator{
  423. iter: s.NewIterator(),
  424. reversed: reversed,
  425. }
  426. }
  427. // Next implements y.Interface
  428. func (s *UniIterator) Next() {
  429. if !s.reversed {
  430. s.iter.Next()
  431. } else {
  432. s.iter.Prev()
  433. }
  434. }
  435. // Rewind implements y.Interface
  436. func (s *UniIterator) Rewind() {
  437. if !s.reversed {
  438. s.iter.SeekToFirst()
  439. } else {
  440. s.iter.SeekToLast()
  441. }
  442. }
  443. // Seek implements y.Interface
  444. func (s *UniIterator) Seek(key []byte) {
  445. if !s.reversed {
  446. s.iter.Seek(key)
  447. } else {
  448. s.iter.SeekForPrev(key)
  449. }
  450. }
  451. // Key implements y.Interface
  452. func (s *UniIterator) Key() []byte { return s.iter.Key() }
  453. // Value implements y.Interface
  454. func (s *UniIterator) Value() y.ValueStruct { return s.iter.Value() }
  455. // Valid implements y.Interface
  456. func (s *UniIterator) Valid() bool { return s.iter.Valid() }
  457. // Close implements y.Interface (and frees up the iter's resources)
  458. func (s *UniIterator) Close() error { return s.iter.Close() }