calloc_jemalloc.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Copyright 2020 The LevelDB-Go and Pebble Authors. All rights reserved. Use
  2. // of this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. // +build jemalloc
  5. package z
  6. /*
  7. #cgo LDFLAGS: /usr/local/lib/libjemalloc.a -L/usr/local/lib -Wl,-rpath,/usr/local/lib -ljemalloc -lm -lstdc++ -pthread -ldl
  8. #include <stdlib.h>
  9. #include <jemalloc/jemalloc.h>
  10. */
  11. import "C"
  12. import (
  13. "bytes"
  14. "fmt"
  15. "sync"
  16. "sync/atomic"
  17. "unsafe"
  18. "github.com/dustin/go-humanize"
  19. )
  20. // The go:linkname directives provides backdoor access to private functions in
  21. // the runtime. Below we're accessing the throw function.
  22. //go:linkname throw runtime.throw
  23. func throw(s string)
  24. // New allocates a slice of size n. The returned slice is from manually managed
  25. // memory and MUST be released by calling Free. Failure to do so will result in
  26. // a memory leak.
  27. //
  28. // Compile jemalloc with ./configure --with-jemalloc-prefix="je_"
  29. // https://android.googlesource.com/platform/external/jemalloc_new/+/6840b22e8e11cb68b493297a5cd757d6eaa0b406/TUNING.md
  30. // These two config options seems useful for frequent allocations and deallocations in
  31. // multi-threaded programs (like we have).
  32. // JE_MALLOC_CONF="background_thread:true,metadata_thp:auto"
  33. //
  34. // Compile Go program with `go build -tags=jemalloc` to enable this.
  35. type dalloc struct {
  36. t string
  37. sz int
  38. }
  39. var dallocsMu sync.Mutex
  40. var dallocs map[unsafe.Pointer]*dalloc
  41. func init() {
  42. // By initializing dallocs, we can start tracking allocations and deallocations via z.Calloc.
  43. dallocs = make(map[unsafe.Pointer]*dalloc)
  44. }
  45. func Calloc(n int, tag string) []byte {
  46. if n == 0 {
  47. return make([]byte, 0)
  48. }
  49. // We need to be conscious of the Cgo pointer passing rules:
  50. //
  51. // https://golang.org/cmd/cgo/#hdr-Passing_pointers
  52. //
  53. // ...
  54. // Note: the current implementation has a bug. While Go code is permitted
  55. // to write nil or a C pointer (but not a Go pointer) to C memory, the
  56. // current implementation may sometimes cause a runtime error if the
  57. // contents of the C memory appear to be a Go pointer. Therefore, avoid
  58. // passing uninitialized C memory to Go code if the Go code is going to
  59. // store pointer values in it. Zero out the memory in C before passing it
  60. // to Go.
  61. ptr := C.je_calloc(C.size_t(n), 1)
  62. if ptr == nil {
  63. // NB: throw is like panic, except it guarantees the process will be
  64. // terminated. The call below is exactly what the Go runtime invokes when
  65. // it cannot allocate memory.
  66. throw("out of memory")
  67. }
  68. uptr := unsafe.Pointer(ptr)
  69. dallocsMu.Lock()
  70. dallocs[uptr] = &dalloc{
  71. t: tag,
  72. sz: n,
  73. }
  74. dallocsMu.Unlock()
  75. atomic.AddInt64(&numBytes, int64(n))
  76. // Interpret the C pointer as a pointer to a Go array, then slice.
  77. return (*[MaxArrayLen]byte)(uptr)[:n:n]
  78. }
  79. // CallocNoRef does the exact same thing as Calloc with jemalloc enabled.
  80. func CallocNoRef(n int, tag string) []byte {
  81. return Calloc(n, tag)
  82. }
  83. // Free frees the specified slice.
  84. func Free(b []byte) {
  85. if sz := cap(b); sz != 0 {
  86. b = b[:cap(b)]
  87. ptr := unsafe.Pointer(&b[0])
  88. C.je_free(ptr)
  89. atomic.AddInt64(&numBytes, -int64(sz))
  90. dallocsMu.Lock()
  91. delete(dallocs, ptr)
  92. dallocsMu.Unlock()
  93. }
  94. }
  95. func Leaks() string {
  96. if dallocs == nil {
  97. return "Leak detection disabled. Enable with 'leak' build flag."
  98. }
  99. dallocsMu.Lock()
  100. defer dallocsMu.Unlock()
  101. if len(dallocs) == 0 {
  102. return "NO leaks found."
  103. }
  104. m := make(map[string]int)
  105. for _, da := range dallocs {
  106. m[da.t] += da.sz
  107. }
  108. var buf bytes.Buffer
  109. fmt.Fprintf(&buf, "Allocations:\n")
  110. for f, sz := range m {
  111. fmt.Fprintf(&buf, "%s at file: %s\n", humanize.IBytes(uint64(sz)), f)
  112. }
  113. return buf.String()
  114. }
  115. // ReadMemStats populates stats with JE Malloc statistics.
  116. func ReadMemStats(stats *MemStats) {
  117. if stats == nil {
  118. return
  119. }
  120. // Call an epoch mallclt to refresh the stats data as mentioned in the docs.
  121. // http://jemalloc.net/jemalloc.3.html#epoch
  122. // Note: This epoch mallctl is as expensive as a malloc call. It takes up the
  123. // malloc_mutex_lock.
  124. epoch := 1
  125. sz := unsafe.Sizeof(&epoch)
  126. C.je_mallctl(
  127. (C.CString)("epoch"),
  128. unsafe.Pointer(&epoch),
  129. (*C.size_t)(unsafe.Pointer(&sz)),
  130. unsafe.Pointer(&epoch),
  131. (C.size_t)(unsafe.Sizeof(epoch)))
  132. stats.Allocated = fetchStat("stats.allocated")
  133. stats.Active = fetchStat("stats.active")
  134. stats.Resident = fetchStat("stats.resident")
  135. stats.Retained = fetchStat("stats.retained")
  136. }
  137. // fetchStat is used to read a specific attribute from je malloc stats using mallctl.
  138. func fetchStat(s string) uint64 {
  139. var out uint64
  140. sz := unsafe.Sizeof(&out)
  141. C.je_mallctl(
  142. (C.CString)(s), // Query: eg: stats.allocated, stats.resident, etc.
  143. unsafe.Pointer(&out), // Variable to store the output.
  144. (*C.size_t)(unsafe.Pointer(&sz)), // Size of the output variable.
  145. nil, // Input variable used to set a value.
  146. 0) // Size of the input variable.
  147. return out
  148. }
  149. func StatsPrint() {
  150. opts := C.CString("mdablxe")
  151. C.je_malloc_stats_print(nil, nil, opts)
  152. C.free(unsafe.Pointer(opts))
  153. }