Source file src/runtime/malloc.go
1 // Copyright 2014 The Go 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 // Memory allocator. 6 // 7 // This was originally based on tcmalloc, but has diverged quite a bit. 8 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html 9 10 // The main allocator works in runs of pages. 11 // Small allocation sizes (up to and including 32 kB) are 12 // rounded to one of about 70 size classes, each of which 13 // has its own free set of objects of exactly that size. 14 // Any free page of memory can be split into a set of objects 15 // of one size class, which are then managed using a free bitmap. 16 // 17 // The allocator's data structures are: 18 // 19 // fixalloc: a free-list allocator for fixed-size off-heap objects, 20 // used to manage storage used by the allocator. 21 // mheap: the malloc heap, managed at page (8192-byte) granularity. 22 // mspan: a run of in-use pages managed by the mheap. 23 // mcentral: collects all spans of a given size class. 24 // mcache: a per-P cache of mspans with free space. 25 // mstats: allocation statistics. 26 // 27 // Allocating a small object proceeds up a hierarchy of caches: 28 // 29 // 1. Round the size up to one of the small size classes 30 // and look in the corresponding mspan in this P's mcache. 31 // Scan the mspan's free bitmap to find a free slot. 32 // If there is a free slot, allocate it. 33 // This can all be done without acquiring a lock. 34 // 35 // 2. If the mspan has no free slots, obtain a new mspan 36 // from the mcentral's list of mspans of the required size 37 // class that have free space. 38 // Obtaining a whole span amortizes the cost of locking 39 // the mcentral. 40 // 41 // 3. If the mcentral's mspan list is empty, obtain a run 42 // of pages from the mheap to use for the mspan. 43 // 44 // 4. If the mheap is empty or has no page runs large enough, 45 // allocate a new group of pages (at least 1MB) from the 46 // operating system. Allocating a large run of pages 47 // amortizes the cost of talking to the operating system. 48 // 49 // Sweeping an mspan and freeing objects on it proceeds up a similar 50 // hierarchy: 51 // 52 // 1. If the mspan is being swept in response to allocation, it 53 // is returned to the mcache to satisfy the allocation. 54 // 55 // 2. Otherwise, if the mspan still has allocated objects in it, 56 // it is placed on the mcentral free list for the mspan's size 57 // class. 58 // 59 // 3. Otherwise, if all objects in the mspan are free, the mspan's 60 // pages are returned to the mheap and the mspan is now dead. 61 // 62 // Allocating and freeing a large object uses the mheap 63 // directly, bypassing the mcache and mcentral. 64 // 65 // If mspan.needzero is false, then free object slots in the mspan are 66 // already zeroed. Otherwise if needzero is true, objects are zeroed as 67 // they are allocated. There are various benefits to delaying zeroing 68 // this way: 69 // 70 // 1. Stack frame allocation can avoid zeroing altogether. 71 // 72 // 2. It exhibits better temporal locality, since the program is 73 // probably about to write to the memory. 74 // 75 // 3. We don't zero pages that never get reused. 76 77 // Virtual memory layout 78 // 79 // The heap consists of a set of arenas, which are 64MB on 64-bit and 80 // 4MB on 32-bit (heapArenaBytes). Each arena's start address is also 81 // aligned to the arena size. 82 // 83 // Each arena has an associated heapArena object that stores the 84 // metadata for that arena: the heap bitmap for all words in the arena 85 // and the span map for all pages in the arena. heapArena objects are 86 // themselves allocated off-heap. 87 // 88 // Since arenas are aligned, the address space can be viewed as a 89 // series of arena frames. The arena map (mheap_.arenas) maps from 90 // arena frame number to *heapArena, or nil for parts of the address 91 // space not backed by the Go heap. The arena map is structured as a 92 // two-level array consisting of a "L1" arena map and many "L2" arena 93 // maps; however, since arenas are large, on many architectures, the 94 // arena map consists of a single, large L2 map. 95 // 96 // The arena map covers the entire possible address space, allowing 97 // the Go heap to use any part of the address space. The allocator 98 // attempts to keep arenas contiguous so that large spans (and hence 99 // large objects) can cross arenas. 100 101 package runtime 102 103 import ( 104 "internal/goarch" 105 "internal/goos" 106 "internal/runtime/atomic" 107 "internal/runtime/math" 108 "internal/runtime/sys" 109 "unsafe" 110 ) 111 112 const ( 113 maxTinySize = _TinySize 114 tinySizeClass = _TinySizeClass 115 maxSmallSize = _MaxSmallSize 116 117 pageShift = _PageShift 118 pageSize = _PageSize 119 120 _PageSize = 1 << _PageShift 121 _PageMask = _PageSize - 1 122 123 // _64bit = 1 on 64-bit systems, 0 on 32-bit systems 124 _64bit = 1 << (^uintptr(0) >> 63) / 2 125 126 // Tiny allocator parameters, see "Tiny allocator" comment in malloc.go. 127 _TinySize = 16 128 _TinySizeClass = int8(2) 129 130 _FixAllocChunk = 16 << 10 // Chunk size for FixAlloc 131 132 // Per-P, per order stack segment cache size. 133 _StackCacheSize = 32 * 1024 134 135 // Number of orders that get caching. Order 0 is FixedStack 136 // and each successive order is twice as large. 137 // We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks 138 // will be allocated directly. 139 // Since FixedStack is different on different systems, we 140 // must vary NumStackOrders to keep the same maximum cached size. 141 // OS | FixedStack | NumStackOrders 142 // -----------------+------------+--------------- 143 // linux/darwin/bsd | 2KB | 4 144 // windows/32 | 4KB | 3 145 // windows/64 | 8KB | 2 146 // plan9 | 4KB | 3 147 _NumStackOrders = 4 - goarch.PtrSize/4*goos.IsWindows - 1*goos.IsPlan9 148 149 // heapAddrBits is the number of bits in a heap address. On 150 // amd64, addresses are sign-extended beyond heapAddrBits. On 151 // other arches, they are zero-extended. 152 // 153 // On most 64-bit platforms, we limit this to 48 bits based on a 154 // combination of hardware and OS limitations. 155 // 156 // amd64 hardware limits addresses to 48 bits, sign-extended 157 // to 64 bits. Addresses where the top 16 bits are not either 158 // all 0 or all 1 are "non-canonical" and invalid. Because of 159 // these "negative" addresses, we offset addresses by 1<<47 160 // (arenaBaseOffset) on amd64 before computing indexes into 161 // the heap arenas index. In 2017, amd64 hardware added 162 // support for 57 bit addresses; however, currently only Linux 163 // supports this extension and the kernel will never choose an 164 // address above 1<<47 unless mmap is called with a hint 165 // address above 1<<47 (which we never do). 166 // 167 // arm64 hardware (as of ARMv8) limits user addresses to 48 168 // bits, in the range [0, 1<<48). 169 // 170 // ppc64, mips64, and s390x support arbitrary 64 bit addresses 171 // in hardware. On Linux, Go leans on stricter OS limits. Based 172 // on Linux's processor.h, the user address space is limited as 173 // follows on 64-bit architectures: 174 // 175 // Architecture Name Maximum Value (exclusive) 176 // --------------------------------------------------------------------- 177 // amd64 TASK_SIZE_MAX 0x007ffffffff000 (47 bit addresses) 178 // arm64 TASK_SIZE_64 0x01000000000000 (48 bit addresses) 179 // ppc64{,le} TASK_SIZE_USER64 0x00400000000000 (46 bit addresses) 180 // mips64{,le} TASK_SIZE64 0x00010000000000 (40 bit addresses) 181 // s390x TASK_SIZE 1<<64 (64 bit addresses) 182 // 183 // These limits may increase over time, but are currently at 184 // most 48 bits except on s390x. On all architectures, Linux 185 // starts placing mmap'd regions at addresses that are 186 // significantly below 48 bits, so even if it's possible to 187 // exceed Go's 48 bit limit, it's extremely unlikely in 188 // practice. 189 // 190 // On 32-bit platforms, we accept the full 32-bit address 191 // space because doing so is cheap. 192 // mips32 only has access to the low 2GB of virtual memory, so 193 // we further limit it to 31 bits. 194 // 195 // On ios/arm64, although 64-bit pointers are presumably 196 // available, pointers are truncated to 33 bits in iOS <14. 197 // Furthermore, only the top 4 GiB of the address space are 198 // actually available to the application. In iOS >=14, more 199 // of the address space is available, and the OS can now 200 // provide addresses outside of those 33 bits. Pick 40 bits 201 // as a reasonable balance between address space usage by the 202 // page allocator, and flexibility for what mmap'd regions 203 // we'll accept for the heap. We can't just move to the full 204 // 48 bits because this uses too much address space for older 205 // iOS versions. 206 // TODO(mknyszek): Once iOS <14 is deprecated, promote ios/arm64 207 // to a 48-bit address space like every other arm64 platform. 208 // 209 // WebAssembly currently has a limit of 4GB linear memory. 210 heapAddrBits = (_64bit*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64))*48 + (1-_64bit+goarch.IsWasm)*(32-(goarch.IsMips+goarch.IsMipsle)) + 40*goos.IsIos*goarch.IsArm64 211 212 // maxAlloc is the maximum size of an allocation. On 64-bit, 213 // it's theoretically possible to allocate 1<<heapAddrBits bytes. On 214 // 32-bit, however, this is one less than 1<<32 because the 215 // number of bytes in the address space doesn't actually fit 216 // in a uintptr. 217 maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1 218 219 // The number of bits in a heap address, the size of heap 220 // arenas, and the L1 and L2 arena map sizes are related by 221 // 222 // (1 << addr bits) = arena size * L1 entries * L2 entries 223 // 224 // Currently, we balance these as follows: 225 // 226 // Platform Addr bits Arena size L1 entries L2 entries 227 // -------------- --------- ---------- ---------- ----------- 228 // */64-bit 48 64MB 1 4M (32MB) 229 // windows/64-bit 48 4MB 64 1M (8MB) 230 // ios/arm64 40 4MB 1 256K (2MB) 231 // */32-bit 32 4MB 1 1024 (4KB) 232 // */mips(le) 31 4MB 1 512 (2KB) 233 234 // heapArenaBytes is the size of a heap arena. The heap 235 // consists of mappings of size heapArenaBytes, aligned to 236 // heapArenaBytes. The initial heap mapping is one arena. 237 // 238 // This is currently 64MB on 64-bit non-Windows and 4MB on 239 // 32-bit and on Windows. We use smaller arenas on Windows 240 // because all committed memory is charged to the process, 241 // even if it's not touched. Hence, for processes with small 242 // heaps, the mapped arena space needs to be commensurate. 243 // This is particularly important with the race detector, 244 // since it significantly amplifies the cost of committed 245 // memory. 246 heapArenaBytes = 1 << logHeapArenaBytes 247 248 heapArenaWords = heapArenaBytes / goarch.PtrSize 249 250 // logHeapArenaBytes is log_2 of heapArenaBytes. For clarity, 251 // prefer using heapArenaBytes where possible (we need the 252 // constant to compute some other constants). 253 logHeapArenaBytes = (6+20)*(_64bit*(1-goos.IsWindows)*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64)) + (2+20)*(_64bit*goos.IsWindows) + (2+20)*(1-_64bit) + (2+20)*goarch.IsWasm + (2+20)*goos.IsIos*goarch.IsArm64 254 255 // heapArenaBitmapWords is the size of each heap arena's bitmap in uintptrs. 256 heapArenaBitmapWords = heapArenaWords / (8 * goarch.PtrSize) 257 258 pagesPerArena = heapArenaBytes / pageSize 259 260 // arenaL1Bits is the number of bits of the arena number 261 // covered by the first level arena map. 262 // 263 // This number should be small, since the first level arena 264 // map requires PtrSize*(1<<arenaL1Bits) of space in the 265 // binary's BSS. It can be zero, in which case the first level 266 // index is effectively unused. There is a performance benefit 267 // to this, since the generated code can be more efficient, 268 // but comes at the cost of having a large L2 mapping. 269 // 270 // We use the L1 map on 64-bit Windows because the arena size 271 // is small, but the address space is still 48 bits, and 272 // there's a high cost to having a large L2. 273 arenaL1Bits = 6 * (_64bit * goos.IsWindows) 274 275 // arenaL2Bits is the number of bits of the arena number 276 // covered by the second level arena index. 277 // 278 // The size of each arena map allocation is proportional to 279 // 1<<arenaL2Bits, so it's important that this not be too 280 // large. 48 bits leads to 32MB arena index allocations, which 281 // is about the practical threshold. 282 arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits 283 284 // arenaL1Shift is the number of bits to shift an arena frame 285 // number by to compute an index into the first level arena map. 286 arenaL1Shift = arenaL2Bits 287 288 // arenaBits is the total bits in a combined arena map index. 289 // This is split between the index into the L1 arena map and 290 // the L2 arena map. 291 arenaBits = arenaL1Bits + arenaL2Bits 292 293 // arenaBaseOffset is the pointer value that corresponds to 294 // index 0 in the heap arena map. 295 // 296 // On amd64, the address space is 48 bits, sign extended to 64 297 // bits. This offset lets us handle "negative" addresses (or 298 // high addresses if viewed as unsigned). 299 // 300 // On aix/ppc64, this offset allows to keep the heapAddrBits to 301 // 48. Otherwise, it would be 60 in order to handle mmap addresses 302 // (in range 0x0a00000000000000 - 0x0afffffffffffff). But in this 303 // case, the memory reserved in (s *pageAlloc).init for chunks 304 // is causing important slowdowns. 305 // 306 // On other platforms, the user address space is contiguous 307 // and starts at 0, so no offset is necessary. 308 arenaBaseOffset = 0xffff800000000000*goarch.IsAmd64 + 0x0a00000000000000*goos.IsAix 309 // A typed version of this constant that will make it into DWARF (for viewcore). 310 arenaBaseOffsetUintptr = uintptr(arenaBaseOffset) 311 312 // Max number of threads to run garbage collection. 313 // 2, 3, and 4 are all plausible maximums depending 314 // on the hardware details of the machine. The garbage 315 // collector scales well to 32 cpus. 316 _MaxGcproc = 32 317 318 // minLegalPointer is the smallest possible legal pointer. 319 // This is the smallest possible architectural page size, 320 // since we assume that the first page is never mapped. 321 // 322 // This should agree with minZeroPage in the compiler. 323 minLegalPointer uintptr = 4096 324 325 // minHeapForMetadataHugePages sets a threshold on when certain kinds of 326 // heap metadata, currently the arenas map L2 entries and page alloc bitmap 327 // mappings, are allowed to be backed by huge pages. If the heap goal ever 328 // exceeds this threshold, then huge pages are enabled. 329 // 330 // These numbers are chosen with the assumption that huge pages are on the 331 // order of a few MiB in size. 332 // 333 // The kind of metadata this applies to has a very low overhead when compared 334 // to address space used, but their constant overheads for small heaps would 335 // be very high if they were to be backed by huge pages (e.g. a few MiB makes 336 // a huge difference for an 8 MiB heap, but barely any difference for a 1 GiB 337 // heap). The benefit of huge pages is also not worth it for small heaps, 338 // because only a very, very small part of the metadata is used for small heaps. 339 // 340 // N.B. If the heap goal exceeds the threshold then shrinks to a very small size 341 // again, then huge pages will still be enabled for this mapping. The reason is that 342 // there's no point unless we're also returning the physical memory for these 343 // metadata mappings back to the OS. That would be quite complex to do in general 344 // as the heap is likely fragmented after a reduction in heap size. 345 minHeapForMetadataHugePages = 1 << 30 346 ) 347 348 // physPageSize is the size in bytes of the OS's physical pages. 349 // Mapping and unmapping operations must be done at multiples of 350 // physPageSize. 351 // 352 // This must be set by the OS init code (typically in osinit) before 353 // mallocinit. 354 var physPageSize uintptr 355 356 // physHugePageSize is the size in bytes of the OS's default physical huge 357 // page size whose allocation is opaque to the application. It is assumed 358 // and verified to be a power of two. 359 // 360 // If set, this must be set by the OS init code (typically in osinit) before 361 // mallocinit. However, setting it at all is optional, and leaving the default 362 // value is always safe (though potentially less efficient). 363 // 364 // Since physHugePageSize is always assumed to be a power of two, 365 // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift. 366 // The purpose of physHugePageShift is to avoid doing divisions in 367 // performance critical functions. 368 var ( 369 physHugePageSize uintptr 370 physHugePageShift uint 371 ) 372 373 func mallocinit() { 374 if class_to_size[_TinySizeClass] != _TinySize { 375 throw("bad TinySizeClass") 376 } 377 378 if heapArenaBitmapWords&(heapArenaBitmapWords-1) != 0 { 379 // heapBits expects modular arithmetic on bitmap 380 // addresses to work. 381 throw("heapArenaBitmapWords not a power of 2") 382 } 383 384 // Check physPageSize. 385 if physPageSize == 0 { 386 // The OS init code failed to fetch the physical page size. 387 throw("failed to get system page size") 388 } 389 if physPageSize > maxPhysPageSize { 390 print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n") 391 throw("bad system page size") 392 } 393 if physPageSize < minPhysPageSize { 394 print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n") 395 throw("bad system page size") 396 } 397 if physPageSize&(physPageSize-1) != 0 { 398 print("system page size (", physPageSize, ") must be a power of 2\n") 399 throw("bad system page size") 400 } 401 if physHugePageSize&(physHugePageSize-1) != 0 { 402 print("system huge page size (", physHugePageSize, ") must be a power of 2\n") 403 throw("bad system huge page size") 404 } 405 if physHugePageSize > maxPhysHugePageSize { 406 // physHugePageSize is greater than the maximum supported huge page size. 407 // Don't throw here, like in the other cases, since a system configured 408 // in this way isn't wrong, we just don't have the code to support them. 409 // Instead, silently set the huge page size to zero. 410 physHugePageSize = 0 411 } 412 if physHugePageSize != 0 { 413 // Since physHugePageSize is a power of 2, it suffices to increase 414 // physHugePageShift until 1<<physHugePageShift == physHugePageSize. 415 for 1<<physHugePageShift != physHugePageSize { 416 physHugePageShift++ 417 } 418 } 419 if pagesPerArena%pagesPerSpanRoot != 0 { 420 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerSpanRoot (", pagesPerSpanRoot, ")\n") 421 throw("bad pagesPerSpanRoot") 422 } 423 if pagesPerArena%pagesPerReclaimerChunk != 0 { 424 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerReclaimerChunk (", pagesPerReclaimerChunk, ")\n") 425 throw("bad pagesPerReclaimerChunk") 426 } 427 // Check that the minimum size (exclusive) for a malloc header is also 428 // a size class boundary. This is important to making sure checks align 429 // across different parts of the runtime. 430 // 431 // While we're here, also check to make sure all these size classes' 432 // span sizes are one page. Some code relies on this. 433 minSizeForMallocHeaderIsSizeClass := false 434 sizeClassesUpToMinSizeForMallocHeaderAreOnePage := true 435 for i := 0; i < len(class_to_size); i++ { 436 if class_to_allocnpages[i] > 1 { 437 sizeClassesUpToMinSizeForMallocHeaderAreOnePage = false 438 } 439 if minSizeForMallocHeader == uintptr(class_to_size[i]) { 440 minSizeForMallocHeaderIsSizeClass = true 441 break 442 } 443 } 444 if !minSizeForMallocHeaderIsSizeClass { 445 throw("min size of malloc header is not a size class boundary") 446 } 447 if !sizeClassesUpToMinSizeForMallocHeaderAreOnePage { 448 throw("expected all size classes up to min size for malloc header to fit in one-page spans") 449 } 450 // Check that the pointer bitmap for all small sizes without a malloc header 451 // fits in a word. 452 if minSizeForMallocHeader/goarch.PtrSize > 8*goarch.PtrSize { 453 throw("max pointer/scan bitmap size for headerless objects is too large") 454 } 455 456 if minTagBits > taggedPointerBits { 457 throw("taggedPointerBits too small") 458 } 459 460 // Initialize the heap. 461 mheap_.init() 462 mcache0 = allocmcache() 463 lockInit(&gcBitsArenas.lock, lockRankGcBitsArenas) 464 lockInit(&profInsertLock, lockRankProfInsert) 465 lockInit(&profBlockLock, lockRankProfBlock) 466 lockInit(&profMemActiveLock, lockRankProfMemActive) 467 for i := range profMemFutureLock { 468 lockInit(&profMemFutureLock[i], lockRankProfMemFuture) 469 } 470 lockInit(&globalAlloc.mutex, lockRankGlobalAlloc) 471 472 // Create initial arena growth hints. 473 if isSbrkPlatform { 474 // Don't generate hints on sbrk platforms. We can 475 // only grow the break sequentially. 476 } else if goarch.PtrSize == 8 { 477 // On a 64-bit machine, we pick the following hints 478 // because: 479 // 480 // 1. Starting from the middle of the address space 481 // makes it easier to grow out a contiguous range 482 // without running in to some other mapping. 483 // 484 // 2. This makes Go heap addresses more easily 485 // recognizable when debugging. 486 // 487 // 3. Stack scanning in gccgo is still conservative, 488 // so it's important that addresses be distinguishable 489 // from other data. 490 // 491 // Starting at 0x00c0 means that the valid memory addresses 492 // will begin 0x00c0, 0x00c1, ... 493 // In little-endian, that's c0 00, c1 00, ... None of those are valid 494 // UTF-8 sequences, and they are otherwise as far away from 495 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0 496 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors 497 // on OS X during thread allocations. 0x00c0 causes conflicts with 498 // AddressSanitizer which reserves all memory up to 0x0100. 499 // These choices reduce the odds of a conservative garbage collector 500 // not collecting memory because some non-pointer block of memory 501 // had a bit pattern that matched a memory address. 502 // 503 // However, on arm64, we ignore all this advice above and slam the 504 // allocation at 0x40 << 32 because when using 4k pages with 3-level 505 // translation buffers, the user address space is limited to 39 bits 506 // On ios/arm64, the address space is even smaller. 507 // 508 // On AIX, mmaps starts at 0x0A00000000000000 for 64-bit. 509 // processes. 510 // 511 // Space mapped for user arenas comes immediately after the range 512 // originally reserved for the regular heap when race mode is not 513 // enabled because user arena chunks can never be used for regular heap 514 // allocations and we want to avoid fragmenting the address space. 515 // 516 // In race mode we have no choice but to just use the same hints because 517 // the race detector requires that the heap be mapped contiguously. 518 for i := 0x7f; i >= 0; i-- { 519 var p uintptr 520 switch { 521 case raceenabled: 522 // The TSAN runtime requires the heap 523 // to be in the range [0x00c000000000, 524 // 0x00e000000000). 525 p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32) 526 if p >= uintptrMask&0x00e000000000 { 527 continue 528 } 529 case GOARCH == "arm64" && GOOS == "ios": 530 p = uintptr(i)<<40 | uintptrMask&(0x0013<<28) 531 case GOARCH == "arm64": 532 p = uintptr(i)<<40 | uintptrMask&(0x0040<<32) 533 case GOOS == "aix": 534 if i == 0 { 535 // We don't use addresses directly after 0x0A00000000000000 536 // to avoid collisions with others mmaps done by non-go programs. 537 continue 538 } 539 p = uintptr(i)<<40 | uintptrMask&(0xa0<<52) 540 default: 541 p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32) 542 } 543 // Switch to generating hints for user arenas if we've gone 544 // through about half the hints. In race mode, take only about 545 // a quarter; we don't have very much space to work with. 546 hintList := &mheap_.arenaHints 547 if (!raceenabled && i > 0x3f) || (raceenabled && i > 0x5f) { 548 hintList = &mheap_.userArena.arenaHints 549 } 550 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc()) 551 hint.addr = p 552 hint.next, *hintList = *hintList, hint 553 } 554 } else { 555 // On a 32-bit machine, we're much more concerned 556 // about keeping the usable heap contiguous. 557 // Hence: 558 // 559 // 1. We reserve space for all heapArenas up front so 560 // they don't get interleaved with the heap. They're 561 // ~258MB, so this isn't too bad. (We could reserve a 562 // smaller amount of space up front if this is a 563 // problem.) 564 // 565 // 2. We hint the heap to start right above the end of 566 // the binary so we have the best chance of keeping it 567 // contiguous. 568 // 569 // 3. We try to stake out a reasonably large initial 570 // heap reservation. 571 572 const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{}) 573 meta := uintptr(sysReserve(nil, arenaMetaSize, "heap reservation")) 574 if meta != 0 { 575 mheap_.heapArenaAlloc.init(meta, arenaMetaSize, true) 576 } 577 578 // We want to start the arena low, but if we're linked 579 // against C code, it's possible global constructors 580 // have called malloc and adjusted the process' brk. 581 // Query the brk so we can avoid trying to map the 582 // region over it (which will cause the kernel to put 583 // the region somewhere else, likely at a high 584 // address). 585 procBrk := sbrk0() 586 587 // If we ask for the end of the data segment but the 588 // operating system requires a little more space 589 // before we can start allocating, it will give out a 590 // slightly higher pointer. Except QEMU, which is 591 // buggy, as usual: it won't adjust the pointer 592 // upward. So adjust it upward a little bit ourselves: 593 // 1/4 MB to get away from the running binary image. 594 p := firstmoduledata.end 595 if p < procBrk { 596 p = procBrk 597 } 598 if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end { 599 p = mheap_.heapArenaAlloc.end 600 } 601 p = alignUp(p+(256<<10), heapArenaBytes) 602 // Because we're worried about fragmentation on 603 // 32-bit, we try to make a large initial reservation. 604 arenaSizes := []uintptr{ 605 512 << 20, 606 256 << 20, 607 128 << 20, 608 } 609 for _, arenaSize := range arenaSizes { 610 a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes, "heap reservation") 611 if a != nil { 612 mheap_.arena.init(uintptr(a), size, false) 613 p = mheap_.arena.end // For hint below 614 break 615 } 616 } 617 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc()) 618 hint.addr = p 619 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint 620 621 // Place the hint for user arenas just after the large reservation. 622 // 623 // While this potentially competes with the hint above, in practice we probably 624 // aren't going to be getting this far anyway on 32-bit platforms. 625 userArenaHint := (*arenaHint)(mheap_.arenaHintAlloc.alloc()) 626 userArenaHint.addr = p 627 userArenaHint.next, mheap_.userArena.arenaHints = mheap_.userArena.arenaHints, userArenaHint 628 } 629 // Initialize the memory limit here because the allocator is going to look at it 630 // but we haven't called gcinit yet and we're definitely going to allocate memory before then. 631 gcController.memoryLimit.Store(maxInt64) 632 } 633 634 // sysAlloc allocates heap arena space for at least n bytes. The 635 // returned pointer is always heapArenaBytes-aligned and backed by 636 // h.arenas metadata. The returned size is always a multiple of 637 // heapArenaBytes. sysAlloc returns nil on failure. 638 // There is no corresponding free function. 639 // 640 // hintList is a list of hint addresses for where to allocate new 641 // heap arenas. It must be non-nil. 642 // 643 // sysAlloc returns a memory region in the Reserved state. This region must 644 // be transitioned to Prepared and then Ready before use. 645 // 646 // arenaList is the list the arena should be added to. 647 // 648 // h must be locked. 649 func (h *mheap) sysAlloc(n uintptr, hintList **arenaHint, arenaList *[]arenaIdx) (v unsafe.Pointer, size uintptr) { 650 assertLockHeld(&h.lock) 651 652 n = alignUp(n, heapArenaBytes) 653 654 if hintList == &h.arenaHints { 655 // First, try the arena pre-reservation. 656 // Newly-used mappings are considered released. 657 // 658 // Only do this if we're using the regular heap arena hints. 659 // This behavior is only for the heap. 660 v = h.arena.alloc(n, heapArenaBytes, &gcController.heapReleased, "heap") 661 if v != nil { 662 size = n 663 goto mapped 664 } 665 } 666 667 // Try to grow the heap at a hint address. 668 for *hintList != nil { 669 hint := *hintList 670 p := hint.addr 671 if hint.down { 672 p -= n 673 } 674 if p+n < p { 675 // We can't use this, so don't ask. 676 v = nil 677 } else if arenaIndex(p+n-1) >= 1<<arenaBits { 678 // Outside addressable heap. Can't use. 679 v = nil 680 } else { 681 v = sysReserve(unsafe.Pointer(p), n, "heap reservation") 682 } 683 if p == uintptr(v) { 684 // Success. Update the hint. 685 if !hint.down { 686 p += n 687 } 688 hint.addr = p 689 size = n 690 break 691 } 692 // Failed. Discard this hint and try the next. 693 // 694 // TODO: This would be cleaner if sysReserve could be 695 // told to only return the requested address. In 696 // particular, this is already how Windows behaves, so 697 // it would simplify things there. 698 if v != nil { 699 sysFreeOS(v, n) 700 } 701 *hintList = hint.next 702 h.arenaHintAlloc.free(unsafe.Pointer(hint)) 703 } 704 705 if size == 0 { 706 if raceenabled { 707 // The race detector assumes the heap lives in 708 // [0x00c000000000, 0x00e000000000), but we 709 // just ran out of hints in this region. Give 710 // a nice failure. 711 throw("too many address space collisions for -race mode") 712 } 713 714 // All of the hints failed, so we'll take any 715 // (sufficiently aligned) address the kernel will give 716 // us. 717 v, size = sysReserveAligned(nil, n, heapArenaBytes, "heap") 718 if v == nil { 719 return nil, 0 720 } 721 722 // Create new hints for extending this region. 723 hint := (*arenaHint)(h.arenaHintAlloc.alloc()) 724 hint.addr, hint.down = uintptr(v), true 725 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint 726 hint = (*arenaHint)(h.arenaHintAlloc.alloc()) 727 hint.addr = uintptr(v) + size 728 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint 729 } 730 731 // Check for bad pointers or pointers we can't use. 732 { 733 var bad string 734 p := uintptr(v) 735 if p+size < p { 736 bad = "region exceeds uintptr range" 737 } else if arenaIndex(p) >= 1<<arenaBits { 738 bad = "base outside usable address space" 739 } else if arenaIndex(p+size-1) >= 1<<arenaBits { 740 bad = "end outside usable address space" 741 } 742 if bad != "" { 743 // This should be impossible on most architectures, 744 // but it would be really confusing to debug. 745 print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n") 746 throw("memory reservation exceeds address space limit") 747 } 748 } 749 750 if uintptr(v)&(heapArenaBytes-1) != 0 { 751 throw("misrounded allocation in sysAlloc") 752 } 753 754 mapped: 755 // Create arena metadata. 756 for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ { 757 l2 := h.arenas[ri.l1()] 758 if l2 == nil { 759 // Allocate an L2 arena map. 760 // 761 // Use sysAllocOS instead of sysAlloc or persistentalloc because there's no 762 // statistic we can comfortably account for this space in. With this structure, 763 // we rely on demand paging to avoid large overheads, but tracking which memory 764 // is paged in is too expensive. Trying to account for the whole region means 765 // that it will appear like an enormous memory overhead in statistics, even though 766 // it is not. 767 l2 = (*[1 << arenaL2Bits]*heapArena)(sysAllocOS(unsafe.Sizeof(*l2), "heap index")) 768 if l2 == nil { 769 throw("out of memory allocating heap arena map") 770 } 771 if h.arenasHugePages { 772 sysHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2)) 773 } else { 774 sysNoHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2)) 775 } 776 atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2)) 777 } 778 779 if l2[ri.l2()] != nil { 780 throw("arena already initialized") 781 } 782 var r *heapArena 783 r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys, "heap metadata")) 784 if r == nil { 785 r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys)) 786 if r == nil { 787 throw("out of memory allocating heap arena metadata") 788 } 789 } 790 791 // Register the arena in allArenas if requested. 792 if len((*arenaList)) == cap((*arenaList)) { 793 size := 2 * uintptr(cap((*arenaList))) * goarch.PtrSize 794 if size == 0 { 795 size = physPageSize 796 } 797 newArray := (*notInHeap)(persistentalloc(size, goarch.PtrSize, &memstats.gcMiscSys)) 798 if newArray == nil { 799 throw("out of memory allocating allArenas") 800 } 801 oldSlice := (*arenaList) 802 *(*notInHeapSlice)(unsafe.Pointer(&(*arenaList))) = notInHeapSlice{newArray, len((*arenaList)), int(size / goarch.PtrSize)} 803 copy((*arenaList), oldSlice) 804 // Do not free the old backing array because 805 // there may be concurrent readers. Since we 806 // double the array each time, this can lead 807 // to at most 2x waste. 808 } 809 (*arenaList) = (*arenaList)[:len((*arenaList))+1] 810 (*arenaList)[len((*arenaList))-1] = ri 811 812 // Store atomically just in case an object from the 813 // new heap arena becomes visible before the heap lock 814 // is released (which shouldn't happen, but there's 815 // little downside to this). 816 atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r)) 817 } 818 819 // Tell the race detector about the new heap memory. 820 if raceenabled { 821 racemapshadow(v, size) 822 } 823 824 return 825 } 826 827 // sysReserveAligned is like sysReserve, but the returned pointer is 828 // aligned to align bytes. It may reserve either n or n+align bytes, 829 // so it returns the size that was reserved. 830 func sysReserveAligned(v unsafe.Pointer, size, align uintptr, vmaName string) (unsafe.Pointer, uintptr) { 831 if isSbrkPlatform { 832 if v != nil { 833 throw("unexpected heap arena hint on sbrk platform") 834 } 835 return sysReserveAlignedSbrk(size, align) 836 } 837 // Since the alignment is rather large in uses of this 838 // function, we're not likely to get it by chance, so we ask 839 // for a larger region and remove the parts we don't need. 840 retries := 0 841 retry: 842 p := uintptr(sysReserve(v, size+align, vmaName)) 843 switch { 844 case p == 0: 845 return nil, 0 846 case p&(align-1) == 0: 847 return unsafe.Pointer(p), size + align 848 case GOOS == "windows": 849 // On Windows we can't release pieces of a 850 // reservation, so we release the whole thing and 851 // re-reserve the aligned sub-region. This may race, 852 // so we may have to try again. 853 sysFreeOS(unsafe.Pointer(p), size+align) 854 p = alignUp(p, align) 855 p2 := sysReserve(unsafe.Pointer(p), size, vmaName) 856 if p != uintptr(p2) { 857 // Must have raced. Try again. 858 sysFreeOS(p2, size) 859 if retries++; retries == 100 { 860 throw("failed to allocate aligned heap memory; too many retries") 861 } 862 goto retry 863 } 864 // Success. 865 return p2, size 866 default: 867 // Trim off the unaligned parts. 868 pAligned := alignUp(p, align) 869 sysFreeOS(unsafe.Pointer(p), pAligned-p) 870 end := pAligned + size 871 endLen := (p + size + align) - end 872 if endLen > 0 { 873 sysFreeOS(unsafe.Pointer(end), endLen) 874 } 875 return unsafe.Pointer(pAligned), size 876 } 877 } 878 879 // enableMetadataHugePages enables huge pages for various sources of heap metadata. 880 // 881 // A note on latency: for sufficiently small heaps (<10s of GiB) this function will take constant 882 // time, but may take time proportional to the size of the mapped heap beyond that. 883 // 884 // This function is idempotent. 885 // 886 // The heap lock must not be held over this operation, since it will briefly acquire 887 // the heap lock. 888 // 889 // Must be called on the system stack because it acquires the heap lock. 890 // 891 //go:systemstack 892 func (h *mheap) enableMetadataHugePages() { 893 // Enable huge pages for page structure. 894 h.pages.enableChunkHugePages() 895 896 // Grab the lock and set arenasHugePages if it's not. 897 // 898 // Once arenasHugePages is set, all new L2 entries will be eligible for 899 // huge pages. We'll set all the old entries after we release the lock. 900 lock(&h.lock) 901 if h.arenasHugePages { 902 unlock(&h.lock) 903 return 904 } 905 h.arenasHugePages = true 906 unlock(&h.lock) 907 908 // N.B. The arenas L1 map is quite small on all platforms, so it's fine to 909 // just iterate over the whole thing. 910 for i := range h.arenas { 911 l2 := (*[1 << arenaL2Bits]*heapArena)(atomic.Loadp(unsafe.Pointer(&h.arenas[i]))) 912 if l2 == nil { 913 continue 914 } 915 sysHugePage(unsafe.Pointer(l2), unsafe.Sizeof(*l2)) 916 } 917 } 918 919 // base address for all 0-byte allocations 920 var zerobase uintptr 921 922 // nextFreeFast returns the next free object if one is quickly available. 923 // Otherwise it returns 0. 924 func nextFreeFast(s *mspan) gclinkptr { 925 theBit := sys.TrailingZeros64(s.allocCache) // Is there a free object in the allocCache? 926 if theBit < 64 { 927 result := s.freeindex + uint16(theBit) 928 if result < s.nelems { 929 freeidx := result + 1 930 if freeidx%64 == 0 && freeidx != s.nelems { 931 return 0 932 } 933 s.allocCache >>= uint(theBit + 1) 934 s.freeindex = freeidx 935 s.allocCount++ 936 return gclinkptr(uintptr(result)*s.elemsize + s.base()) 937 } 938 } 939 return 0 940 } 941 942 // nextFree returns the next free object from the cached span if one is available. 943 // Otherwise it refills the cache with a span with an available object and 944 // returns that object along with a flag indicating that this was a heavy 945 // weight allocation. If it is a heavy weight allocation the caller must 946 // determine whether a new GC cycle needs to be started or if the GC is active 947 // whether this goroutine needs to assist the GC. 948 // 949 // Must run in a non-preemptible context since otherwise the owner of 950 // c could change. 951 func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, checkGCTrigger bool) { 952 s = c.alloc[spc] 953 checkGCTrigger = false 954 freeIndex := s.nextFreeIndex() 955 if freeIndex == s.nelems { 956 // The span is full. 957 if s.allocCount != s.nelems { 958 println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems) 959 throw("s.allocCount != s.nelems && freeIndex == s.nelems") 960 } 961 c.refill(spc) 962 checkGCTrigger = true 963 s = c.alloc[spc] 964 965 freeIndex = s.nextFreeIndex() 966 } 967 968 if freeIndex >= s.nelems { 969 throw("freeIndex is not valid") 970 } 971 972 v = gclinkptr(uintptr(freeIndex)*s.elemsize + s.base()) 973 s.allocCount++ 974 if s.allocCount > s.nelems { 975 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems) 976 throw("s.allocCount > s.nelems") 977 } 978 return 979 } 980 981 // doubleCheckMalloc enables a bunch of extra checks to malloc to double-check 982 // that various invariants are upheld. 983 // 984 // We might consider turning these on by default; many of them previously were. 985 // They account for a few % of mallocgc's cost though, which does matter somewhat 986 // at scale. 987 const doubleCheckMalloc = false 988 989 // Allocate an object of size bytes. 990 // Small objects are allocated from the per-P cache's free lists. 991 // Large objects (> 32 kB) are allocated straight from the heap. 992 // 993 // mallocgc should be an internal detail, 994 // but widely used packages access it using linkname. 995 // Notable members of the hall of shame include: 996 // - github.com/bytedance/gopkg 997 // - github.com/bytedance/sonic 998 // - github.com/cloudwego/frugal 999 // - github.com/cockroachdb/cockroach 1000 // - github.com/cockroachdb/pebble 1001 // - github.com/ugorji/go/codec 1002 // 1003 // Do not remove or change the type signature. 1004 // See go.dev/issue/67401. 1005 // 1006 //go:linkname mallocgc 1007 func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer { 1008 if doubleCheckMalloc { 1009 if gcphase == _GCmarktermination { 1010 throw("mallocgc called with gcphase == _GCmarktermination") 1011 } 1012 } 1013 1014 // Short-circuit zero-sized allocation requests. 1015 if size == 0 { 1016 return unsafe.Pointer(&zerobase) 1017 } 1018 1019 // It's possible for any malloc to trigger sweeping, which may in 1020 // turn queue finalizers. Record this dynamic lock edge. 1021 // N.B. Compiled away if lockrank experiment is not enabled. 1022 lockRankMayQueueFinalizer() 1023 1024 // Pre-malloc debug hooks. 1025 if debug.malloc { 1026 if x := preMallocgcDebug(size, typ); x != nil { 1027 return x 1028 } 1029 } 1030 1031 // For ASAN, we allocate extra memory around each allocation called the "redzone." 1032 // These "redzones" are marked as unaddressable. 1033 var asanRZ uintptr 1034 if asanenabled { 1035 asanRZ = redZoneSize(size) 1036 size += asanRZ 1037 } 1038 1039 // Assist the GC if needed. 1040 if gcBlackenEnabled != 0 { 1041 deductAssistCredit(size) 1042 } 1043 1044 // Actually do the allocation. 1045 var x unsafe.Pointer 1046 var elemsize uintptr 1047 if size <= maxSmallSize-mallocHeaderSize { 1048 if typ == nil || !typ.Pointers() { 1049 if size < maxTinySize { 1050 x, elemsize = mallocgcTiny(size, typ, needzero) 1051 } else { 1052 x, elemsize = mallocgcSmallNoscan(size, typ, needzero) 1053 } 1054 } else if heapBitsInSpan(size) { 1055 x, elemsize = mallocgcSmallScanNoHeader(size, typ, needzero) 1056 } else { 1057 x, elemsize = mallocgcSmallScanHeader(size, typ, needzero) 1058 } 1059 } else { 1060 x, elemsize = mallocgcLarge(size, typ, needzero) 1061 } 1062 1063 // Notify sanitizers, if enabled. 1064 if raceenabled { 1065 racemalloc(x, size-asanRZ) 1066 } 1067 if msanenabled { 1068 msanmalloc(x, size-asanRZ) 1069 } 1070 if asanenabled { 1071 // Poison the space between the end of the requested size of x 1072 // and the end of the slot. Unpoison the requested allocation. 1073 frag := elemsize - size 1074 if typ != nil && typ.Pointers() && !heapBitsInSpan(elemsize) && size <= maxSmallSize-mallocHeaderSize { 1075 frag -= mallocHeaderSize 1076 } 1077 asanpoison(unsafe.Add(x, size-asanRZ), asanRZ) 1078 asanunpoison(x, size-asanRZ) 1079 } 1080 1081 // Adjust our GC assist debt to account for internal fragmentation. 1082 if gcBlackenEnabled != 0 && elemsize != 0 { 1083 if assistG := getg().m.curg; assistG != nil { 1084 assistG.gcAssistBytes -= int64(elemsize - size) 1085 } 1086 } 1087 1088 // Post-malloc debug hooks. 1089 if debug.malloc { 1090 postMallocgcDebug(x, elemsize, typ) 1091 } 1092 return x 1093 } 1094 1095 func mallocgcTiny(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) { 1096 // Set mp.mallocing to keep from being preempted by GC. 1097 mp := acquirem() 1098 if doubleCheckMalloc { 1099 if mp.mallocing != 0 { 1100 throw("malloc deadlock") 1101 } 1102 if mp.gsignal == getg() { 1103 throw("malloc during signal") 1104 } 1105 if typ != nil && typ.Pointers() { 1106 throw("expected noscan for tiny alloc") 1107 } 1108 } 1109 mp.mallocing = 1 1110 1111 // Tiny allocator. 1112 // 1113 // Tiny allocator combines several tiny allocation requests 1114 // into a single memory block. The resulting memory block 1115 // is freed when all subobjects are unreachable. The subobjects 1116 // must be noscan (don't have pointers), this ensures that 1117 // the amount of potentially wasted memory is bounded. 1118 // 1119 // Size of the memory block used for combining (maxTinySize) is tunable. 1120 // Current setting is 16 bytes, which relates to 2x worst case memory 1121 // wastage (when all but one subobjects are unreachable). 1122 // 8 bytes would result in no wastage at all, but provides less 1123 // opportunities for combining. 1124 // 32 bytes provides more opportunities for combining, 1125 // but can lead to 4x worst case wastage. 1126 // The best case winning is 8x regardless of block size. 1127 // 1128 // Objects obtained from tiny allocator must not be freed explicitly. 1129 // So when an object will be freed explicitly, we ensure that 1130 // its size >= maxTinySize. 1131 // 1132 // SetFinalizer has a special case for objects potentially coming 1133 // from tiny allocator, it such case it allows to set finalizers 1134 // for an inner byte of a memory block. 1135 // 1136 // The main targets of tiny allocator are small strings and 1137 // standalone escaping variables. On a json benchmark 1138 // the allocator reduces number of allocations by ~12% and 1139 // reduces heap size by ~20%. 1140 c := getMCache(mp) 1141 off := c.tinyoffset 1142 // Align tiny pointer for required (conservative) alignment. 1143 if size&7 == 0 { 1144 off = alignUp(off, 8) 1145 } else if goarch.PtrSize == 4 && size == 12 { 1146 // Conservatively align 12-byte objects to 8 bytes on 32-bit 1147 // systems so that objects whose first field is a 64-bit 1148 // value is aligned to 8 bytes and does not cause a fault on 1149 // atomic access. See issue 37262. 1150 // TODO(mknyszek): Remove this workaround if/when issue 36606 1151 // is resolved. 1152 off = alignUp(off, 8) 1153 } else if size&3 == 0 { 1154 off = alignUp(off, 4) 1155 } else if size&1 == 0 { 1156 off = alignUp(off, 2) 1157 } 1158 if off+size <= maxTinySize && c.tiny != 0 { 1159 // The object fits into existing tiny block. 1160 x := unsafe.Pointer(c.tiny + off) 1161 c.tinyoffset = off + size 1162 c.tinyAllocs++ 1163 mp.mallocing = 0 1164 releasem(mp) 1165 return x, 0 1166 } 1167 // Allocate a new maxTinySize block. 1168 checkGCTrigger := false 1169 span := c.alloc[tinySpanClass] 1170 v := nextFreeFast(span) 1171 if v == 0 { 1172 v, span, checkGCTrigger = c.nextFree(tinySpanClass) 1173 } 1174 x := unsafe.Pointer(v) 1175 (*[2]uint64)(x)[0] = 0 1176 (*[2]uint64)(x)[1] = 0 1177 // See if we need to replace the existing tiny block with the new one 1178 // based on amount of remaining free space. 1179 if !raceenabled && (size < c.tinyoffset || c.tiny == 0) { 1180 // Note: disabled when race detector is on, see comment near end of this function. 1181 c.tiny = uintptr(x) 1182 c.tinyoffset = size 1183 } 1184 1185 // Ensure that the stores above that initialize x to 1186 // type-safe memory and set the heap bits occur before 1187 // the caller can make x observable to the garbage 1188 // collector. Otherwise, on weakly ordered machines, 1189 // the garbage collector could follow a pointer to x, 1190 // but see uninitialized memory or stale heap bits. 1191 publicationBarrier() 1192 // As x and the heap bits are initialized, update 1193 // freeIndexForScan now so x is seen by the GC 1194 // (including conservative scan) as an allocated object. 1195 // While this pointer can't escape into user code as a 1196 // _live_ pointer until we return, conservative scanning 1197 // may find a dead pointer that happens to point into this 1198 // object. Delaying this update until now ensures that 1199 // conservative scanning considers this pointer dead until 1200 // this point. 1201 span.freeIndexForScan = span.freeindex 1202 1203 // Allocate black during GC. 1204 // All slots hold nil so no scanning is needed. 1205 // This may be racing with GC so do it atomically if there can be 1206 // a race marking the bit. 1207 if writeBarrier.enabled { 1208 gcmarknewobject(span, uintptr(x)) 1209 } 1210 1211 // Note cache c only valid while m acquired; see #47302 1212 // 1213 // N.B. Use the full size because that matches how the GC 1214 // will update the mem profile on the "free" side. 1215 // 1216 // TODO(mknyszek): We should really count the header as part 1217 // of gc_sys or something. The code below just pretends it is 1218 // internal fragmentation and matches the GC's accounting by 1219 // using the whole allocation slot. 1220 c.nextSample -= int64(span.elemsize) 1221 if c.nextSample < 0 || MemProfileRate != c.memProfRate { 1222 profilealloc(mp, x, span.elemsize) 1223 } 1224 mp.mallocing = 0 1225 releasem(mp) 1226 1227 if checkGCTrigger { 1228 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { 1229 gcStart(t) 1230 } 1231 } 1232 1233 if raceenabled { 1234 // Pad tinysize allocations so they are aligned with the end 1235 // of the tinyalloc region. This ensures that any arithmetic 1236 // that goes off the top end of the object will be detectable 1237 // by checkptr (issue 38872). 1238 // Note that we disable tinyalloc when raceenabled for this to work. 1239 // TODO: This padding is only performed when the race detector 1240 // is enabled. It would be nice to enable it if any package 1241 // was compiled with checkptr, but there's no easy way to 1242 // detect that (especially at compile time). 1243 // TODO: enable this padding for all allocations, not just 1244 // tinyalloc ones. It's tricky because of pointer maps. 1245 // Maybe just all noscan objects? 1246 x = add(x, span.elemsize-size) 1247 } 1248 return x, span.elemsize 1249 } 1250 1251 func mallocgcSmallNoscan(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) { 1252 // Set mp.mallocing to keep from being preempted by GC. 1253 mp := acquirem() 1254 if doubleCheckMalloc { 1255 if mp.mallocing != 0 { 1256 throw("malloc deadlock") 1257 } 1258 if mp.gsignal == getg() { 1259 throw("malloc during signal") 1260 } 1261 if typ != nil && typ.Pointers() { 1262 throw("expected noscan type for noscan alloc") 1263 } 1264 } 1265 mp.mallocing = 1 1266 1267 checkGCTrigger := false 1268 c := getMCache(mp) 1269 var sizeclass uint8 1270 if size <= smallSizeMax-8 { 1271 sizeclass = size_to_class8[divRoundUp(size, smallSizeDiv)] 1272 } else { 1273 sizeclass = size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)] 1274 } 1275 size = uintptr(class_to_size[sizeclass]) 1276 spc := makeSpanClass(sizeclass, true) 1277 span := c.alloc[spc] 1278 v := nextFreeFast(span) 1279 if v == 0 { 1280 v, span, checkGCTrigger = c.nextFree(spc) 1281 } 1282 x := unsafe.Pointer(v) 1283 if needzero && span.needzero != 0 { 1284 memclrNoHeapPointers(x, size) 1285 } 1286 1287 // Ensure that the stores above that initialize x to 1288 // type-safe memory and set the heap bits occur before 1289 // the caller can make x observable to the garbage 1290 // collector. Otherwise, on weakly ordered machines, 1291 // the garbage collector could follow a pointer to x, 1292 // but see uninitialized memory or stale heap bits. 1293 publicationBarrier() 1294 // As x and the heap bits are initialized, update 1295 // freeIndexForScan now so x is seen by the GC 1296 // (including conservative scan) as an allocated object. 1297 // While this pointer can't escape into user code as a 1298 // _live_ pointer until we return, conservative scanning 1299 // may find a dead pointer that happens to point into this 1300 // object. Delaying this update until now ensures that 1301 // conservative scanning considers this pointer dead until 1302 // this point. 1303 span.freeIndexForScan = span.freeindex 1304 1305 // Allocate black during GC. 1306 // All slots hold nil so no scanning is needed. 1307 // This may be racing with GC so do it atomically if there can be 1308 // a race marking the bit. 1309 if writeBarrier.enabled { 1310 gcmarknewobject(span, uintptr(x)) 1311 } 1312 1313 // Note cache c only valid while m acquired; see #47302 1314 // 1315 // N.B. Use the full size because that matches how the GC 1316 // will update the mem profile on the "free" side. 1317 // 1318 // TODO(mknyszek): We should really count the header as part 1319 // of gc_sys or something. The code below just pretends it is 1320 // internal fragmentation and matches the GC's accounting by 1321 // using the whole allocation slot. 1322 c.nextSample -= int64(size) 1323 if c.nextSample < 0 || MemProfileRate != c.memProfRate { 1324 profilealloc(mp, x, size) 1325 } 1326 mp.mallocing = 0 1327 releasem(mp) 1328 1329 if checkGCTrigger { 1330 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { 1331 gcStart(t) 1332 } 1333 } 1334 return x, size 1335 } 1336 1337 func mallocgcSmallScanNoHeader(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) { 1338 // Set mp.mallocing to keep from being preempted by GC. 1339 mp := acquirem() 1340 if doubleCheckMalloc { 1341 if mp.mallocing != 0 { 1342 throw("malloc deadlock") 1343 } 1344 if mp.gsignal == getg() { 1345 throw("malloc during signal") 1346 } 1347 if typ == nil || !typ.Pointers() { 1348 throw("noscan allocated in scan-only path") 1349 } 1350 if !heapBitsInSpan(size) { 1351 throw("heap bits in not in span for non-header-only path") 1352 } 1353 } 1354 mp.mallocing = 1 1355 1356 checkGCTrigger := false 1357 c := getMCache(mp) 1358 sizeclass := size_to_class8[divRoundUp(size, smallSizeDiv)] 1359 spc := makeSpanClass(sizeclass, false) 1360 span := c.alloc[spc] 1361 v := nextFreeFast(span) 1362 if v == 0 { 1363 v, span, checkGCTrigger = c.nextFree(spc) 1364 } 1365 x := unsafe.Pointer(v) 1366 if needzero && span.needzero != 0 { 1367 memclrNoHeapPointers(x, size) 1368 } 1369 if goarch.PtrSize == 8 && sizeclass == 1 { 1370 // initHeapBits already set the pointer bits for the 8-byte sizeclass 1371 // on 64-bit platforms. 1372 c.scanAlloc += 8 1373 } else { 1374 c.scanAlloc += heapSetTypeNoHeader(uintptr(x), size, typ, span) 1375 } 1376 size = uintptr(class_to_size[sizeclass]) 1377 1378 // Ensure that the stores above that initialize x to 1379 // type-safe memory and set the heap bits occur before 1380 // the caller can make x observable to the garbage 1381 // collector. Otherwise, on weakly ordered machines, 1382 // the garbage collector could follow a pointer to x, 1383 // but see uninitialized memory or stale heap bits. 1384 publicationBarrier() 1385 // As x and the heap bits are initialized, update 1386 // freeIndexForScan now so x is seen by the GC 1387 // (including conservative scan) as an allocated object. 1388 // While this pointer can't escape into user code as a 1389 // _live_ pointer until we return, conservative scanning 1390 // may find a dead pointer that happens to point into this 1391 // object. Delaying this update until now ensures that 1392 // conservative scanning considers this pointer dead until 1393 // this point. 1394 span.freeIndexForScan = span.freeindex 1395 1396 // Allocate black during GC. 1397 // All slots hold nil so no scanning is needed. 1398 // This may be racing with GC so do it atomically if there can be 1399 // a race marking the bit. 1400 if writeBarrier.enabled { 1401 gcmarknewobject(span, uintptr(x)) 1402 } 1403 1404 // Note cache c only valid while m acquired; see #47302 1405 // 1406 // N.B. Use the full size because that matches how the GC 1407 // will update the mem profile on the "free" side. 1408 // 1409 // TODO(mknyszek): We should really count the header as part 1410 // of gc_sys or something. The code below just pretends it is 1411 // internal fragmentation and matches the GC's accounting by 1412 // using the whole allocation slot. 1413 c.nextSample -= int64(size) 1414 if c.nextSample < 0 || MemProfileRate != c.memProfRate { 1415 profilealloc(mp, x, size) 1416 } 1417 mp.mallocing = 0 1418 releasem(mp) 1419 1420 if checkGCTrigger { 1421 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { 1422 gcStart(t) 1423 } 1424 } 1425 return x, size 1426 } 1427 1428 func mallocgcSmallScanHeader(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) { 1429 // Set mp.mallocing to keep from being preempted by GC. 1430 mp := acquirem() 1431 if doubleCheckMalloc { 1432 if mp.mallocing != 0 { 1433 throw("malloc deadlock") 1434 } 1435 if mp.gsignal == getg() { 1436 throw("malloc during signal") 1437 } 1438 if typ == nil || !typ.Pointers() { 1439 throw("noscan allocated in scan-only path") 1440 } 1441 if heapBitsInSpan(size) { 1442 throw("heap bits in span for header-only path") 1443 } 1444 } 1445 mp.mallocing = 1 1446 1447 checkGCTrigger := false 1448 c := getMCache(mp) 1449 size += mallocHeaderSize 1450 var sizeclass uint8 1451 if size <= smallSizeMax-8 { 1452 sizeclass = size_to_class8[divRoundUp(size, smallSizeDiv)] 1453 } else { 1454 sizeclass = size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)] 1455 } 1456 size = uintptr(class_to_size[sizeclass]) 1457 spc := makeSpanClass(sizeclass, false) 1458 span := c.alloc[spc] 1459 v := nextFreeFast(span) 1460 if v == 0 { 1461 v, span, checkGCTrigger = c.nextFree(spc) 1462 } 1463 x := unsafe.Pointer(v) 1464 if needzero && span.needzero != 0 { 1465 memclrNoHeapPointers(x, size) 1466 } 1467 header := (**_type)(x) 1468 x = add(x, mallocHeaderSize) 1469 c.scanAlloc += heapSetTypeSmallHeader(uintptr(x), size-mallocHeaderSize, typ, header, span) 1470 1471 // Ensure that the stores above that initialize x to 1472 // type-safe memory and set the heap bits occur before 1473 // the caller can make x observable to the garbage 1474 // collector. Otherwise, on weakly ordered machines, 1475 // the garbage collector could follow a pointer to x, 1476 // but see uninitialized memory or stale heap bits. 1477 publicationBarrier() 1478 // As x and the heap bits are initialized, update 1479 // freeIndexForScan now so x is seen by the GC 1480 // (including conservative scan) as an allocated object. 1481 // While this pointer can't escape into user code as a 1482 // _live_ pointer until we return, conservative scanning 1483 // may find a dead pointer that happens to point into this 1484 // object. Delaying this update until now ensures that 1485 // conservative scanning considers this pointer dead until 1486 // this point. 1487 span.freeIndexForScan = span.freeindex 1488 1489 // Allocate black during GC. 1490 // All slots hold nil so no scanning is needed. 1491 // This may be racing with GC so do it atomically if there can be 1492 // a race marking the bit. 1493 if writeBarrier.enabled { 1494 gcmarknewobject(span, uintptr(x)) 1495 } 1496 1497 // Note cache c only valid while m acquired; see #47302 1498 // 1499 // N.B. Use the full size because that matches how the GC 1500 // will update the mem profile on the "free" side. 1501 // 1502 // TODO(mknyszek): We should really count the header as part 1503 // of gc_sys or something. The code below just pretends it is 1504 // internal fragmentation and matches the GC's accounting by 1505 // using the whole allocation slot. 1506 c.nextSample -= int64(size) 1507 if c.nextSample < 0 || MemProfileRate != c.memProfRate { 1508 profilealloc(mp, x, size) 1509 } 1510 mp.mallocing = 0 1511 releasem(mp) 1512 1513 if checkGCTrigger { 1514 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { 1515 gcStart(t) 1516 } 1517 } 1518 return x, size 1519 } 1520 1521 func mallocgcLarge(size uintptr, typ *_type, needzero bool) (unsafe.Pointer, uintptr) { 1522 // Set mp.mallocing to keep from being preempted by GC. 1523 mp := acquirem() 1524 if doubleCheckMalloc { 1525 if mp.mallocing != 0 { 1526 throw("malloc deadlock") 1527 } 1528 if mp.gsignal == getg() { 1529 throw("malloc during signal") 1530 } 1531 } 1532 mp.mallocing = 1 1533 1534 c := getMCache(mp) 1535 // For large allocations, keep track of zeroed state so that 1536 // bulk zeroing can be happen later in a preemptible context. 1537 span := c.allocLarge(size, typ == nil || !typ.Pointers()) 1538 span.freeindex = 1 1539 span.allocCount = 1 1540 span.largeType = nil // Tell the GC not to look at this yet. 1541 size = span.elemsize 1542 x := unsafe.Pointer(span.base()) 1543 1544 // Ensure that the stores above that initialize x to 1545 // type-safe memory and set the heap bits occur before 1546 // the caller can make x observable to the garbage 1547 // collector. Otherwise, on weakly ordered machines, 1548 // the garbage collector could follow a pointer to x, 1549 // but see uninitialized memory or stale heap bits. 1550 publicationBarrier() 1551 // As x and the heap bits are initialized, update 1552 // freeIndexForScan now so x is seen by the GC 1553 // (including conservative scan) as an allocated object. 1554 // While this pointer can't escape into user code as a 1555 // _live_ pointer until we return, conservative scanning 1556 // may find a dead pointer that happens to point into this 1557 // object. Delaying this update until now ensures that 1558 // conservative scanning considers this pointer dead until 1559 // this point. 1560 span.freeIndexForScan = span.freeindex 1561 1562 // Allocate black during GC. 1563 // All slots hold nil so no scanning is needed. 1564 // This may be racing with GC so do it atomically if there can be 1565 // a race marking the bit. 1566 if writeBarrier.enabled { 1567 gcmarknewobject(span, uintptr(x)) 1568 } 1569 1570 // Note cache c only valid while m acquired; see #47302 1571 // 1572 // N.B. Use the full size because that matches how the GC 1573 // will update the mem profile on the "free" side. 1574 // 1575 // TODO(mknyszek): We should really count the header as part 1576 // of gc_sys or something. The code below just pretends it is 1577 // internal fragmentation and matches the GC's accounting by 1578 // using the whole allocation slot. 1579 c.nextSample -= int64(size) 1580 if c.nextSample < 0 || MemProfileRate != c.memProfRate { 1581 profilealloc(mp, x, size) 1582 } 1583 mp.mallocing = 0 1584 releasem(mp) 1585 1586 // Check to see if we need to trigger the GC. 1587 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { 1588 gcStart(t) 1589 } 1590 1591 // Objects can be zeroed late in a context where preemption can occur. 1592 // If the object contains pointers, its pointer data must be cleared 1593 // or otherwise indicate that the GC shouldn't scan it. 1594 // x will keep the memory alive. 1595 if noscan := typ == nil || !typ.Pointers(); !noscan || (needzero && span.needzero != 0) { 1596 // N.B. size == fullSize always in this case. 1597 memclrNoHeapPointersChunked(size, x) // This is a possible preemption point: see #47302 1598 1599 // Finish storing the type information for this case. 1600 mp := acquirem() 1601 if !noscan { 1602 getMCache(mp).scanAlloc += heapSetTypeLarge(uintptr(x), size, typ, span) 1603 } 1604 // Publish the object with the now-zeroed memory. 1605 publicationBarrier() 1606 releasem(mp) 1607 } 1608 return x, size 1609 } 1610 1611 func preMallocgcDebug(size uintptr, typ *_type) unsafe.Pointer { 1612 if debug.sbrk != 0 { 1613 align := uintptr(16) 1614 if typ != nil { 1615 // TODO(austin): This should be just 1616 // align = uintptr(typ.align) 1617 // but that's only 4 on 32-bit platforms, 1618 // even if there's a uint64 field in typ (see #599). 1619 // This causes 64-bit atomic accesses to panic. 1620 // Hence, we use stricter alignment that matches 1621 // the normal allocator better. 1622 if size&7 == 0 { 1623 align = 8 1624 } else if size&3 == 0 { 1625 align = 4 1626 } else if size&1 == 0 { 1627 align = 2 1628 } else { 1629 align = 1 1630 } 1631 } 1632 return persistentalloc(size, align, &memstats.other_sys) 1633 } 1634 if inittrace.active && inittrace.id == getg().goid { 1635 // Init functions are executed sequentially in a single goroutine. 1636 inittrace.allocs += 1 1637 } 1638 return nil 1639 } 1640 1641 func postMallocgcDebug(x unsafe.Pointer, elemsize uintptr, typ *_type) { 1642 if inittrace.active && inittrace.id == getg().goid { 1643 // Init functions are executed sequentially in a single goroutine. 1644 inittrace.bytes += uint64(elemsize) 1645 } 1646 1647 if traceAllocFreeEnabled() { 1648 trace := traceAcquire() 1649 if trace.ok() { 1650 trace.HeapObjectAlloc(uintptr(x), typ) 1651 traceRelease(trace) 1652 } 1653 } 1654 } 1655 1656 // deductAssistCredit reduces the current G's assist credit 1657 // by size bytes, and assists the GC if necessary. 1658 // 1659 // Caller must be preemptible. 1660 // 1661 // Returns the G for which the assist credit was accounted. 1662 func deductAssistCredit(size uintptr) { 1663 // Charge the current user G for this allocation. 1664 assistG := getg() 1665 if assistG.m.curg != nil { 1666 assistG = assistG.m.curg 1667 } 1668 // Charge the allocation against the G. We'll account 1669 // for internal fragmentation at the end of mallocgc. 1670 assistG.gcAssistBytes -= int64(size) 1671 1672 if assistG.gcAssistBytes < 0 { 1673 // This G is in debt. Assist the GC to correct 1674 // this before allocating. This must happen 1675 // before disabling preemption. 1676 gcAssistAlloc(assistG) 1677 } 1678 } 1679 1680 // memclrNoHeapPointersChunked repeatedly calls memclrNoHeapPointers 1681 // on chunks of the buffer to be zeroed, with opportunities for preemption 1682 // along the way. memclrNoHeapPointers contains no safepoints and also 1683 // cannot be preemptively scheduled, so this provides a still-efficient 1684 // block copy that can also be preempted on a reasonable granularity. 1685 // 1686 // Use this with care; if the data being cleared is tagged to contain 1687 // pointers, this allows the GC to run before it is all cleared. 1688 func memclrNoHeapPointersChunked(size uintptr, x unsafe.Pointer) { 1689 v := uintptr(x) 1690 // got this from benchmarking. 128k is too small, 512k is too large. 1691 const chunkBytes = 256 * 1024 1692 vsize := v + size 1693 for voff := v; voff < vsize; voff = voff + chunkBytes { 1694 if getg().preempt { 1695 // may hold locks, e.g., profiling 1696 goschedguarded() 1697 } 1698 // clear min(avail, lump) bytes 1699 n := vsize - voff 1700 if n > chunkBytes { 1701 n = chunkBytes 1702 } 1703 memclrNoHeapPointers(unsafe.Pointer(voff), n) 1704 } 1705 } 1706 1707 // implementation of new builtin 1708 // compiler (both frontend and SSA backend) knows the signature 1709 // of this function. 1710 func newobject(typ *_type) unsafe.Pointer { 1711 return mallocgc(typ.Size_, typ, true) 1712 } 1713 1714 //go:linkname maps_newobject internal/runtime/maps.newobject 1715 func maps_newobject(typ *_type) unsafe.Pointer { 1716 return newobject(typ) 1717 } 1718 1719 // reflect_unsafe_New is meant for package reflect, 1720 // but widely used packages access it using linkname. 1721 // Notable members of the hall of shame include: 1722 // - gitee.com/quant1x/gox 1723 // - github.com/goccy/json 1724 // - github.com/modern-go/reflect2 1725 // - github.com/v2pro/plz 1726 // 1727 // Do not remove or change the type signature. 1728 // See go.dev/issue/67401. 1729 // 1730 //go:linkname reflect_unsafe_New reflect.unsafe_New 1731 func reflect_unsafe_New(typ *_type) unsafe.Pointer { 1732 return mallocgc(typ.Size_, typ, true) 1733 } 1734 1735 //go:linkname reflectlite_unsafe_New internal/reflectlite.unsafe_New 1736 func reflectlite_unsafe_New(typ *_type) unsafe.Pointer { 1737 return mallocgc(typ.Size_, typ, true) 1738 } 1739 1740 // newarray allocates an array of n elements of type typ. 1741 // 1742 // newarray should be an internal detail, 1743 // but widely used packages access it using linkname. 1744 // Notable members of the hall of shame include: 1745 // - github.com/RomiChan/protobuf 1746 // - github.com/segmentio/encoding 1747 // - github.com/ugorji/go/codec 1748 // 1749 // Do not remove or change the type signature. 1750 // See go.dev/issue/67401. 1751 // 1752 //go:linkname newarray 1753 func newarray(typ *_type, n int) unsafe.Pointer { 1754 if n == 1 { 1755 return mallocgc(typ.Size_, typ, true) 1756 } 1757 mem, overflow := math.MulUintptr(typ.Size_, uintptr(n)) 1758 if overflow || mem > maxAlloc || n < 0 { 1759 panic(plainError("runtime: allocation size out of range")) 1760 } 1761 return mallocgc(mem, typ, true) 1762 } 1763 1764 // reflect_unsafe_NewArray is meant for package reflect, 1765 // but widely used packages access it using linkname. 1766 // Notable members of the hall of shame include: 1767 // - gitee.com/quant1x/gox 1768 // - github.com/bytedance/sonic 1769 // - github.com/goccy/json 1770 // - github.com/modern-go/reflect2 1771 // - github.com/segmentio/encoding 1772 // - github.com/segmentio/kafka-go 1773 // - github.com/v2pro/plz 1774 // 1775 // Do not remove or change the type signature. 1776 // See go.dev/issue/67401. 1777 // 1778 //go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray 1779 func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer { 1780 return newarray(typ, n) 1781 } 1782 1783 //go:linkname maps_newarray internal/runtime/maps.newarray 1784 func maps_newarray(typ *_type, n int) unsafe.Pointer { 1785 return newarray(typ, n) 1786 } 1787 1788 // profilealloc resets the current mcache's nextSample counter and 1789 // records a memory profile sample. 1790 // 1791 // The caller must be non-preemptible and have a P. 1792 func profilealloc(mp *m, x unsafe.Pointer, size uintptr) { 1793 c := getMCache(mp) 1794 if c == nil { 1795 throw("profilealloc called without a P or outside bootstrapping") 1796 } 1797 c.memProfRate = MemProfileRate 1798 c.nextSample = nextSample() 1799 mProf_Malloc(mp, x, size) 1800 } 1801 1802 // nextSample returns the next sampling point for heap profiling. The goal is 1803 // to sample allocations on average every MemProfileRate bytes, but with a 1804 // completely random distribution over the allocation timeline; this 1805 // corresponds to a Poisson process with parameter MemProfileRate. In Poisson 1806 // processes, the distance between two samples follows the exponential 1807 // distribution (exp(MemProfileRate)), so the best return value is a random 1808 // number taken from an exponential distribution whose mean is MemProfileRate. 1809 func nextSample() int64 { 1810 if MemProfileRate == 0 { 1811 // Basically never sample. 1812 return maxInt64 1813 } 1814 if MemProfileRate == 1 { 1815 // Sample immediately. 1816 return 0 1817 } 1818 return int64(fastexprand(MemProfileRate)) 1819 } 1820 1821 // fastexprand returns a random number from an exponential distribution with 1822 // the specified mean. 1823 func fastexprand(mean int) int32 { 1824 // Avoid overflow. Maximum possible step is 1825 // -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean. 1826 switch { 1827 case mean > 0x7000000: 1828 mean = 0x7000000 1829 case mean == 0: 1830 return 0 1831 } 1832 1833 // Take a random sample of the exponential distribution exp(-mean*x). 1834 // The probability distribution function is mean*exp(-mean*x), so the CDF is 1835 // p = 1 - exp(-mean*x), so 1836 // q = 1 - p == exp(-mean*x) 1837 // log_e(q) = -mean*x 1838 // -log_e(q)/mean = x 1839 // x = -log_e(q) * mean 1840 // x = log_2(q) * (-log_e(2)) * mean ; Using log_2 for efficiency 1841 const randomBitCount = 26 1842 q := cheaprandn(1<<randomBitCount) + 1 1843 qlog := fastlog2(float64(q)) - randomBitCount 1844 if qlog > 0 { 1845 qlog = 0 1846 } 1847 const minusLog2 = -0.6931471805599453 // -ln(2) 1848 return int32(qlog*(minusLog2*float64(mean))) + 1 1849 } 1850 1851 type persistentAlloc struct { 1852 base *notInHeap 1853 off uintptr 1854 } 1855 1856 var globalAlloc struct { 1857 mutex 1858 persistentAlloc 1859 } 1860 1861 // persistentChunkSize is the number of bytes we allocate when we grow 1862 // a persistentAlloc. 1863 const persistentChunkSize = 256 << 10 1864 1865 // persistentChunks is a list of all the persistent chunks we have 1866 // allocated. The list is maintained through the first word in the 1867 // persistent chunk. This is updated atomically. 1868 var persistentChunks *notInHeap 1869 1870 // Wrapper around sysAlloc that can allocate small chunks. 1871 // There is no associated free operation. 1872 // Intended for things like function/type/debug-related persistent data. 1873 // If align is 0, uses default align (currently 8). 1874 // The returned memory will be zeroed. 1875 // sysStat must be non-nil. 1876 // 1877 // Consider marking persistentalloc'd types not in heap by embedding 1878 // internal/runtime/sys.NotInHeap. 1879 // 1880 // nosplit because it is used during write barriers and must not be preempted. 1881 // 1882 //go:nosplit 1883 func persistentalloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer { 1884 var p *notInHeap 1885 systemstack(func() { 1886 p = persistentalloc1(size, align, sysStat) 1887 }) 1888 return unsafe.Pointer(p) 1889 } 1890 1891 // Must run on system stack because stack growth can (re)invoke it. 1892 // See issue 9174. 1893 // 1894 //go:systemstack 1895 func persistentalloc1(size, align uintptr, sysStat *sysMemStat) *notInHeap { 1896 const ( 1897 maxBlock = 64 << 10 // VM reservation granularity is 64K on windows 1898 ) 1899 1900 if size == 0 { 1901 throw("persistentalloc: size == 0") 1902 } 1903 if align != 0 { 1904 if align&(align-1) != 0 { 1905 throw("persistentalloc: align is not a power of 2") 1906 } 1907 if align > _PageSize { 1908 throw("persistentalloc: align is too large") 1909 } 1910 } else { 1911 align = 8 1912 } 1913 1914 if size >= maxBlock { 1915 return (*notInHeap)(sysAlloc(size, sysStat, "immortal metadata")) 1916 } 1917 1918 mp := acquirem() 1919 var persistent *persistentAlloc 1920 if mp != nil && mp.p != 0 { 1921 persistent = &mp.p.ptr().palloc 1922 } else { 1923 lock(&globalAlloc.mutex) 1924 persistent = &globalAlloc.persistentAlloc 1925 } 1926 persistent.off = alignUp(persistent.off, align) 1927 if persistent.off+size > persistentChunkSize || persistent.base == nil { 1928 persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys, "immortal metadata")) 1929 if persistent.base == nil { 1930 if persistent == &globalAlloc.persistentAlloc { 1931 unlock(&globalAlloc.mutex) 1932 } 1933 throw("runtime: cannot allocate memory") 1934 } 1935 1936 // Add the new chunk to the persistentChunks list. 1937 for { 1938 chunks := uintptr(unsafe.Pointer(persistentChunks)) 1939 *(*uintptr)(unsafe.Pointer(persistent.base)) = chunks 1940 if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) { 1941 break 1942 } 1943 } 1944 persistent.off = alignUp(goarch.PtrSize, align) 1945 } 1946 p := persistent.base.add(persistent.off) 1947 persistent.off += size 1948 releasem(mp) 1949 if persistent == &globalAlloc.persistentAlloc { 1950 unlock(&globalAlloc.mutex) 1951 } 1952 1953 if sysStat != &memstats.other_sys { 1954 sysStat.add(int64(size)) 1955 memstats.other_sys.add(-int64(size)) 1956 } 1957 return p 1958 } 1959 1960 // inPersistentAlloc reports whether p points to memory allocated by 1961 // persistentalloc. This must be nosplit because it is called by the 1962 // cgo checker code, which is called by the write barrier code. 1963 // 1964 //go:nosplit 1965 func inPersistentAlloc(p uintptr) bool { 1966 chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks))) 1967 for chunk != 0 { 1968 if p >= chunk && p < chunk+persistentChunkSize { 1969 return true 1970 } 1971 chunk = *(*uintptr)(unsafe.Pointer(chunk)) 1972 } 1973 return false 1974 } 1975 1976 // linearAlloc is a simple linear allocator that pre-reserves a region 1977 // of memory and then optionally maps that region into the Ready state 1978 // as needed. 1979 // 1980 // The caller is responsible for locking. 1981 type linearAlloc struct { 1982 next uintptr // next free byte 1983 mapped uintptr // one byte past end of mapped space 1984 end uintptr // end of reserved space 1985 1986 mapMemory bool // transition memory from Reserved to Ready if true 1987 } 1988 1989 func (l *linearAlloc) init(base, size uintptr, mapMemory bool) { 1990 if base+size < base { 1991 // Chop off the last byte. The runtime isn't prepared 1992 // to deal with situations where the bounds could overflow. 1993 // Leave that memory reserved, though, so we don't map it 1994 // later. 1995 size -= 1 1996 } 1997 l.next, l.mapped = base, base 1998 l.end = base + size 1999 l.mapMemory = mapMemory 2000 } 2001 2002 func (l *linearAlloc) alloc(size, align uintptr, sysStat *sysMemStat, vmaName string) unsafe.Pointer { 2003 p := alignUp(l.next, align) 2004 if p+size > l.end { 2005 return nil 2006 } 2007 l.next = p + size 2008 if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped { 2009 if l.mapMemory { 2010 // Transition from Reserved to Prepared to Ready. 2011 n := pEnd - l.mapped 2012 sysMap(unsafe.Pointer(l.mapped), n, sysStat, vmaName) 2013 sysUsed(unsafe.Pointer(l.mapped), n, n) 2014 } 2015 l.mapped = pEnd 2016 } 2017 return unsafe.Pointer(p) 2018 } 2019 2020 // notInHeap is off-heap memory allocated by a lower-level allocator 2021 // like sysAlloc or persistentAlloc. 2022 // 2023 // In general, it's better to use real types which embed 2024 // internal/runtime/sys.NotInHeap, but this serves as a generic type 2025 // for situations where that isn't possible (like in the allocators). 2026 // 2027 // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc? 2028 type notInHeap struct{ _ sys.NotInHeap } 2029 2030 func (p *notInHeap) add(bytes uintptr) *notInHeap { 2031 return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes)) 2032 } 2033 2034 // redZoneSize computes the size of the redzone for a given allocation. 2035 // Refer to the implementation of the compiler-rt. 2036 func redZoneSize(userSize uintptr) uintptr { 2037 switch { 2038 case userSize <= (64 - 16): 2039 return 16 << 0 2040 case userSize <= (128 - 32): 2041 return 16 << 1 2042 case userSize <= (512 - 64): 2043 return 16 << 2 2044 case userSize <= (4096 - 128): 2045 return 16 << 3 2046 case userSize <= (1<<14)-256: 2047 return 16 << 4 2048 case userSize <= (1<<15)-512: 2049 return 16 << 5 2050 case userSize <= (1<<16)-1024: 2051 return 16 << 6 2052 default: 2053 return 16 << 7 2054 } 2055 } 2056