bucket.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. package bolt
  2. import (
  3. "bytes"
  4. "fmt"
  5. "unsafe"
  6. )
  7. const (
  8. // MaxKeySize is the maximum length of a key, in bytes.
  9. MaxKeySize = 32768
  10. // MaxValueSize is the maximum length of a value, in bytes.
  11. MaxValueSize = (1 << 31) - 2
  12. )
  13. const (
  14. maxUint = ^uint(0)
  15. minUint = 0
  16. maxInt = int(^uint(0) >> 1)
  17. minInt = -maxInt - 1
  18. )
  19. const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
  20. const (
  21. minFillPercent = 0.1
  22. maxFillPercent = 1.0
  23. )
  24. // DefaultFillPercent is the percentage that split pages are filled.
  25. // This value can be changed by setting Bucket.FillPercent.
  26. const DefaultFillPercent = 0.5
  27. // Bucket represents a collection of key/value pairs inside the database.
  28. type Bucket struct {
  29. *bucket
  30. tx *Tx // the associated transaction
  31. buckets map[string]*Bucket // subbucket cache
  32. page *page // inline page reference
  33. rootNode *node // materialized node for the root page.
  34. nodes map[pgid]*node // node cache
  35. // Sets the threshold for filling nodes when they split. By default,
  36. // the bucket will fill to 50% but it can be useful to increase this
  37. // amount if you know that your write workloads are mostly append-only.
  38. //
  39. // This is non-persisted across transactions so it must be set in every Tx.
  40. FillPercent float64
  41. }
  42. // bucket represents the on-file representation of a bucket.
  43. // This is stored as the "value" of a bucket key. If the bucket is small enough,
  44. // then its root page can be stored inline in the "value", after the bucket
  45. // header. In the case of inline buckets, the "root" will be 0.
  46. type bucket struct {
  47. root pgid // page id of the bucket's root-level page
  48. sequence uint64 // monotonically incrementing, used by NextSequence()
  49. }
  50. // newBucket returns a new bucket associated with a transaction.
  51. func newBucket(tx *Tx) Bucket {
  52. var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
  53. if tx.writable {
  54. b.buckets = make(map[string]*Bucket)
  55. b.nodes = make(map[pgid]*node)
  56. }
  57. return b
  58. }
  59. // Tx returns the tx of the bucket.
  60. func (b *Bucket) Tx() *Tx {
  61. return b.tx
  62. }
  63. // Root returns the root of the bucket.
  64. func (b *Bucket) Root() pgid {
  65. return b.root
  66. }
  67. // Writable returns whether the bucket is writable.
  68. func (b *Bucket) Writable() bool {
  69. return b.tx.writable
  70. }
  71. // Cursor creates a cursor associated with the bucket.
  72. // The cursor is only valid as long as the transaction is open.
  73. // Do not use a cursor after the transaction is closed.
  74. func (b *Bucket) Cursor() *Cursor {
  75. // Update transaction statistics.
  76. b.tx.stats.CursorCount++
  77. // Allocate and return a cursor.
  78. return &Cursor{
  79. bucket: b,
  80. stack: make([]elemRef, 0),
  81. }
  82. }
  83. // Bucket retrieves a nested bucket by name.
  84. // Returns nil if the bucket does not exist.
  85. // The bucket instance is only valid for the lifetime of the transaction.
  86. func (b *Bucket) Bucket(name []byte) *Bucket {
  87. if b.buckets != nil {
  88. if child := b.buckets[string(name)]; child != nil {
  89. return child
  90. }
  91. }
  92. // Move cursor to key.
  93. c := b.Cursor()
  94. k, v, flags := c.seek(name)
  95. // Return nil if the key doesn't exist or it is not a bucket.
  96. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
  97. return nil
  98. }
  99. // Otherwise create a bucket and cache it.
  100. var child = b.openBucket(v)
  101. if b.buckets != nil {
  102. b.buckets[string(name)] = child
  103. }
  104. return child
  105. }
  106. // Helper method that re-interprets a sub-bucket value
  107. // from a parent into a Bucket
  108. func (b *Bucket) openBucket(value []byte) *Bucket {
  109. var child = newBucket(b.tx)
  110. // If unaligned load/stores are broken on this arch and value is
  111. // unaligned simply clone to an aligned byte array.
  112. unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
  113. if unaligned {
  114. value = cloneBytes(value)
  115. }
  116. // If this is a writable transaction then we need to copy the bucket entry.
  117. // Read-only transactions can point directly at the mmap entry.
  118. if b.tx.writable && !unaligned {
  119. child.bucket = &bucket{}
  120. *child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
  121. } else {
  122. child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
  123. }
  124. // Save a reference to the inline page if the bucket is inline.
  125. if child.root == 0 {
  126. child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  127. }
  128. return &child
  129. }
  130. // CreateBucket creates a new bucket at the given key and returns the new bucket.
  131. // Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
  132. // The bucket instance is only valid for the lifetime of the transaction.
  133. func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
  134. if b.tx.db == nil {
  135. return nil, ErrTxClosed
  136. } else if !b.tx.writable {
  137. return nil, ErrTxNotWritable
  138. } else if len(key) == 0 {
  139. return nil, ErrBucketNameRequired
  140. }
  141. // Move cursor to correct position.
  142. c := b.Cursor()
  143. k, _, flags := c.seek(key)
  144. // Return an error if there is an existing key.
  145. if bytes.Equal(key, k) {
  146. if (flags & bucketLeafFlag) != 0 {
  147. return nil, ErrBucketExists
  148. } else {
  149. return nil, ErrIncompatibleValue
  150. }
  151. }
  152. // Create empty, inline bucket.
  153. var bucket = Bucket{
  154. bucket: &bucket{},
  155. rootNode: &node{isLeaf: true},
  156. FillPercent: DefaultFillPercent,
  157. }
  158. var value = bucket.write()
  159. // Insert into node.
  160. key = cloneBytes(key)
  161. c.node().put(key, key, value, 0, bucketLeafFlag)
  162. // Since subbuckets are not allowed on inline buckets, we need to
  163. // dereference the inline page, if it exists. This will cause the bucket
  164. // to be treated as a regular, non-inline bucket for the rest of the tx.
  165. b.page = nil
  166. return b.Bucket(key), nil
  167. }
  168. // CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
  169. // Returns an error if the bucket name is blank, or if the bucket name is too long.
  170. // The bucket instance is only valid for the lifetime of the transaction.
  171. func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
  172. child, err := b.CreateBucket(key)
  173. if err == ErrBucketExists {
  174. return b.Bucket(key), nil
  175. } else if err != nil {
  176. return nil, err
  177. }
  178. return child, nil
  179. }
  180. // DeleteBucket deletes a bucket at the given key.
  181. // Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
  182. func (b *Bucket) DeleteBucket(key []byte) error {
  183. if b.tx.db == nil {
  184. return ErrTxClosed
  185. } else if !b.Writable() {
  186. return ErrTxNotWritable
  187. }
  188. // Move cursor to correct position.
  189. c := b.Cursor()
  190. k, _, flags := c.seek(key)
  191. // Return an error if bucket doesn't exist or is not a bucket.
  192. if !bytes.Equal(key, k) {
  193. return ErrBucketNotFound
  194. } else if (flags & bucketLeafFlag) == 0 {
  195. return ErrIncompatibleValue
  196. }
  197. // Recursively delete all child buckets.
  198. child := b.Bucket(key)
  199. err := child.ForEach(func(k, v []byte) error {
  200. if v == nil {
  201. if err := child.DeleteBucket(k); err != nil {
  202. return fmt.Errorf("delete bucket: %s", err)
  203. }
  204. }
  205. return nil
  206. })
  207. if err != nil {
  208. return err
  209. }
  210. // Remove cached copy.
  211. delete(b.buckets, string(key))
  212. // Release all bucket pages to freelist.
  213. child.nodes = nil
  214. child.rootNode = nil
  215. child.free()
  216. // Delete the node if we have a matching key.
  217. c.node().del(key)
  218. return nil
  219. }
  220. // Get retrieves the value for a key in the bucket.
  221. // Returns a nil value if the key does not exist or if the key is a nested bucket.
  222. // The returned value is only valid for the life of the transaction.
  223. func (b *Bucket) Get(key []byte) []byte {
  224. k, v, flags := b.Cursor().seek(key)
  225. // Return nil if this is a bucket.
  226. if (flags & bucketLeafFlag) != 0 {
  227. return nil
  228. }
  229. // If our target node isn't the same key as what's passed in then return nil.
  230. if !bytes.Equal(key, k) {
  231. return nil
  232. }
  233. return v
  234. }
  235. // Put sets the value for a key in the bucket.
  236. // If the key exist then its previous value will be overwritten.
  237. // Supplied value must remain valid for the life of the transaction.
  238. // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
  239. func (b *Bucket) Put(key []byte, value []byte) error {
  240. if b.tx.db == nil {
  241. return ErrTxClosed
  242. } else if !b.Writable() {
  243. return ErrTxNotWritable
  244. } else if len(key) == 0 {
  245. return ErrKeyRequired
  246. } else if len(key) > MaxKeySize {
  247. return ErrKeyTooLarge
  248. } else if int64(len(value)) > MaxValueSize {
  249. return ErrValueTooLarge
  250. }
  251. // Move cursor to correct position.
  252. c := b.Cursor()
  253. k, _, flags := c.seek(key)
  254. // Return an error if there is an existing key with a bucket value.
  255. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
  256. return ErrIncompatibleValue
  257. }
  258. // Insert into node.
  259. key = cloneBytes(key)
  260. c.node().put(key, key, value, 0, 0)
  261. return nil
  262. }
  263. // Delete removes a key from the bucket.
  264. // If the key does not exist then nothing is done and a nil error is returned.
  265. // Returns an error if the bucket was created from a read-only transaction.
  266. func (b *Bucket) Delete(key []byte) error {
  267. if b.tx.db == nil {
  268. return ErrTxClosed
  269. } else if !b.Writable() {
  270. return ErrTxNotWritable
  271. }
  272. // Move cursor to correct position.
  273. c := b.Cursor()
  274. _, _, flags := c.seek(key)
  275. // Return an error if there is already existing bucket value.
  276. if (flags & bucketLeafFlag) != 0 {
  277. return ErrIncompatibleValue
  278. }
  279. // Delete the node if we have a matching key.
  280. c.node().del(key)
  281. return nil
  282. }
  283. // Sequence returns the current integer for the bucket without incrementing it.
  284. func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
  285. // SetSequence updates the sequence number for the bucket.
  286. func (b *Bucket) SetSequence(v uint64) error {
  287. if b.tx.db == nil {
  288. return ErrTxClosed
  289. } else if !b.Writable() {
  290. return ErrTxNotWritable
  291. }
  292. // Materialize the root node if it hasn't been already so that the
  293. // bucket will be saved during commit.
  294. if b.rootNode == nil {
  295. _ = b.node(b.root, nil)
  296. }
  297. // Increment and return the sequence.
  298. b.bucket.sequence = v
  299. return nil
  300. }
  301. // NextSequence returns an autoincrementing integer for the bucket.
  302. func (b *Bucket) NextSequence() (uint64, error) {
  303. if b.tx.db == nil {
  304. return 0, ErrTxClosed
  305. } else if !b.Writable() {
  306. return 0, ErrTxNotWritable
  307. }
  308. // Materialize the root node if it hasn't been already so that the
  309. // bucket will be saved during commit.
  310. if b.rootNode == nil {
  311. _ = b.node(b.root, nil)
  312. }
  313. // Increment and return the sequence.
  314. b.bucket.sequence++
  315. return b.bucket.sequence, nil
  316. }
  317. // ForEach executes a function for each key/value pair in a bucket.
  318. // If the provided function returns an error then the iteration is stopped and
  319. // the error is returned to the caller. The provided function must not modify
  320. // the bucket; this will result in undefined behavior.
  321. func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
  322. if b.tx.db == nil {
  323. return ErrTxClosed
  324. }
  325. c := b.Cursor()
  326. for k, v := c.First(); k != nil; k, v = c.Next() {
  327. if err := fn(k, v); err != nil {
  328. return err
  329. }
  330. }
  331. return nil
  332. }
  333. // Stat returns stats on a bucket.
  334. func (b *Bucket) Stats() BucketStats {
  335. var s, subStats BucketStats
  336. pageSize := b.tx.db.pageSize
  337. s.BucketN += 1
  338. if b.root == 0 {
  339. s.InlineBucketN += 1
  340. }
  341. b.forEachPage(func(p *page, depth int) {
  342. if (p.flags & leafPageFlag) != 0 {
  343. s.KeyN += int(p.count)
  344. // used totals the used bytes for the page
  345. used := pageHeaderSize
  346. if p.count != 0 {
  347. // If page has any elements, add all element headers.
  348. used += leafPageElementSize * int(p.count-1)
  349. // Add all element key, value sizes.
  350. // The computation takes advantage of the fact that the position
  351. // of the last element's key/value equals to the total of the sizes
  352. // of all previous elements' keys and values.
  353. // It also includes the last element's header.
  354. lastElement := p.leafPageElement(p.count - 1)
  355. used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
  356. }
  357. if b.root == 0 {
  358. // For inlined bucket just update the inline stats
  359. s.InlineBucketInuse += used
  360. } else {
  361. // For non-inlined bucket update all the leaf stats
  362. s.LeafPageN++
  363. s.LeafInuse += used
  364. s.LeafOverflowN += int(p.overflow)
  365. // Collect stats from sub-buckets.
  366. // Do that by iterating over all element headers
  367. // looking for the ones with the bucketLeafFlag.
  368. for i := uint16(0); i < p.count; i++ {
  369. e := p.leafPageElement(i)
  370. if (e.flags & bucketLeafFlag) != 0 {
  371. // For any bucket element, open the element value
  372. // and recursively call Stats on the contained bucket.
  373. subStats.Add(b.openBucket(e.value()).Stats())
  374. }
  375. }
  376. }
  377. } else if (p.flags & branchPageFlag) != 0 {
  378. s.BranchPageN++
  379. lastElement := p.branchPageElement(p.count - 1)
  380. // used totals the used bytes for the page
  381. // Add header and all element headers.
  382. used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
  383. // Add size of all keys and values.
  384. // Again, use the fact that last element's position equals to
  385. // the total of key, value sizes of all previous elements.
  386. used += int(lastElement.pos + lastElement.ksize)
  387. s.BranchInuse += used
  388. s.BranchOverflowN += int(p.overflow)
  389. }
  390. // Keep track of maximum page depth.
  391. if depth+1 > s.Depth {
  392. s.Depth = (depth + 1)
  393. }
  394. })
  395. // Alloc stats can be computed from page counts and pageSize.
  396. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
  397. s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
  398. // Add the max depth of sub-buckets to get total nested depth.
  399. s.Depth += subStats.Depth
  400. // Add the stats for all sub-buckets
  401. s.Add(subStats)
  402. return s
  403. }
  404. // forEachPage iterates over every page in a bucket, including inline pages.
  405. func (b *Bucket) forEachPage(fn func(*page, int)) {
  406. // If we have an inline page then just use that.
  407. if b.page != nil {
  408. fn(b.page, 0)
  409. return
  410. }
  411. // Otherwise traverse the page hierarchy.
  412. b.tx.forEachPage(b.root, 0, fn)
  413. }
  414. // forEachPageNode iterates over every page (or node) in a bucket.
  415. // This also includes inline pages.
  416. func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
  417. // If we have an inline page or root node then just use that.
  418. if b.page != nil {
  419. fn(b.page, nil, 0)
  420. return
  421. }
  422. b._forEachPageNode(b.root, 0, fn)
  423. }
  424. func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
  425. var p, n = b.pageNode(pgid)
  426. // Execute function.
  427. fn(p, n, depth)
  428. // Recursively loop over children.
  429. if p != nil {
  430. if (p.flags & branchPageFlag) != 0 {
  431. for i := 0; i < int(p.count); i++ {
  432. elem := p.branchPageElement(uint16(i))
  433. b._forEachPageNode(elem.pgid, depth+1, fn)
  434. }
  435. }
  436. } else {
  437. if !n.isLeaf {
  438. for _, inode := range n.inodes {
  439. b._forEachPageNode(inode.pgid, depth+1, fn)
  440. }
  441. }
  442. }
  443. }
  444. // spill writes all the nodes for this bucket to dirty pages.
  445. func (b *Bucket) spill() error {
  446. // Spill all child buckets first.
  447. for name, child := range b.buckets {
  448. // If the child bucket is small enough and it has no child buckets then
  449. // write it inline into the parent bucket's page. Otherwise spill it
  450. // like a normal bucket and make the parent value a pointer to the page.
  451. var value []byte
  452. if child.inlineable() {
  453. child.free()
  454. value = child.write()
  455. } else {
  456. if err := child.spill(); err != nil {
  457. return err
  458. }
  459. // Update the child bucket header in this bucket.
  460. value = make([]byte, unsafe.Sizeof(bucket{}))
  461. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  462. *bucket = *child.bucket
  463. }
  464. // Skip writing the bucket if there are no materialized nodes.
  465. if child.rootNode == nil {
  466. continue
  467. }
  468. // Update parent node.
  469. var c = b.Cursor()
  470. k, _, flags := c.seek([]byte(name))
  471. if !bytes.Equal([]byte(name), k) {
  472. panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
  473. }
  474. if flags&bucketLeafFlag == 0 {
  475. panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
  476. }
  477. c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
  478. }
  479. // Ignore if there's not a materialized root node.
  480. if b.rootNode == nil {
  481. return nil
  482. }
  483. // Spill nodes.
  484. if err := b.rootNode.spill(); err != nil {
  485. return err
  486. }
  487. b.rootNode = b.rootNode.root()
  488. // Update the root node for this bucket.
  489. if b.rootNode.pgid >= b.tx.meta.pgid {
  490. panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
  491. }
  492. b.root = b.rootNode.pgid
  493. return nil
  494. }
  495. // inlineable returns true if a bucket is small enough to be written inline
  496. // and if it contains no subbuckets. Otherwise returns false.
  497. func (b *Bucket) inlineable() bool {
  498. var n = b.rootNode
  499. // Bucket must only contain a single leaf node.
  500. if n == nil || !n.isLeaf {
  501. return false
  502. }
  503. // Bucket is not inlineable if it contains subbuckets or if it goes beyond
  504. // our threshold for inline bucket size.
  505. var size = pageHeaderSize
  506. for _, inode := range n.inodes {
  507. size += leafPageElementSize + len(inode.key) + len(inode.value)
  508. if inode.flags&bucketLeafFlag != 0 {
  509. return false
  510. } else if size > b.maxInlineBucketSize() {
  511. return false
  512. }
  513. }
  514. return true
  515. }
  516. // Returns the maximum total size of a bucket to make it a candidate for inlining.
  517. func (b *Bucket) maxInlineBucketSize() int {
  518. return b.tx.db.pageSize / 4
  519. }
  520. // write allocates and writes a bucket to a byte slice.
  521. func (b *Bucket) write() []byte {
  522. // Allocate the appropriate size.
  523. var n = b.rootNode
  524. var value = make([]byte, bucketHeaderSize+n.size())
  525. // Write a bucket header.
  526. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  527. *bucket = *b.bucket
  528. // Convert byte slice to a fake page and write the root node.
  529. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  530. n.write(p)
  531. return value
  532. }
  533. // rebalance attempts to balance all nodes.
  534. func (b *Bucket) rebalance() {
  535. for _, n := range b.nodes {
  536. n.rebalance()
  537. }
  538. for _, child := range b.buckets {
  539. child.rebalance()
  540. }
  541. }
  542. // node creates a node from a page and associates it with a given parent.
  543. func (b *Bucket) node(pgid pgid, parent *node) *node {
  544. _assert(b.nodes != nil, "nodes map expected")
  545. // Retrieve node if it's already been created.
  546. if n := b.nodes[pgid]; n != nil {
  547. return n
  548. }
  549. // Otherwise create a node and cache it.
  550. n := &node{bucket: b, parent: parent}
  551. if parent == nil {
  552. b.rootNode = n
  553. } else {
  554. parent.children = append(parent.children, n)
  555. }
  556. // Use the inline page if this is an inline bucket.
  557. var p = b.page
  558. if p == nil {
  559. p = b.tx.page(pgid)
  560. }
  561. // Read the page into the node and cache it.
  562. n.read(p)
  563. b.nodes[pgid] = n
  564. // Update statistics.
  565. b.tx.stats.NodeCount++
  566. return n
  567. }
  568. // free recursively frees all pages in the bucket.
  569. func (b *Bucket) free() {
  570. if b.root == 0 {
  571. return
  572. }
  573. var tx = b.tx
  574. b.forEachPageNode(func(p *page, n *node, _ int) {
  575. if p != nil {
  576. tx.db.freelist.free(tx.meta.txid, p)
  577. } else {
  578. n.free()
  579. }
  580. })
  581. b.root = 0
  582. }
  583. // dereference removes all references to the old mmap.
  584. func (b *Bucket) dereference() {
  585. if b.rootNode != nil {
  586. b.rootNode.root().dereference()
  587. }
  588. for _, child := range b.buckets {
  589. child.dereference()
  590. }
  591. }
  592. // pageNode returns the in-memory node, if it exists.
  593. // Otherwise returns the underlying page.
  594. func (b *Bucket) pageNode(id pgid) (*page, *node) {
  595. // Inline buckets have a fake page embedded in their value so treat them
  596. // differently. We'll return the rootNode (if available) or the fake page.
  597. if b.root == 0 {
  598. if id != 0 {
  599. panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
  600. }
  601. if b.rootNode != nil {
  602. return nil, b.rootNode
  603. }
  604. return b.page, nil
  605. }
  606. // Check the node cache for non-inline buckets.
  607. if b.nodes != nil {
  608. if n := b.nodes[id]; n != nil {
  609. return nil, n
  610. }
  611. }
  612. // Finally lookup the page from the transaction if no node is materialized.
  613. return b.tx.page(id), nil
  614. }
  615. // BucketStats records statistics about resources used by a bucket.
  616. type BucketStats struct {
  617. // Page count statistics.
  618. BranchPageN int // number of logical branch pages
  619. BranchOverflowN int // number of physical branch overflow pages
  620. LeafPageN int // number of logical leaf pages
  621. LeafOverflowN int // number of physical leaf overflow pages
  622. // Tree statistics.
  623. KeyN int // number of keys/value pairs
  624. Depth int // number of levels in B+tree
  625. // Page size utilization.
  626. BranchAlloc int // bytes allocated for physical branch pages
  627. BranchInuse int // bytes actually used for branch data
  628. LeafAlloc int // bytes allocated for physical leaf pages
  629. LeafInuse int // bytes actually used for leaf data
  630. // Bucket statistics
  631. BucketN int // total number of buckets including the top bucket
  632. InlineBucketN int // total number on inlined buckets
  633. InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
  634. }
  635. func (s *BucketStats) Add(other BucketStats) {
  636. s.BranchPageN += other.BranchPageN
  637. s.BranchOverflowN += other.BranchOverflowN
  638. s.LeafPageN += other.LeafPageN
  639. s.LeafOverflowN += other.LeafOverflowN
  640. s.KeyN += other.KeyN
  641. if s.Depth < other.Depth {
  642. s.Depth = other.Depth
  643. }
  644. s.BranchAlloc += other.BranchAlloc
  645. s.BranchInuse += other.BranchInuse
  646. s.LeafAlloc += other.LeafAlloc
  647. s.LeafInuse += other.LeafInuse
  648. s.BucketN += other.BucketN
  649. s.InlineBucketN += other.InlineBucketN
  650. s.InlineBucketInuse += other.InlineBucketInuse
  651. }
  652. // cloneBytes returns a copy of a given slice.
  653. func cloneBytes(v []byte) []byte {
  654. var clone = make([]byte, len(v))
  655. copy(clone, v)
  656. return clone
  657. }