| 1 | // Copyright 2017 The Memory Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package memory implements a memory allocator. |
| 6 | // |
| 7 | // # Build status |
| 8 | // |
| 9 | // available at https://modern-c.appspot.com/-/builder/?importpath=modernc.org%2fmemory |
| 10 | // |
| 11 | // # Changelog |
| 12 | // |
| 13 | // 2017-10-03 Added alternative, unsafe.Pointer-based API. |
| 14 | // |
| 15 | // Package memory implements a memory allocator. |
| 16 | // |
| 17 | // # Changelog |
| 18 | // |
| 19 | // 2017-10-03 Added alternative, unsafe.Pointer-based API. |
| 20 | // |
| 21 | // # Page retention |
| 22 | // |
| 23 | // Memory is acquired from the OS in 64 KiB units or, for larger |
| 24 | // allocations, in units rounded up to a power of two on 64-bit hosts. |
| 25 | // An Allocator retains empty regions for reuse instead of unmapping |
| 26 | // them as soon as their last slot is freed: each size class keeps its |
| 27 | // current carve-target page, and beyond that, retired regions of any |
| 28 | // size go into a pool bounded by 4 MiB plus the high-water mark of the |
| 29 | // live mapping. An allocation pattern that repeatedly drains a size |
| 30 | // class, or repeatedly frees and reallocates large buffers, no longer |
| 31 | // pays a mmap/munmap round trip per turnover. Use Allocator.Trim to |
| 32 | // hand the retained regions back. |
| 33 | // |
| 34 | // # Benchmarks |
| 35 | // |
| 36 | // jnml@3900x:~/src/modernc.org/memory$ date ; go version ; go test -run @ -bench . -benchmem |& tee log |
| 37 | // Mon Sep 25 16:02:02 CEST 2023 |
| 38 | // go version go1.21.1 linux/amd64 |
| 39 | // goos: linux |
| 40 | // goarch: amd64 |
| 41 | // pkg: modernc.org/memory |
| 42 | // cpu: AMD Ryzen 9 3900X 12-Core Processor |
| 43 | // BenchmarkFree16-24 123506772 9.802 ns/op 0 B/op 0 allocs/op |
| 44 | // BenchmarkFree32-24 73853230 15.08 ns/op 0 B/op 0 allocs/op |
| 45 | // BenchmarkFree64-24 43070334 25.15 ns/op 0 B/op 0 allocs/op |
| 46 | // BenchmarkCalloc16-24 59353304 18.92 ns/op 0 B/op 0 allocs/op |
| 47 | // BenchmarkCalloc32-24 39415004 29.00 ns/op 0 B/op 0 allocs/op |
| 48 | // BenchmarkCalloc64-24 35825725 32.02 ns/op 0 B/op 0 allocs/op |
| 49 | // BenchmarkGoCalloc16-24 38274313 26.99 ns/op 16 B/op 1 allocs/op |
| 50 | // BenchmarkGoCalloc32-24 44590477 33.06 ns/op 32 B/op 1 allocs/op |
| 51 | // BenchmarkGoCalloc64-24 44233016 37.20 ns/op 64 B/op 1 allocs/op |
| 52 | // BenchmarkMalloc16-24 145736911 7.720 ns/op 0 B/op 0 allocs/op |
| 53 | // BenchmarkMalloc32-24 128898334 7.887 ns/op 0 B/op 0 allocs/op |
| 54 | // BenchmarkMalloc64-24 149569483 7.994 ns/op 0 B/op 0 allocs/op |
| 55 | // BenchmarkUintptrFree16-24 117043012 9.205 ns/op 0 B/op 0 allocs/op |
| 56 | // BenchmarkUintptrFree32-24 77399617 14.20 ns/op 0 B/op 0 allocs/op |
| 57 | // BenchmarkUintptrFree64-24 48770785 25.04 ns/op 0 B/op 0 allocs/op |
| 58 | // BenchmarkUintptrCalloc16-24 79257636 15.44 ns/op 0 B/op 0 allocs/op |
| 59 | // BenchmarkUintptrCalloc32-24 49644562 23.62 ns/op 0 B/op 0 allocs/op |
| 60 | // BenchmarkUintptrCalloc64-24 39854710 28.22 ns/op 0 B/op 0 allocs/op |
| 61 | // BenchmarkUintptrMalloc16-24 252987727 4.525 ns/op 0 B/op 0 allocs/op |
| 62 | // BenchmarkUintptrMalloc32-24 241423840 4.433 ns/op 0 B/op 0 allocs/op |
| 63 | // BenchmarkUintptrMalloc64-24 256450324 4.669 ns/op 0 B/op 0 allocs/op |
| 64 | // PASS |
| 65 | // ok modernc.org/memory 93.178s |
| 66 | // jnml@3900x:~/src/modernc.org/memory$ |
| 67 | package memory // import "modernc.org/memory" |
| 68 | |
| 69 | import ( |
| 70 | "fmt" |
| 71 | "math/bits" |
| 72 | "os" |
| 73 | "unsafe" |
| 74 | ) |
| 75 | |
| 76 | const ( |
| 77 | headerSize = unsafe.Sizeof(page{}) |
| 78 | mallocAllign = 2 * unsafe.Sizeof(uintptr(0)) |
| 79 | maxSlotSize = 1 << maxSlotSizeLog |
| 80 | maxSlotSizeLog = pageSizeLog - 2 |
| 81 | pageAvail = pageSize - headerSize |
| 82 | pageMask = pageSize - 1 |
| 83 | pageSize = 1 << pageSizeLog |
| 84 | ) |
| 85 | |
| 86 | func init() { |
| 87 | if unsafe.Sizeof(page{})%mallocAllign != 0 { |
| 88 | panic("internal error") |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // if n%m != 0 { n += m-n%m }. m must be a power of 2. |
| 93 | func roundup(n, m int) int { return (n + m - 1) &^ (m - 1) } |
| 94 | |
| 95 | type node struct { |
| 96 | prev, next uintptr // *node |
| 97 | } |
| 98 | |
| 99 | type page struct { |
| 100 | brk int |
| 101 | log uint |
| 102 | size int |
| 103 | used int |
| 104 | } |
| 105 | |
| 106 | // Allocator allocates and frees memory. Its zero value is ready for use. The |
| 107 | // exported counters are updated only when build tag memory.counters is |
| 108 | // present. |
| 109 | // |
| 110 | // An Allocator retains empty regions for reuse, see Trim. |
| 111 | type Allocator struct { |
| 112 | Allocs int // # of allocs. |
| 113 | Bytes int // Asked from OS. |
| 114 | cap [64]int |
| 115 | lists [64]uintptr // *node |
| 116 | Mmaps int // Asked from OS. |
| 117 | pages [64]uintptr // *page |
| 118 | regs map[uintptr]struct{} // map[*page]struct{} |
| 119 | freed map[int][]uintptr // empty regions retained for reuse, keyed by region size |
| 120 | freedSize int // total bytes in freed |
| 121 | cold map[int]int // the bottom cold[size] regions of freed[size] are decommitted |
| 122 | live int // bytes mapped and not in freed |
| 123 | hiLive int // high-water mark of live |
| 124 | } |
| 125 | |
| 126 | // maxFreedSize returns the bound on the total bytes retained in |
| 127 | // a.freed: a fixed floor plus the high-water mark of the live mapping. |
| 128 | // The high-water mark rather than the current live size matters for |
| 129 | // large transient buffers: when one is freed, live has already shrunk |
| 130 | // by the buffer, and it is exactly the region most worth retaining. |
| 131 | func (a *Allocator) maxFreedSize() int { return 4<<20 + a.hiLive } |
| 132 | |
| 133 | // addLive adds n bytes to the live mapping size, tracking its |
| 134 | // high-water mark. |
| 135 | func (a *Allocator) addLive(n int) { |
| 136 | a.live += n |
| 137 | if a.live > a.hiLive { |
| 138 | a.hiLive = a.live |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | // canRetain reports whether a.freed has room to retain size more bytes. |
| 143 | func (a *Allocator) canRetain(size int) bool { return a.freedSize+size <= a.maxFreedSize() } |
| 144 | |
| 145 | // mmapSize returns the region size class that backs a request for size |
| 146 | // bytes: requests up to pageSize share the single pageSize class, and |
| 147 | // on 64-bit larger requests are rounded up to a power of two. The |
| 148 | // extra address space is never touched and so costs nothing, and |
| 149 | // collapsing sizes into classes makes reuse via a.freed much more |
| 150 | // likely. |
| 151 | // |
| 152 | // Classes are multiples of mmapGranularity - the granularity the platform |
| 153 | // mmap actually maps at - so the class of a request agrees with the |
| 154 | // page.size the mapping comes back with, which is what retain later keys |
| 155 | // the pool by. Rounding to anything finer describes a mapping the platform |
| 156 | // cannot make: on windows/386 a 1 MiB+1 request rounded to OS pages misses |
| 157 | // forever the 1 MiB+64 KiB region its own mapping put into the pool. |
| 158 | func mmapSize(size int) int { |
| 159 | switch { |
| 160 | case size <= pageSize && pageSize%osPageSize == 0: |
| 161 | return pageSize |
| 162 | case size > pageSize && bits.UintSize == 64: |
| 163 | return roundup(1<<bits.Len(uint(size-1)), mmapGranularity) |
| 164 | default: |
| 165 | return roundup(size, mmapGranularity) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | // slabBatch is how many pageSize regions a single mapping acquires |
| 170 | // when a pageSize region is needed and the pool is empty. |
| 171 | const slabBatch = 16 |
| 172 | |
| 173 | func (a *Allocator) mmap(size int) (uintptr /* *page */, error) { |
| 174 | size = mmapSize(size) |
| 175 | if s := a.freed[size]; len(s) != 0 { |
| 176 | p := s[len(s)-1] |
| 177 | if canDecommit { |
| 178 | if c := a.cold[size]; c >= len(s) { // popping from the decommitted prefix |
| 179 | if err := recommit(p, size); err != nil { |
| 180 | return 0, err // pool left untouched |
| 181 | } |
| 182 | |
| 183 | a.cold[size] = len(s) - 1 |
| 184 | } |
| 185 | } |
| 186 | a.freed[size] = s[:len(s)-1] |
| 187 | a.freedSize -= size |
| 188 | a.addLive(size) |
| 189 | pg := (*page)(unsafe.Pointer(p)) |
| 190 | pg.brk = 0 |
| 191 | pg.used = 0 |
| 192 | return p, nil |
| 193 | } |
| 194 | |
| 195 | // Aligning a fresh mapping to a pageSize boundary costs up to two |
| 196 | // munmap calls for the trimmed-off ends, so when a single pageSize |
| 197 | // region is needed, acquire a batch in one mapping and put the |
| 198 | // rest into the pool: three syscalls amortized over slabBatch |
| 199 | // regions instead of per region. |
| 200 | if canCarve && size == pageSize { |
| 201 | if p, n, err := mmap(slabBatch * pageSize); err == nil { |
| 202 | if n%pageSize == 0 && a.canRetain(n-pageSize) { |
| 203 | for off := pageSize; off < n; off += pageSize { |
| 204 | q := p + uintptr(off) |
| 205 | a.reg(q, pageSize) |
| 206 | a.retain(q, pageSize) |
| 207 | } |
| 208 | return a.reg(p, pageSize), nil |
| 209 | } |
| 210 | |
| 211 | if err := unmap(p, n); err != nil { |
| 212 | return 0, err |
| 213 | } |
| 214 | } |
| 215 | // Fall through and map a single region. |
| 216 | } |
| 217 | |
| 218 | p, size, err := mmap(size) |
| 219 | if err != nil { |
| 220 | return 0, err |
| 221 | } |
| 222 | |
| 223 | //TODO(jnml) The returned size may now be nearly as twice as large as we asked |
| 224 | //for. Use that extra capacity. For that we need to move the respective |
| 225 | //Allocator.cap item into the page struct so the page cap becomes dynamic. |
| 226 | // |
| 227 | // Related: This is a consequence of fixing the bigsort.test failures on |
| 228 | // linux/s390x, see: https://gitlab.com/cznic/sqlite/-/issues/207 |
| 229 | return a.reg(p, size), nil |
| 230 | } |
| 231 | |
| 232 | // reg registers the freshly mapped size-byte region at p. |
| 233 | func (a *Allocator) reg(p uintptr, size int) uintptr { |
| 234 | a.addLive(size) |
| 235 | if counters { |
| 236 | a.Mmaps++ |
| 237 | a.Bytes += size |
| 238 | } |
| 239 | if a.regs == nil { |
| 240 | a.regs = map[uintptr]struct{}{} |
| 241 | } |
| 242 | (*page)(unsafe.Pointer(p)).size = size |
| 243 | a.regs[p] = struct{}{} |
| 244 | return p |
| 245 | } |
| 246 | |
| 247 | func (a *Allocator) newPage(size int) (uintptr /* *page */, error) { |
| 248 | size += int(headerSize) |
| 249 | p, err := a.mmap(size) |
| 250 | if err != nil { |
| 251 | return 0, err |
| 252 | } |
| 253 | |
| 254 | (*page)(unsafe.Pointer(p)).log = 0 |
| 255 | return p, nil |
| 256 | } |
| 257 | |
| 258 | func (a *Allocator) newSharedPage(log uint) (uintptr /* *page */, error) { |
| 259 | if a.cap[log] == 0 { |
| 260 | a.cap[log] = int(pageAvail) / (1 << log) |
| 261 | } |
| 262 | size := int(headerSize) + a.cap[log]<<log |
| 263 | p, err := a.mmap(size) |
| 264 | if err != nil { |
| 265 | return 0, err |
| 266 | } |
| 267 | |
| 268 | a.pages[log] = p |
| 269 | (*page)(unsafe.Pointer(p)).log = log |
| 270 | return p, nil |
| 271 | } |
| 272 | |
| 273 | func (a *Allocator) unmap(p uintptr /* *page */) error { |
| 274 | delete(a.regs, p) |
| 275 | size := (*page)(unsafe.Pointer(p)).size |
| 276 | if counters { |
| 277 | a.Mmaps-- |
| 278 | a.Bytes -= size |
| 279 | } |
| 280 | return unmap(p, size) |
| 281 | } |
| 282 | |
| 283 | // release retires the empty region at p: it is retained in a.freed for |
| 284 | // reuse, unless the retained total is at its bound, in which case the |
| 285 | // region is returned to the OS. Retained regions stay in a.regs and in |
| 286 | // the counters; Trim and Close return them to the OS. |
| 287 | func (a *Allocator) release(p uintptr /* *page */) error { |
| 288 | size := (*page)(unsafe.Pointer(p)).size |
| 289 | if a.canRetain(size) { |
| 290 | a.retain(p, size) |
| 291 | return nil |
| 292 | } |
| 293 | |
| 294 | a.live -= size |
| 295 | return a.unmap(p) |
| 296 | } |
| 297 | |
| 298 | // hotBytes is how much of the retained pool stays committed per size class. |
| 299 | // 4 MiB costs nothing measurable against not decommitting at all (speedtest1 |
| 300 | // and production simulations) while returning the hoard above it. |
| 301 | const hotBytes = 4 << 20 |
| 302 | |
| 303 | // retain puts the empty size-byte region at p into a.freed. |
| 304 | func (a *Allocator) retain(p uintptr, size int) { |
| 305 | if a.freed == nil { |
| 306 | a.freed = map[int][]uintptr{} |
| 307 | } |
| 308 | a.freed[size] = append(a.freed[size], p) |
| 309 | a.freedSize += size |
| 310 | a.live -= size |
| 311 | if !canDecommit { |
| 312 | return |
| 313 | } |
| 314 | |
| 315 | // Keep the newest hotBytes worth of this class committed: those are the |
| 316 | // regions a churning workload takes straight back, where decommitting only |
| 317 | // buys a page fault. What falls out of that window is hoard - it is holding |
| 318 | // a resident set the workload has stopped using - so hand its pages back |
| 319 | // while keeping the mapping. |
| 320 | // |
| 321 | // a.cold counts the stack's already-decommitted bottom, so only a region |
| 322 | // newly falling out of the hot window pays a syscall: a pool oscillating |
| 323 | // around the boundary would otherwise re-madvise the same region on every |
| 324 | // retain. |
| 325 | hot := hotBytes / size |
| 326 | if hot < 1 { |
| 327 | hot = 1 |
| 328 | } |
| 329 | if s := a.freed[size]; len(s)-a.cold[size] > hot { |
| 330 | if a.cold == nil { |
| 331 | a.cold = map[int]int{} |
| 332 | } |
| 333 | decommit(s[a.cold[size]], size) |
| 334 | a.cold[size]++ |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // UintptrCalloc is like Calloc except it returns an uintptr. |
| 339 | func (a *Allocator) UintptrCalloc(size int) (r uintptr, err error) { |
| 340 | if trace { |
| 341 | defer func() { |
| 342 | fmt.Fprintf(os.Stderr, "Calloc(%#x) %#x, %v\n", size, r, err) |
| 343 | }() |
| 344 | } |
| 345 | if r, err = a.UintptrMalloc(size); r == 0 || err != nil { |
| 346 | return 0, err |
| 347 | } |
| 348 | b := ((*rawmem)(unsafe.Pointer(r)))[:size:size] |
| 349 | for i := range b { |
| 350 | b[i] = 0 |
| 351 | } |
| 352 | return r, nil |
| 353 | } |
| 354 | |
| 355 | // UintptrFree is like Free except its argument is an uintptr, which must have |
| 356 | // been acquired from UintptrCalloc or UintptrMalloc or UintptrRealloc. |
| 357 | func (a *Allocator) UintptrFree(p uintptr) (err error) { |
| 358 | if trace { |
| 359 | defer func() { |
| 360 | fmt.Fprintf(os.Stderr, "Free(%#x) %v\n", p, err) |
| 361 | }() |
| 362 | } |
| 363 | if p == 0 { |
| 364 | return nil |
| 365 | } |
| 366 | |
| 367 | if counters { |
| 368 | a.Allocs-- |
| 369 | } |
| 370 | pg := p &^ uintptr(pageMask) |
| 371 | log := (*page)(unsafe.Pointer(pg)).log |
| 372 | if log == 0 { |
| 373 | return a.release(pg) |
| 374 | } |
| 375 | |
| 376 | (*node)(unsafe.Pointer(p)).prev = 0 |
| 377 | (*node)(unsafe.Pointer(p)).next = a.lists[log] |
| 378 | if next := (*node)(unsafe.Pointer(p)).next; next != 0 { |
| 379 | (*node)(unsafe.Pointer(next)).prev = p |
| 380 | } |
| 381 | a.lists[log] = p |
| 382 | (*page)(unsafe.Pointer(pg)).used-- |
| 383 | if (*page)(unsafe.Pointer(pg)).used != 0 { |
| 384 | return nil |
| 385 | } |
| 386 | |
| 387 | for i := 0; i < (*page)(unsafe.Pointer(pg)).brk; i++ { |
| 388 | n := pg + headerSize + uintptr(i)<<log |
| 389 | next := (*node)(unsafe.Pointer(n)).next |
| 390 | prev := (*node)(unsafe.Pointer(n)).prev |
| 391 | switch { |
| 392 | case prev == 0: |
| 393 | a.lists[log] = next |
| 394 | if next != 0 { |
| 395 | (*node)(unsafe.Pointer(next)).prev = 0 |
| 396 | } |
| 397 | case next == 0: |
| 398 | (*node)(unsafe.Pointer(prev)).next = 0 |
| 399 | default: |
| 400 | (*node)(unsafe.Pointer(prev)).next = next |
| 401 | (*node)(unsafe.Pointer(next)).prev = prev |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | // The page is now empty. Retain it as the carve target of its size class |
| 406 | // rather than returning it to the OS, unless the class already has one. |
| 407 | // Otherwise a pattern that repeatedly drains the class pays a mmap/munmap |
| 408 | // round trip per turnover. Trim releases the pages retained this way. |
| 409 | if a.pages[log] == 0 || a.pages[log] == pg { |
| 410 | (*page)(unsafe.Pointer(pg)).brk = 0 |
| 411 | a.pages[log] = pg |
| 412 | return nil |
| 413 | } |
| 414 | |
| 415 | return a.release(pg) |
| 416 | } |
| 417 | |
| 418 | // UintptrMalloc is like Malloc except it returns an uinptr. |
| 419 | func (a *Allocator) UintptrMalloc(size int) (r uintptr, err error) { |
| 420 | if trace { |
| 421 | defer func() { |
| 422 | fmt.Fprintf(os.Stderr, "Malloc(%#x) %#x, %v\n", size, r, err) |
| 423 | }() |
| 424 | } |
| 425 | if size < 0 { |
| 426 | panic("invalid malloc size") |
| 427 | } |
| 428 | |
| 429 | if size == 0 { |
| 430 | return 0, nil |
| 431 | } |
| 432 | if size > int(^uint(0)>>1)-int(headerSize) { |
| 433 | return 0, fmt.Errorf("memory: allocation size %d is too large", size) |
| 434 | } |
| 435 | |
| 436 | if counters { |
| 437 | a.Allocs++ |
| 438 | } |
| 439 | log := uint(bits.Len(uint((size+int(mallocAllign)-1)&^int(mallocAllign-1) - 1))) |
| 440 | if log > maxSlotSizeLog { |
| 441 | p, err := a.newPage(size) |
| 442 | if err != nil { |
| 443 | return 0, err |
| 444 | } |
| 445 | |
| 446 | return p + headerSize, nil |
| 447 | } |
| 448 | |
| 449 | if a.lists[log] == 0 && a.pages[log] == 0 { |
| 450 | if _, err := a.newSharedPage(log); err != nil { |
| 451 | return 0, err |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | if p := a.pages[log]; p != 0 { |
| 456 | (*page)(unsafe.Pointer(p)).used++ |
| 457 | (*page)(unsafe.Pointer(p)).brk++ |
| 458 | if (*page)(unsafe.Pointer(p)).brk == a.cap[log] { |
| 459 | a.pages[log] = 0 |
| 460 | } |
| 461 | return p + headerSize + uintptr((*page)(unsafe.Pointer(p)).brk-1)<<log, nil |
| 462 | } |
| 463 | |
| 464 | n := a.lists[log] |
| 465 | p := n &^ uintptr(pageMask) |
| 466 | a.lists[log] = (*node)(unsafe.Pointer(n)).next |
| 467 | if next := (*node)(unsafe.Pointer(n)).next; next != 0 { |
| 468 | (*node)(unsafe.Pointer(next)).prev = 0 |
| 469 | } |
| 470 | (*page)(unsafe.Pointer(p)).used++ |
| 471 | return n, nil |
| 472 | } |
| 473 | |
| 474 | // UintptrRealloc is like Realloc except its first argument is an uintptr, |
| 475 | // which must have been returned from UintptrCalloc, UintptrMalloc or |
| 476 | // UintptrRealloc. |
| 477 | func (a *Allocator) UintptrRealloc(p uintptr, size int) (r uintptr, err error) { |
| 478 | if trace { |
| 479 | defer func() { |
| 480 | fmt.Fprintf(os.Stderr, "UnsafeRealloc(%#x, %#x) %#x, %v\n", p, size, r, err) |
| 481 | }() |
| 482 | } |
| 483 | switch { |
| 484 | case p == 0: |
| 485 | return a.UintptrMalloc(size) |
| 486 | case size == 0 && p != 0: |
| 487 | return 0, a.UintptrFree(p) |
| 488 | } |
| 489 | |
| 490 | us := UintptrUsableSize(p) |
| 491 | if us >= size { |
| 492 | return p, nil |
| 493 | } |
| 494 | |
| 495 | if r, err = a.UintptrMalloc(size); err != nil { |
| 496 | return 0, err |
| 497 | } |
| 498 | |
| 499 | if us < size { |
| 500 | size = us |
| 501 | } |
| 502 | copy((*rawmem)(unsafe.Pointer(r))[:size:size], (*rawmem)(unsafe.Pointer(p))[:size:size]) |
| 503 | return r, a.UintptrFree(p) |
| 504 | } |
| 505 | |
| 506 | // UintptrUsableSize is like UsableSize except its argument is an uintptr, |
| 507 | // which must have been returned from UintptrCalloc, UintptrMalloc or |
| 508 | // UintptrRealloc. |
| 509 | func UintptrUsableSize(p uintptr) (r int) { |
| 510 | if trace { |
| 511 | defer func() { |
| 512 | fmt.Fprintf(os.Stderr, "UsableSize(%#x) %#x\n", p, r) |
| 513 | }() |
| 514 | } |
| 515 | if p == 0 { |
| 516 | return 0 |
| 517 | } |
| 518 | |
| 519 | return usableSize(p) |
| 520 | } |
| 521 | |
| 522 | func usableSize(p uintptr) (r int) { |
| 523 | pg := p &^ uintptr(pageMask) |
| 524 | if log := (*page)(unsafe.Pointer(pg)).log; log != 0 { |
| 525 | return 1 << log |
| 526 | } |
| 527 | |
| 528 | return (*page)(unsafe.Pointer(pg)).size - int(headerSize) |
| 529 | } |
| 530 | |
| 531 | // Calloc is like Malloc except the allocated memory is zeroed. |
| 532 | func (a *Allocator) Calloc(size int) (r []byte, err error) { |
| 533 | p, err := a.UintptrCalloc(size) |
| 534 | if err != nil { |
| 535 | return nil, err |
| 536 | } |
| 537 | |
| 538 | return (*rawmem)(unsafe.Pointer(p))[:size:usableSize(p)], nil |
| 539 | } |
| 540 | |
| 541 | // Close releases all OS resources used by a and sets it to its zero value. |
| 542 | // |
| 543 | // It's not necessary to Close the Allocator when exiting a process. |
| 544 | func (a *Allocator) Close() (err error) { |
| 545 | for p := range a.regs { |
| 546 | if e := a.unmap(p); e != nil && err == nil { |
| 547 | err = e |
| 548 | } |
| 549 | } |
| 550 | *a = Allocator{} |
| 551 | return err |
| 552 | } |
| 553 | |
| 554 | // Free deallocates memory (as in C.free). The argument of Free must have been |
| 555 | // acquired from Calloc or Malloc or Realloc. |
| 556 | func (a *Allocator) Free(b []byte) (err error) { |
| 557 | if b = b[:cap(b)]; len(b) == 0 { |
| 558 | return nil |
| 559 | } |
| 560 | |
| 561 | return a.UintptrFree(uintptr(unsafe.Pointer(&b[0]))) |
| 562 | } |
| 563 | |
| 564 | // Malloc allocates size bytes and returns a byte slice of the allocated |
| 565 | // memory. The memory is not initialized. Malloc panics for size < 0 and |
| 566 | // returns (nil, nil) for zero size. |
| 567 | // |
| 568 | // It's ok to reslice the returned slice but the result of appending to it |
| 569 | // cannot be passed to Free or Realloc as it may refer to a different backing |
| 570 | // array afterwards. |
| 571 | func (a *Allocator) Malloc(size int) (r []byte, err error) { |
| 572 | p, err := a.UintptrMalloc(size) |
| 573 | if p == 0 || err != nil { |
| 574 | return nil, err |
| 575 | } |
| 576 | |
| 577 | return (*rawmem)(unsafe.Pointer(p))[:size:usableSize(p)], nil |
| 578 | } |
| 579 | |
| 580 | // Realloc changes the size of the backing array of b to size bytes or returns |
| 581 | // an error, if any. The contents will be unchanged in the range from the |
| 582 | // start of the region up to the minimum of the old and new sizes. If the |
| 583 | // new size is larger than the old size, the added memory will not be |
| 584 | // initialized. If b's backing array is of zero size, then the call is |
| 585 | // equivalent to Malloc(size), for all values of size; if size is equal to |
| 586 | // zero, and b's backing array is not of zero size, then the call is equivalent |
| 587 | // to Free(b). Unless b's backing array is of zero size, it must have been |
| 588 | // returned by an earlier call to Malloc, Calloc or Realloc. If the area |
| 589 | // pointed to was moved, a Free(b) is done. |
| 590 | func (a *Allocator) Realloc(b []byte, size int) (r []byte, err error) { |
| 591 | var p uintptr |
| 592 | if b = b[:cap(b)]; len(b) != 0 { |
| 593 | p = uintptr(unsafe.Pointer(&b[0])) |
| 594 | } |
| 595 | if p, err = a.UintptrRealloc(p, size); p == 0 || err != nil { |
| 596 | return nil, err |
| 597 | } |
| 598 | |
| 599 | return (*rawmem)(unsafe.Pointer(p))[:size:usableSize(p)], nil |
| 600 | } |
| 601 | |
| 602 | // Trim returns to the OS the empty regions a retains for reuse: each |
| 603 | // size class's empty carve-target page and the bounded pool of retired |
| 604 | // regions. Pages still having live allocations are not affected and a |
| 605 | // stays ready for use. |
| 606 | // |
| 607 | // Trim is never necessary for correctness. It trades a smaller resident set |
| 608 | // now for the cost of mapping those pages again later. |
| 609 | func (a *Allocator) Trim() (err error) { |
| 610 | if trace { |
| 611 | defer func() { |
| 612 | fmt.Fprintf(os.Stderr, "Trim() %v\n", err) |
| 613 | }() |
| 614 | } |
| 615 | for log := range a.pages { |
| 616 | pg := a.pages[log] |
| 617 | if pg == 0 || (*page)(unsafe.Pointer(pg)).used != 0 { |
| 618 | continue |
| 619 | } |
| 620 | |
| 621 | a.pages[log] = 0 |
| 622 | a.live -= (*page)(unsafe.Pointer(pg)).size |
| 623 | if e := a.unmap(pg); e != nil && err == nil { |
| 624 | err = e |
| 625 | } |
| 626 | } |
| 627 | for _, s := range a.freed { |
| 628 | for _, pg := range s { |
| 629 | if e := a.unmap(pg); e != nil && err == nil { |
| 630 | err = e |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | a.freed = nil |
| 635 | a.freedSize = 0 |
| 636 | a.cold = nil |
| 637 | return err |
| 638 | } |
| 639 | |
| 640 | // UsableSize reports the size of the memory block allocated at p, which must |
| 641 | // point to the first byte of a slice returned from Calloc, Malloc or Realloc. |
| 642 | // The allocated memory block size can be larger than the size originally |
| 643 | // requested from Calloc, Malloc or Realloc. |
| 644 | func UsableSize(p *byte) (r int) { return UintptrUsableSize(uintptr(unsafe.Pointer(p))) } |
| 645 | |
| 646 | // UnsafeCalloc is like Calloc except it returns an unsafe.Pointer. |
| 647 | func (a *Allocator) UnsafeCalloc(size int) (r unsafe.Pointer, err error) { |
| 648 | p, err := a.UintptrCalloc(size) |
| 649 | if err != nil { |
| 650 | return nil, err |
| 651 | } |
| 652 | |
| 653 | return unsafe.Pointer(p), nil |
| 654 | } |
| 655 | |
| 656 | // UnsafeFree is like Free except its argument is an unsafe.Pointer, which must |
| 657 | // have been acquired from UnsafeCalloc or UnsafeMalloc or UnsafeRealloc. |
| 658 | func (a *Allocator) UnsafeFree(p unsafe.Pointer) (err error) { return a.UintptrFree(uintptr(p)) } |
| 659 | |
| 660 | // UnsafeMalloc is like Malloc except it returns an unsafe.Pointer. |
| 661 | func (a *Allocator) UnsafeMalloc(size int) (r unsafe.Pointer, err error) { |
| 662 | p, err := a.UintptrMalloc(size) |
| 663 | if err != nil { |
| 664 | return nil, err |
| 665 | } |
| 666 | |
| 667 | return unsafe.Pointer(p), nil |
| 668 | } |
| 669 | |
| 670 | // UnsafeRealloc is like Realloc except its first argument is an |
| 671 | // unsafe.Pointer, which must have been returned from UnsafeCalloc, |
| 672 | // UnsafeMalloc or UnsafeRealloc. |
| 673 | func (a *Allocator) UnsafeRealloc(p unsafe.Pointer, size int) (r unsafe.Pointer, err error) { |
| 674 | q, err := a.UintptrRealloc(uintptr(p), size) |
| 675 | if err != nil { |
| 676 | return nil, err |
| 677 | } |
| 678 | |
| 679 | return unsafe.Pointer(q), nil |
| 680 | } |
| 681 | |
| 682 | // UnsafeUsableSize is like UsableSize except its argument is an |
| 683 | // unsafe.Pointer, which must have been returned from UnsafeCalloc, |
| 684 | // UnsafeMalloc or UnsafeRealloc. |
| 685 | func UnsafeUsableSize(p unsafe.Pointer) (r int) { return UintptrUsableSize(uintptr(p)) } |