Source file src/runtime/mheap.go
1 // Copyright 2009 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 // Page heap. 6 // 7 // See malloc.go for overview. 8 9 package runtime 10 11 import ( 12 "internal/abi" 13 "internal/cpu" 14 "internal/goarch" 15 "internal/goexperiment" 16 "internal/runtime/atomic" 17 "internal/runtime/gc" 18 "internal/runtime/sys" 19 "unsafe" 20 ) 21 22 const ( 23 // minPhysPageSize is a lower-bound on the physical page size. The 24 // true physical page size may be larger than this. In contrast, 25 // sys.PhysPageSize is an upper-bound on the physical page size. 26 minPhysPageSize = 4096 27 28 // maxPhysPageSize is the maximum page size the runtime supports. 29 maxPhysPageSize = 512 << 10 30 31 // maxPhysHugePageSize sets an upper-bound on the maximum huge page size 32 // that the runtime supports. 33 maxPhysHugePageSize = pallocChunkBytes 34 35 // pagesPerReclaimerChunk indicates how many pages to scan from the 36 // pageInUse bitmap at a time. Used by the page reclaimer. 37 // 38 // Higher values reduce contention on scanning indexes (such as 39 // h.reclaimIndex), but increase the minimum latency of the 40 // operation. 41 // 42 // The time required to scan this many pages can vary a lot depending 43 // on how many spans are actually freed. Experimentally, it can 44 // scan for pages at ~300 GB/ms on a 2.6GHz Core i7, but can only 45 // free spans at ~32 MB/ms. Using 512 pages bounds this at 46 // roughly 100µs. 47 // 48 // Must be a multiple of the pageInUse bitmap element size and 49 // must also evenly divide pagesPerArena. 50 pagesPerReclaimerChunk = min(512, pagesPerArena) 51 52 // physPageAlignedStacks indicates whether stack allocations must be 53 // physical page aligned. This is a requirement for MAP_STACK on 54 // OpenBSD. 55 physPageAlignedStacks = GOOS == "openbsd" 56 ) 57 58 // Main malloc heap. 59 // The heap use pageAlloc to manage free and scavenged pages, 60 // but all the other global data is here too. 61 // 62 // mheap must not be heap-allocated because it contains mSpanLists, 63 // which must not be heap-allocated. 64 type mheap struct { 65 _ sys.NotInHeap 66 67 // lock must only be acquired on the system stack, otherwise a g 68 // could self-deadlock if its stack grows with the lock held. 69 lock mutex 70 71 pages pageAlloc // page allocation data structure 72 73 sweepgen uint32 // sweep generation, see comment in mspan; written during STW 74 75 // allspans is a slice of all mspans ever created. Each mspan 76 // appears exactly once. 77 // 78 // The memory for allspans is manually managed and can be 79 // reallocated and move as the heap grows. 80 // 81 // In general, allspans is protected by mheap_.lock, which 82 // prevents concurrent access as well as freeing the backing 83 // store. Accesses during STW might not hold the lock, but 84 // must ensure that allocation cannot happen around the 85 // access (since that may free the backing store). 86 allspans []*mspan // all spans out there 87 88 // Proportional sweep 89 // 90 // These parameters represent a linear function from gcController.heapLive 91 // to page sweep count. The proportional sweep system works to 92 // stay in the black by keeping the current page sweep count 93 // above this line at the current gcController.heapLive. 94 // 95 // The line has slope sweepPagesPerByte and passes through a 96 // basis point at (sweepHeapLiveBasis, pagesSweptBasis). At 97 // any given time, the system is at (gcController.heapLive, 98 // pagesSwept) in this space. 99 // 100 // It is important that the line pass through a point we 101 // control rather than simply starting at a 0,0 origin 102 // because that lets us adjust sweep pacing at any time while 103 // accounting for current progress. If we could only adjust 104 // the slope, it would create a discontinuity in debt if any 105 // progress has already been made. 106 pagesInUse atomic.Uintptr // pages of spans in stats mSpanInUse 107 pagesSwept atomic.Uint64 // pages swept this cycle 108 pagesSweptBasis atomic.Uint64 // pagesSwept to use as the origin of the sweep ratio 109 sweepHeapLiveBasis uint64 // value of gcController.heapLive to use as the origin of sweep ratio; written with lock, read without 110 sweepPagesPerByte float64 // proportional sweep ratio; written with lock, read without 111 112 // Page reclaimer state 113 114 // reclaimIndex is the page index in heapArenas of next page to 115 // reclaim. Specifically, it refers to page (i % 116 // pagesPerArena) of arena heapArenas[i / pagesPerArena]. 117 // 118 // If this is >= 1<<63, the page reclaimer is done scanning 119 // the page marks. 120 reclaimIndex atomic.Uint64 121 122 // reclaimCredit is spare credit for extra pages swept. Since 123 // the page reclaimer works in large chunks, it may reclaim 124 // more than requested. Any spare pages released go to this 125 // credit pool. 126 reclaimCredit atomic.Uintptr 127 128 _ cpu.CacheLinePad // prevents false-sharing between arenas and preceding variables 129 130 // arenas is the heap arena map. It points to the metadata for 131 // the heap for every arena frame of the entire usable virtual 132 // address space. 133 // 134 // Use arenaIndex to compute indexes into this array. 135 // 136 // For regions of the address space that are not backed by the 137 // Go heap, the arena map contains nil. 138 // 139 // Modifications are protected by mheap_.lock. Reads can be 140 // performed without locking; however, a given entry can 141 // transition from nil to non-nil at any time when the lock 142 // isn't held. (Entries never transitions back to nil.) 143 // 144 // In general, this is a two-level mapping consisting of an L1 145 // map and possibly many L2 maps. This saves space when there 146 // are a huge number of arena frames. However, on many 147 // platforms (even 64-bit), arenaL1Bits is 0, making this 148 // effectively a single-level map. In this case, arenas[0] 149 // will never be nil. 150 arenas [1 << arenaL1Bits]*[1 << arenaL2Bits]*heapArena 151 152 // arenasHugePages indicates whether arenas' L2 entries are eligible 153 // to be backed by huge pages. 154 arenasHugePages bool 155 156 // heapArenaAlloc is pre-reserved space for allocating heapArena 157 // objects. This is only used on 32-bit, where we pre-reserve 158 // this space to avoid interleaving it with the heap itself. 159 heapArenaAlloc linearAlloc 160 161 // arenaHints is a list of addresses at which to attempt to 162 // add more heap arenas. This is initially populated with a 163 // set of general hint addresses, and grown with the bounds of 164 // actual heap arena ranges. 165 arenaHints *arenaHint 166 167 // arena is a pre-reserved space for allocating heap arenas 168 // (the actual arenas). This is only used on 32-bit. 169 arena linearAlloc 170 171 // heapArenas is the arenaIndex of every mapped arena mapped for the heap. 172 // This can be used to iterate through the heap address space. 173 // 174 // Access is protected by mheap_.lock. However, since this is 175 // append-only and old backing arrays are never freed, it is 176 // safe to acquire mheap_.lock, copy the slice header, and 177 // then release mheap_.lock. 178 heapArenas []arenaIdx 179 180 // userArenaArenas is the arenaIndex of every mapped arena mapped for 181 // user arenas. 182 // 183 // Access is protected by mheap_.lock. However, since this is 184 // append-only and old backing arrays are never freed, it is 185 // safe to acquire mheap_.lock, copy the slice header, and 186 // then release mheap_.lock. 187 userArenaArenas []arenaIdx 188 189 // sweepArenas is a snapshot of heapArenas taken at the 190 // beginning of the sweep cycle. This can be read safely by 191 // simply blocking GC (by disabling preemption). 192 sweepArenas []arenaIdx 193 194 // markArenas is a snapshot of heapArenas taken at the beginning 195 // of the mark cycle. Because heapArenas is append-only, neither 196 // this slice nor its contents will change during the mark, so 197 // it can be read safely. 198 markArenas []arenaIdx 199 200 // curArena is the arena that the heap is currently growing 201 // into. This should always be physPageSize-aligned. 202 curArena struct { 203 base, end uintptr 204 } 205 206 // central free lists for small size classes. 207 // the padding makes sure that the mcentrals are 208 // spaced CacheLinePadSize bytes apart, so that each mcentral.lock 209 // gets its own cache line. 210 // central is indexed by spanClass. 211 central [numSpanClasses]struct { 212 mcentral mcentral 213 pad [(cpu.CacheLinePadSize - unsafe.Sizeof(mcentral{})%cpu.CacheLinePadSize) % cpu.CacheLinePadSize]byte 214 } 215 216 spanalloc fixalloc // allocator for span 217 spanSPMCAlloc fixalloc // allocator for spanSPMC, protected by work.spanSPMCs.lock 218 cachealloc fixalloc // allocator for mcache 219 specialfinalizeralloc fixalloc // allocator for specialfinalizer 220 specialCleanupAlloc fixalloc // allocator for specialCleanup 221 specialCheckFinalizerAlloc fixalloc // allocator for specialCheckFinalizer 222 specialTinyBlockAlloc fixalloc // allocator for specialTinyBlock 223 specialprofilealloc fixalloc // allocator for specialprofile 224 specialReachableAlloc fixalloc // allocator for specialReachable 225 specialPinCounterAlloc fixalloc // allocator for specialPinCounter 226 specialWeakHandleAlloc fixalloc // allocator for specialWeakHandle 227 specialBubbleAlloc fixalloc // allocator for specialBubble 228 specialSecretAlloc fixalloc // allocator for specialSecret 229 speciallock mutex // lock for special record allocators. 230 arenaHintAlloc fixalloc // allocator for arenaHints 231 232 // User arena state. 233 // 234 // Protected by mheap_.lock. 235 userArena struct { 236 // arenaHints is a list of addresses at which to attempt to 237 // add more heap arenas for user arena chunks. This is initially 238 // populated with a set of general hint addresses, and grown with 239 // the bounds of actual heap arena ranges. 240 arenaHints *arenaHint 241 242 // quarantineList is a list of user arena spans that have been set to fault, but 243 // are waiting for all pointers into them to go away. Sweeping handles 244 // identifying when this is true, and moves the span to the ready list. 245 quarantineList mSpanList 246 247 // readyList is a list of empty user arena spans that are ready for reuse. 248 readyList mSpanList 249 } 250 251 // cleanupID is a counter which is incremented each time a cleanup special is added 252 // to a span. It's used to create globally unique identifiers for individual cleanup. 253 // cleanupID is protected by mheap_.speciallock. It must only be incremented while holding 254 // the lock. ID 0 is reserved. Users should increment first, then read the value. 255 cleanupID uint64 256 257 _ cpu.CacheLinePad 258 259 immortalWeakHandles immortalWeakHandleMap 260 261 unused *specialfinalizer // never set, just here to force the specialfinalizer type into DWARF 262 } 263 264 var mheap_ mheap 265 266 // A heapArena stores metadata for a heap arena. heapArenas are stored 267 // outside of the Go heap and accessed via the mheap_.arenas index. 268 type heapArena struct { 269 _ sys.NotInHeap 270 271 // spans maps from virtual address page ID within this arena to *mspan. 272 // For allocated spans, their pages map to the span itself. 273 // For free spans, only the lowest and highest pages map to the span itself. 274 // Internal pages map to an arbitrary span. 275 // For pages that have never been allocated, spans entries are nil. 276 // 277 // Modifications are protected by mheap.lock. Reads can be 278 // performed without locking, but ONLY from indexes that are 279 // known to contain in-use or stack spans. This means there 280 // must not be a safe-point between establishing that an 281 // address is live and looking it up in the spans array. 282 spans [pagesPerArena]*mspan 283 284 // pageInUse is a bitmap that indicates which spans are in 285 // state mSpanInUse. This bitmap is indexed by page number, 286 // but only the bit corresponding to the first page in each 287 // span is used. 288 // 289 // Reads and writes are atomic. 290 pageInUse [pagesPerArena / 8]uint8 291 292 // pageMarks is a bitmap that indicates which spans have any 293 // marked objects on them. Like pageInUse, only the bit 294 // corresponding to the first page in each span is used. 295 // 296 // Writes are done atomically during marking. Reads are 297 // non-atomic and lock-free since they only occur during 298 // sweeping (and hence never race with writes). 299 // 300 // This is used to quickly find whole spans that can be freed. 301 // 302 // TODO(austin): It would be nice if this was uint64 for 303 // faster scanning, but we don't have 64-bit atomic bit 304 // operations. 305 pageMarks [pagesPerArena / 8]uint8 306 307 // pageSpecials is a bitmap that indicates which spans have 308 // specials (finalizers or other). Like pageInUse, only the bit 309 // corresponding to the first page in each span is used. 310 // 311 // The bit is set atomically when the first special is added to 312 // a span and cleared when the last special is removed from a span. 313 // Reads are done atomically to find spans containing specials 314 // during marking. 315 pageSpecials [pagesPerArena / 8]uint8 316 317 // pageUseSpanInlineMarkBits is a bitmap where each bit corresponds 318 // to a span, as only spans one page in size can have inline mark bits. 319 // The bit indicates that the span has a spanInlineMarkBits struct 320 // stored directly at the top end of the span's memory. 321 pageUseSpanInlineMarkBits [pagesPerArena / 8]uint8 322 323 // checkmarks stores the debug.gccheckmark state. It is only 324 // used if debug.gccheckmark > 0 or debug.checkfinalizers > 0. 325 checkmarks *checkmarksMap 326 327 // zeroedBase marks the first byte of the first page in this 328 // arena which hasn't been used yet and is therefore already 329 // zero. zeroedBase is relative to the arena base. 330 // Increases monotonically until it hits heapArenaBytes. 331 // 332 // This field is sufficient to determine if an allocation 333 // needs to be zeroed because the page allocator follows an 334 // address-ordered first-fit policy. 335 // 336 // Read atomically and written with an atomic CAS. 337 zeroedBase uintptr 338 } 339 340 // arenaHint is a hint for where to grow the heap arenas. See 341 // mheap_.arenaHints. 342 type arenaHint struct { 343 _ sys.NotInHeap 344 addr uintptr 345 down bool 346 next *arenaHint 347 } 348 349 // An mspan is a run of pages. 350 // 351 // When a mspan is in the heap free treap, state == mSpanFree 352 // and heapmap(s->start) == span, heapmap(s->start+s->npages-1) == span. 353 // If the mspan is in the heap scav treap, then in addition to the 354 // above scavenged == true. scavenged == false in all other cases. 355 // 356 // When a mspan is allocated, state == mSpanInUse or mSpanManual 357 // and heapmap(i) == span for all s->start <= i < s->start+s->npages. 358 359 // Every mspan is in one doubly-linked list, either in the mheap's 360 // busy list or one of the mcentral's span lists. 361 362 // An mspan representing actual memory has state mSpanInUse, 363 // mSpanManual, or mSpanFree. Transitions between these states are 364 // constrained as follows: 365 // 366 // - A span may transition from free to in-use or manual during any GC 367 // phase. 368 // 369 // - During sweeping (gcphase == _GCoff), a span may transition from 370 // in-use to free (as a result of sweeping) or manual to free (as a 371 // result of stacks being freed). 372 // 373 // - During GC (gcphase != _GCoff), a span *must not* transition from 374 // manual or in-use to free. Because concurrent GC may read a pointer 375 // and then look up its span, the span state must be monotonic. 376 // 377 // Setting mspan.state to mSpanInUse or mSpanManual must be done 378 // atomically and only after all other span fields are valid. 379 // Likewise, if inspecting a span is contingent on it being 380 // mSpanInUse, the state should be loaded atomically and checked 381 // before depending on other fields. This allows the garbage collector 382 // to safely deal with potentially invalid pointers, since resolving 383 // such pointers may race with a span being allocated. 384 type mSpanState uint8 385 386 const ( 387 mSpanDead mSpanState = iota 388 mSpanInUse // allocated for garbage collected heap 389 mSpanManual // allocated for manual management (e.g., stack allocator) 390 ) 391 392 // mSpanStateNames are the names of the span states, indexed by 393 // mSpanState. 394 var mSpanStateNames = []string{ 395 "mSpanDead", 396 "mSpanInUse", 397 "mSpanManual", 398 } 399 400 // mSpanStateBox holds an atomic.Uint8 to provide atomic operations on 401 // an mSpanState. This is a separate type to disallow accidental comparison 402 // or assignment with mSpanState. 403 type mSpanStateBox struct { 404 s atomic.Uint8 405 } 406 407 // It is nosplit to match get, below. 408 409 //go:nosplit 410 func (b *mSpanStateBox) set(s mSpanState) { 411 b.s.Store(uint8(s)) 412 } 413 414 // It is nosplit because it's called indirectly by typedmemclr, 415 // which must not be preempted. 416 417 //go:nosplit 418 func (b *mSpanStateBox) get() mSpanState { 419 return mSpanState(b.s.Load()) 420 } 421 422 type mspan struct { 423 _ sys.NotInHeap 424 next *mspan // next span in list, or nil if none 425 prev *mspan // previous span in list, or nil if none 426 list *mSpanList // For debugging. 427 428 startAddr uintptr // address of first byte of span aka s.base() 429 npages uintptr // number of pages in span 430 431 manualFreeList gclinkptr // list of free objects in mSpanManual spans 432 433 // freeindex is the slot index between 0 and nelems at which to begin scanning 434 // for the next free object in this span. 435 // Each allocation scans allocBits starting at freeindex until it encounters a 0 436 // indicating a free object. freeindex is then adjusted so that subsequent scans begin 437 // just past the newly discovered free object. 438 // 439 // If freeindex == nelems, this span has no free objects, though might have reusable objects. 440 // 441 // allocBits is a bitmap of objects in this span. 442 // If n >= freeindex and allocBits[n/8] & (1<<(n%8)) is 0 443 // then object n is free; 444 // otherwise, object n is allocated. Bits starting at nelems are 445 // undefined and should never be referenced. 446 // 447 // Object n starts at address n*elemsize + (start << pageShift). 448 freeindex uint16 449 // TODO: Look up nelems from sizeclass and remove this field if it 450 // helps performance. 451 nelems uint16 // number of object in the span. 452 // freeIndexForScan is like freeindex, except that freeindex is 453 // used by the allocator whereas freeIndexForScan is used by the 454 // GC scanner. They are two fields so that the GC sees the object 455 // is allocated only when the object and the heap bits are 456 // initialized (see also the assignment of freeIndexForScan in 457 // mallocgc, and issue 54596). 458 freeIndexForScan uint16 459 460 // Cache of the allocBits at freeindex. allocCache is shifted 461 // such that the lowest bit corresponds to the bit freeindex. 462 // allocCache holds the complement of allocBits, thus allowing 463 // ctz (count trailing zero) to use it directly. 464 // allocCache may contain bits beyond s.nelems; the caller must ignore 465 // these. 466 allocCache uint64 467 468 // allocBits and gcmarkBits hold pointers to a span's mark and 469 // allocation bits. The pointers are 8 byte aligned. 470 // There are three arenas where this data is held. 471 // free: Dirty arenas that are no longer accessed 472 // and can be reused. 473 // next: Holds information to be used in the next GC cycle. 474 // current: Information being used during this GC cycle. 475 // previous: Information being used during the last GC cycle. 476 // A new GC cycle starts with the call to finishsweep_m. 477 // finishsweep_m moves the previous arena to the free arena, 478 // the current arena to the previous arena, and 479 // the next arena to the current arena. 480 // The next arena is populated as the spans request 481 // memory to hold gcmarkBits for the next GC cycle as well 482 // as allocBits for newly allocated spans. 483 // 484 // The pointer arithmetic is done "by hand" instead of using 485 // arrays to avoid bounds checks along critical performance 486 // paths. 487 // The sweep will free the old allocBits and set allocBits to the 488 // gcmarkBits. The gcmarkBits are replaced with a fresh zeroed 489 // out memory. 490 allocBits *gcBits 491 gcmarkBits *gcBits 492 pinnerBits *gcBits // bitmap for pinned objects; accessed atomically 493 494 // sweep generation: 495 // if sweepgen == h->sweepgen - 2, the span needs sweeping 496 // if sweepgen == h->sweepgen - 1, the span is currently being swept 497 // if sweepgen == h->sweepgen, the span is swept and ready to use 498 // if sweepgen == h->sweepgen + 1, the span was cached before sweep began and is still cached, and needs sweeping 499 // if sweepgen == h->sweepgen + 3, the span was swept and then cached and is still cached 500 // h->sweepgen is incremented by 2 after every GC 501 502 sweepgen uint32 503 divMul uint32 // for divide by elemsize 504 allocCount uint16 // number of allocated objects 505 spanclass spanClass // size class and noscan (uint8) 506 state mSpanStateBox // mSpanInUse etc; accessed atomically (get/set methods) 507 needzero uint8 // needs to be zeroed before allocation 508 isUserArenaChunk bool // whether or not this span represents a user arena 509 allocCountBeforeCache uint16 // a copy of allocCount that is stored just before this span is cached 510 elemsize uintptr // computed from sizeclass or from npages 511 limit uintptr // end of data in span 512 speciallock mutex // guards specials list and changes to pinnerBits 513 specials *special // linked list of special records sorted by offset. 514 userArenaChunkFree addrRange // interval for managing chunk allocation 515 largeType *_type // malloc header for large objects. 516 } 517 518 func (s *mspan) base() uintptr { 519 return s.startAddr 520 } 521 522 // recordspan adds a newly allocated span to h.allspans. 523 // 524 // This only happens the first time a span is allocated from 525 // mheap.spanalloc (it is not called when a span is reused). 526 // 527 // Write barriers are disallowed here because it can be called from 528 // gcWork when allocating new workbufs. However, because it's an 529 // indirect call from the fixalloc initializer, the compiler can't see 530 // this. 531 // 532 // The heap lock must be held. 533 // 534 //go:nowritebarrierrec 535 func recordspan(vh unsafe.Pointer, p unsafe.Pointer) { 536 h := (*mheap)(vh) 537 s := (*mspan)(p) 538 539 assertLockHeld(&h.lock) 540 541 if len(h.allspans) >= cap(h.allspans) { 542 n := 64 * 1024 / goarch.PtrSize 543 if n < cap(h.allspans)*3/2 { 544 n = cap(h.allspans) * 3 / 2 545 } 546 var new []*mspan 547 sp := (*slice)(unsafe.Pointer(&new)) 548 sp.array = sysAlloc(uintptr(n)*goarch.PtrSize, &memstats.other_sys, "allspans array") 549 if sp.array == nil { 550 throw("runtime: cannot allocate memory") 551 } 552 sp.len = len(h.allspans) 553 sp.cap = n 554 if len(h.allspans) > 0 { 555 copy(new, h.allspans) 556 } 557 oldAllspans := h.allspans 558 *(*notInHeapSlice)(unsafe.Pointer(&h.allspans)) = *(*notInHeapSlice)(unsafe.Pointer(&new)) 559 if len(oldAllspans) != 0 { 560 sysFree(unsafe.Pointer(&oldAllspans[0]), uintptr(cap(oldAllspans))*unsafe.Sizeof(oldAllspans[0]), &memstats.other_sys) 561 } 562 } 563 h.allspans = h.allspans[:len(h.allspans)+1] 564 h.allspans[len(h.allspans)-1] = s 565 } 566 567 // A spanClass represents the size class and noscan-ness of a span. 568 // 569 // Each size class has a noscan spanClass and a scan spanClass. The 570 // noscan spanClass contains only noscan objects, which do not contain 571 // pointers and thus do not need to be scanned by the garbage 572 // collector. 573 type spanClass uint8 574 575 const ( 576 numSpanClasses = gc.NumSizeClasses << 1 577 tinySpanClass = spanClass(tinySizeClass<<1 | 1) 578 ) 579 580 func makeSpanClass(sizeclass uint8, noscan bool) spanClass { 581 return spanClass(sizeclass<<1) | spanClass(bool2int(noscan)) 582 } 583 584 //go:nosplit 585 func (sc spanClass) sizeclass() int8 { 586 return int8(sc >> 1) 587 } 588 589 //go:nosplit 590 func (sc spanClass) noscan() bool { 591 return sc&1 != 0 592 } 593 594 // arenaIndex returns the index into mheap_.arenas of the arena 595 // containing metadata for p. This index combines of an index into the 596 // L1 map and an index into the L2 map and should be used as 597 // mheap_.arenas[ai.l1()][ai.l2()]. 598 // 599 // If p is outside the range of valid heap addresses, either l1() or 600 // l2() will be out of bounds. 601 // 602 // It is nosplit because it's called by spanOf and several other 603 // nosplit functions. 604 // 605 //go:nosplit 606 func arenaIndex(p uintptr) arenaIdx { 607 return arenaIdx((p - arenaBaseOffset) / heapArenaBytes) 608 } 609 610 // arenaBase returns the low address of the region covered by heap 611 // arena i. 612 func arenaBase(i arenaIdx) uintptr { 613 return uintptr(i)*heapArenaBytes + arenaBaseOffset 614 } 615 616 type arenaIdx uint 617 618 // l1 returns the "l1" portion of an arenaIdx. 619 // 620 // Marked nosplit because it's called by spanOf and other nosplit 621 // functions. 622 // 623 //go:nosplit 624 func (i arenaIdx) l1() uint { 625 if arenaL1Bits == 0 { 626 // Let the compiler optimize this away if there's no 627 // L1 map. 628 return 0 629 } else { 630 return uint(i) >> arenaL1Shift 631 } 632 } 633 634 // l2 returns the "l2" portion of an arenaIdx. 635 // 636 // Marked nosplit because it's called by spanOf and other nosplit funcs. 637 // functions. 638 // 639 //go:nosplit 640 func (i arenaIdx) l2() uint { 641 if arenaL1Bits == 0 { 642 return uint(i) 643 } else { 644 return uint(i) & (1<<arenaL2Bits - 1) 645 } 646 } 647 648 // inheap reports whether b is a pointer into a (potentially dead) heap object. 649 // It returns false for pointers into mSpanManual spans. 650 // Non-preemptible because it is used by write barriers. 651 // 652 //go:nowritebarrier 653 //go:nosplit 654 func inheap(b uintptr) bool { 655 return spanOfHeap(b) != nil 656 } 657 658 // inHeapOrStack is a variant of inheap that returns true for pointers 659 // into any allocated heap span. 660 // 661 //go:nowritebarrier 662 //go:nosplit 663 func inHeapOrStack(b uintptr) bool { 664 s := spanOf(b) 665 if s == nil || b < s.base() { 666 return false 667 } 668 switch s.state.get() { 669 case mSpanInUse, mSpanManual: 670 return b < s.limit 671 default: 672 return false 673 } 674 } 675 676 // spanOf returns the span of p. If p does not point into the heap 677 // arena or no span has ever contained p, spanOf returns nil. 678 // 679 // If p does not point to allocated memory, this may return a non-nil 680 // span that does *not* contain p. If this is a possibility, the 681 // caller should either call spanOfHeap or check the span bounds 682 // explicitly. 683 // 684 // Must be nosplit because it has callers that are nosplit. 685 // 686 //go:nosplit 687 func spanOf(p uintptr) *mspan { 688 // This function looks big, but we use a lot of constant 689 // folding around arenaL1Bits to get it under the inlining 690 // budget. Also, many of the checks here are safety checks 691 // that Go needs to do anyway, so the generated code is quite 692 // short. 693 ri := arenaIndex(p) 694 if arenaL1Bits == 0 { 695 // If there's no L1, then ri.l1() can't be out of bounds but ri.l2() can. 696 if ri.l2() >= uint(len(mheap_.arenas[0])) { 697 return nil 698 } 699 } else { 700 // If there's an L1, then ri.l1() can be out of bounds but ri.l2() can't. 701 if ri.l1() >= uint(len(mheap_.arenas)) { 702 return nil 703 } 704 } 705 l2 := mheap_.arenas[ri.l1()] 706 if arenaL1Bits != 0 && l2 == nil { // Should never happen if there's no L1. 707 return nil 708 } 709 ha := l2[ri.l2()] 710 if ha == nil { 711 return nil 712 } 713 return ha.spans[(p/pageSize)%pagesPerArena] 714 } 715 716 // spanOfUnchecked is equivalent to spanOf, but the caller must ensure 717 // that p points into an allocated heap arena. 718 // 719 // Must be nosplit because it has callers that are nosplit. 720 // 721 //go:nosplit 722 func spanOfUnchecked(p uintptr) *mspan { 723 ai := arenaIndex(p) 724 return mheap_.arenas[ai.l1()][ai.l2()].spans[(p/pageSize)%pagesPerArena] 725 } 726 727 // spanOfHeap is like spanOf, but returns nil if p does not point to a 728 // heap object. 729 // 730 // Must be nosplit because it has callers that are nosplit. 731 // 732 //go:nosplit 733 func spanOfHeap(p uintptr) *mspan { 734 s := spanOf(p) 735 // s is nil if it's never been allocated. Otherwise, we check 736 // its state first because we don't trust this pointer, so we 737 // have to synchronize with span initialization. Then, it's 738 // still possible we picked up a stale span pointer, so we 739 // have to check the span's bounds. 740 if s == nil || s.state.get() != mSpanInUse || p < s.base() || p >= s.limit { 741 return nil 742 } 743 return s 744 } 745 746 // pageIndexOf returns the arena, page index, and page mask for pointer p. 747 // The caller must ensure p is in the heap. 748 func pageIndexOf(p uintptr) (arena *heapArena, pageIdx uintptr, pageMask uint8) { 749 ai := arenaIndex(p) 750 arena = mheap_.arenas[ai.l1()][ai.l2()] 751 pageIdx = ((p / pageSize) / 8) % uintptr(len(arena.pageInUse)) 752 pageMask = byte(1 << ((p / pageSize) % 8)) 753 return 754 } 755 756 // heapArenaOf returns the heap arena for p, if one exists. 757 func heapArenaOf(p uintptr) *heapArena { 758 ri := arenaIndex(p) 759 if arenaL1Bits == 0 { 760 // If there's no L1, then ri.l1() can't be out of bounds but ri.l2() can. 761 if ri.l2() >= uint(len(mheap_.arenas[0])) { 762 return nil 763 } 764 } else { 765 // If there's an L1, then ri.l1() can be out of bounds but ri.l2() can't. 766 if ri.l1() >= uint(len(mheap_.arenas)) { 767 return nil 768 } 769 } 770 l2 := mheap_.arenas[ri.l1()] 771 if arenaL1Bits != 0 && l2 == nil { // Should never happen if there's no L1. 772 return nil 773 } 774 return l2[ri.l2()] 775 } 776 777 // Initialize the heap. 778 func (h *mheap) init() { 779 lockInit(&h.lock, lockRankMheap) 780 lockInit(&h.speciallock, lockRankMheapSpecial) 781 782 h.spanalloc.init(unsafe.Sizeof(mspan{}), recordspan, unsafe.Pointer(h), &memstats.mspan_sys) 783 h.spanSPMCAlloc.init(unsafe.Sizeof(spanSPMC{}), nil, nil, &memstats.gcMiscSys) 784 h.cachealloc.init(unsafe.Sizeof(mcache{}), nil, nil, &memstats.mcache_sys) 785 h.specialfinalizeralloc.init(unsafe.Sizeof(specialfinalizer{}), nil, nil, &memstats.other_sys) 786 h.specialCleanupAlloc.init(unsafe.Sizeof(specialCleanup{}), nil, nil, &memstats.other_sys) 787 h.specialCheckFinalizerAlloc.init(unsafe.Sizeof(specialCheckFinalizer{}), nil, nil, &memstats.other_sys) 788 h.specialTinyBlockAlloc.init(unsafe.Sizeof(specialTinyBlock{}), nil, nil, &memstats.other_sys) 789 h.specialprofilealloc.init(unsafe.Sizeof(specialprofile{}), nil, nil, &memstats.other_sys) 790 h.specialReachableAlloc.init(unsafe.Sizeof(specialReachable{}), nil, nil, &memstats.other_sys) 791 h.specialPinCounterAlloc.init(unsafe.Sizeof(specialPinCounter{}), nil, nil, &memstats.other_sys) 792 h.specialSecretAlloc.init(unsafe.Sizeof(specialSecret{}), nil, nil, &memstats.other_sys) 793 h.specialWeakHandleAlloc.init(unsafe.Sizeof(specialWeakHandle{}), nil, nil, &memstats.gcMiscSys) 794 h.specialBubbleAlloc.init(unsafe.Sizeof(specialBubble{}), nil, nil, &memstats.other_sys) 795 h.arenaHintAlloc.init(unsafe.Sizeof(arenaHint{}), nil, nil, &memstats.other_sys) 796 797 // Don't zero mspan allocations. Background sweeping can 798 // inspect a span concurrently with allocating it, so it's 799 // important that the span's sweepgen survive across freeing 800 // and re-allocating a span to prevent background sweeping 801 // from improperly cas'ing it from 0. 802 // 803 // This is safe because mspan contains no heap pointers. 804 h.spanalloc.zero = false 805 806 // h->mapcache needs no init 807 808 for i := range h.central { 809 h.central[i].mcentral.init(spanClass(i)) 810 } 811 812 h.pages.init(&h.lock, &memstats.gcMiscSys, false) 813 814 xRegInitAlloc() 815 } 816 817 // reclaim sweeps and reclaims at least npage pages into the heap. 818 // It is called before allocating npage pages to keep growth in check. 819 // 820 // reclaim implements the page-reclaimer half of the sweeper. 821 // 822 // h.lock must NOT be held. 823 func (h *mheap) reclaim(npage uintptr) { 824 // TODO(austin): Half of the time spent freeing spans is in 825 // locking/unlocking the heap (even with low contention). We 826 // could make the slow path here several times faster by 827 // batching heap frees. 828 829 // Bail early if there's no more reclaim work. 830 if h.reclaimIndex.Load() >= 1<<63 { 831 return 832 } 833 834 // Disable preemption so the GC can't start while we're 835 // sweeping, so we can read h.sweepArenas, and so 836 // traceGCSweepStart/Done pair on the P. 837 mp := acquirem() 838 839 trace := traceAcquire() 840 if trace.ok() { 841 trace.GCSweepStart() 842 traceRelease(trace) 843 } 844 845 arenas := h.sweepArenas 846 locked := false 847 for npage > 0 { 848 // Pull from accumulated credit first. 849 if credit := h.reclaimCredit.Load(); credit > 0 { 850 take := credit 851 if take > npage { 852 // Take only what we need. 853 take = npage 854 } 855 if h.reclaimCredit.CompareAndSwap(credit, credit-take) { 856 npage -= take 857 } 858 continue 859 } 860 861 // Claim a chunk of work. 862 idx := uintptr(h.reclaimIndex.Add(pagesPerReclaimerChunk) - pagesPerReclaimerChunk) 863 if idx/pagesPerArena >= uintptr(len(arenas)) { 864 // Page reclaiming is done. 865 h.reclaimIndex.Store(1 << 63) 866 break 867 } 868 869 if !locked { 870 // Lock the heap for reclaimChunk. 871 lock(&h.lock) 872 locked = true 873 } 874 875 // Scan this chunk. 876 nfound := h.reclaimChunk(arenas, idx, pagesPerReclaimerChunk) 877 if nfound <= npage { 878 npage -= nfound 879 } else { 880 // Put spare pages toward global credit. 881 h.reclaimCredit.Add(nfound - npage) 882 npage = 0 883 } 884 } 885 if locked { 886 unlock(&h.lock) 887 } 888 889 trace = traceAcquire() 890 if trace.ok() { 891 trace.GCSweepDone() 892 traceRelease(trace) 893 } 894 releasem(mp) 895 } 896 897 // reclaimChunk sweeps unmarked spans that start at page indexes [pageIdx, pageIdx+n). 898 // It returns the number of pages returned to the heap. 899 // 900 // h.lock must be held and the caller must be non-preemptible. Note: h.lock may be 901 // temporarily unlocked and re-locked in order to do sweeping or if tracing is 902 // enabled. 903 func (h *mheap) reclaimChunk(arenas []arenaIdx, pageIdx, n uintptr) uintptr { 904 // The heap lock must be held because this accesses the 905 // heapArena.spans arrays using potentially non-live pointers. 906 // In particular, if a span were freed and merged concurrently 907 // with this probing heapArena.spans, it would be possible to 908 // observe arbitrary, stale span pointers. 909 assertLockHeld(&h.lock) 910 911 n0 := n 912 var nFreed uintptr 913 sl := sweep.active.begin() 914 if !sl.valid { 915 return 0 916 } 917 for n > 0 { 918 ai := arenas[pageIdx/pagesPerArena] 919 ha := h.arenas[ai.l1()][ai.l2()] 920 921 // Get a chunk of the bitmap to work on. 922 arenaPage := uint(pageIdx % pagesPerArena) 923 inUse := ha.pageInUse[arenaPage/8:] 924 marked := ha.pageMarks[arenaPage/8:] 925 if uintptr(len(inUse)) > n/8 { 926 inUse = inUse[:n/8] 927 marked = marked[:n/8] 928 } 929 930 // Scan this bitmap chunk for spans that are in-use 931 // but have no marked objects on them. 932 for i := range inUse { 933 inUseUnmarked := atomic.Load8(&inUse[i]) &^ marked[i] 934 if inUseUnmarked == 0 { 935 continue 936 } 937 938 for j := uint(0); j < 8; j++ { 939 if inUseUnmarked&(1<<j) != 0 { 940 s := ha.spans[arenaPage+uint(i)*8+j] 941 if s, ok := sl.tryAcquire(s); ok { 942 npages := s.npages 943 unlock(&h.lock) 944 if s.sweep(false) { 945 nFreed += npages 946 } 947 lock(&h.lock) 948 // Reload inUse. It's possible nearby 949 // spans were freed when we dropped the 950 // lock and we don't want to get stale 951 // pointers from the spans array. 952 inUseUnmarked = atomic.Load8(&inUse[i]) &^ marked[i] 953 } 954 } 955 } 956 } 957 958 // Advance. 959 pageIdx += uintptr(len(inUse) * 8) 960 n -= uintptr(len(inUse) * 8) 961 } 962 sweep.active.end(sl) 963 trace := traceAcquire() 964 if trace.ok() { 965 unlock(&h.lock) 966 // Account for pages scanned but not reclaimed. 967 trace.GCSweepSpan((n0 - nFreed) * pageSize) 968 traceRelease(trace) 969 lock(&h.lock) 970 } 971 972 assertLockHeld(&h.lock) // Must be locked on return. 973 return nFreed 974 } 975 976 // spanAllocType represents the type of allocation to make, or 977 // the type of allocation to be freed. 978 type spanAllocType uint8 979 980 const ( 981 spanAllocHeap spanAllocType = iota // heap span 982 spanAllocStack // stack span 983 spanAllocWorkBuf // work buf span 984 ) 985 986 // manual returns true if the span allocation is manually managed. 987 func (s spanAllocType) manual() bool { 988 return s != spanAllocHeap 989 } 990 991 // alloc allocates a new span of npage pages from the GC'd heap. 992 // 993 // spanclass indicates the span's size class and scannability. 994 // 995 // Returns a span that has been fully initialized. span.needzero indicates 996 // whether the span has been zeroed. Note that it may not be. 997 func (h *mheap) alloc(npages uintptr, spanclass spanClass) *mspan { 998 // Don't do any operations that lock the heap on the G stack. 999 // It might trigger stack growth, and the stack growth code needs 1000 // to be able to allocate heap. 1001 var s *mspan 1002 systemstack(func() { 1003 // To prevent excessive heap growth, before allocating n pages 1004 // we need to sweep and reclaim at least n pages. 1005 if !isSweepDone() { 1006 h.reclaim(npages) 1007 } 1008 s = h.allocSpan(npages, spanAllocHeap, spanclass) 1009 }) 1010 return s 1011 } 1012 1013 // allocManual allocates a manually-managed span of npage pages. 1014 // allocManual returns nil if allocation fails. 1015 // 1016 // allocManual adds the bytes used to *stat, which should be a 1017 // memstats in-use field. Unlike allocations in the GC'd heap, the 1018 // allocation does *not* count toward heapInUse. 1019 // 1020 // The memory backing the returned span may not be zeroed if 1021 // span.needzero is set. 1022 // 1023 // allocManual must be called on the system stack because it may 1024 // acquire the heap lock via allocSpan. See mheap for details. 1025 // 1026 // If new code is written to call allocManual, do NOT use an 1027 // existing spanAllocType value and instead declare a new one. 1028 // 1029 //go:systemstack 1030 func (h *mheap) allocManual(npages uintptr, typ spanAllocType) *mspan { 1031 if !typ.manual() { 1032 throw("manual span allocation called with non-manually-managed type") 1033 } 1034 return h.allocSpan(npages, typ, 0) 1035 } 1036 1037 // setSpans modifies the span map so [spanOf(base), spanOf(base+npage*pageSize)) 1038 // is s. 1039 func (h *mheap) setSpans(base, npage uintptr, s *mspan) { 1040 p := base / pageSize 1041 ai := arenaIndex(base) 1042 ha := h.arenas[ai.l1()][ai.l2()] 1043 for n := uintptr(0); n < npage; n++ { 1044 i := (p + n) % pagesPerArena 1045 if i == 0 { 1046 ai = arenaIndex(base + n*pageSize) 1047 ha = h.arenas[ai.l1()][ai.l2()] 1048 } 1049 ha.spans[i] = s 1050 } 1051 } 1052 1053 // allocNeedsZero checks if the region of address space [base, base+npage*pageSize), 1054 // assumed to be allocated, needs to be zeroed, updating heap arena metadata for 1055 // future allocations. 1056 // 1057 // This must be called each time pages are allocated from the heap, even if the page 1058 // allocator can otherwise prove the memory it's allocating is already zero because 1059 // they're fresh from the operating system. It updates heapArena metadata that is 1060 // critical for future page allocations. 1061 // 1062 // There are no locking constraints on this method. 1063 func (h *mheap) allocNeedsZero(base, npage uintptr) (needZero bool) { 1064 for npage > 0 { 1065 ai := arenaIndex(base) 1066 ha := h.arenas[ai.l1()][ai.l2()] 1067 1068 zeroedBase := atomic.Loaduintptr(&ha.zeroedBase) 1069 arenaBase := base % heapArenaBytes 1070 if arenaBase < zeroedBase { 1071 // We extended into the non-zeroed part of the 1072 // arena, so this region needs to be zeroed before use. 1073 // 1074 // zeroedBase is monotonically increasing, so if we see this now then 1075 // we can be sure we need to zero this memory region. 1076 // 1077 // We still need to update zeroedBase for this arena, and 1078 // potentially more arenas. 1079 needZero = true 1080 } 1081 // We may observe arenaBase > zeroedBase if we're racing with one or more 1082 // allocations which are acquiring memory directly before us in the address 1083 // space. But, because we know no one else is acquiring *this* memory, it's 1084 // still safe to not zero. 1085 1086 // Compute how far into the arena we extend into, capped 1087 // at heapArenaBytes. 1088 arenaLimit := arenaBase + npage*pageSize 1089 if arenaLimit > heapArenaBytes { 1090 arenaLimit = heapArenaBytes 1091 } 1092 // Increase ha.zeroedBase so it's >= arenaLimit. 1093 // We may be racing with other updates. 1094 for arenaLimit > zeroedBase { 1095 if atomic.Casuintptr(&ha.zeroedBase, zeroedBase, arenaLimit) { 1096 break 1097 } 1098 zeroedBase = atomic.Loaduintptr(&ha.zeroedBase) 1099 // Double check basic conditions of zeroedBase. 1100 if zeroedBase <= arenaLimit && zeroedBase > arenaBase { 1101 // The zeroedBase moved into the space we were trying to 1102 // claim. That's very bad, and indicates someone allocated 1103 // the same region we did. 1104 throw("potentially overlapping in-use allocations detected") 1105 } 1106 } 1107 1108 // Move base forward and subtract from npage to move into 1109 // the next arena, or finish. 1110 base += arenaLimit - arenaBase 1111 npage -= (arenaLimit - arenaBase) / pageSize 1112 } 1113 return 1114 } 1115 1116 // tryAllocMSpan attempts to allocate an mspan object from 1117 // the P-local cache, but may fail. 1118 // 1119 // h.lock need not be held. 1120 // 1121 // This caller must ensure that its P won't change underneath 1122 // it during this function. Currently to ensure that we enforce 1123 // that the function is run on the system stack, because that's 1124 // the only place it is used now. In the future, this requirement 1125 // may be relaxed if its use is necessary elsewhere. 1126 // 1127 //go:systemstack 1128 func (h *mheap) tryAllocMSpan() *mspan { 1129 pp := getg().m.p.ptr() 1130 // If we don't have a p or the cache is empty, we can't do 1131 // anything here. 1132 if pp == nil || pp.mspancache.len == 0 { 1133 return nil 1134 } 1135 // Pull off the last entry in the cache. 1136 s := pp.mspancache.buf[pp.mspancache.len-1] 1137 pp.mspancache.len-- 1138 return s 1139 } 1140 1141 // allocMSpanLocked allocates an mspan object. 1142 // 1143 // h.lock must be held. 1144 // 1145 // allocMSpanLocked must be called on the system stack because 1146 // its caller holds the heap lock. See mheap for details. 1147 // Running on the system stack also ensures that we won't 1148 // switch Ps during this function. See tryAllocMSpan for details. 1149 // 1150 //go:systemstack 1151 func (h *mheap) allocMSpanLocked() *mspan { 1152 assertLockHeld(&h.lock) 1153 1154 pp := getg().m.p.ptr() 1155 if pp == nil { 1156 // We don't have a p so just do the normal thing. 1157 return (*mspan)(h.spanalloc.alloc()) 1158 } 1159 // Refill the cache if necessary. 1160 if pp.mspancache.len == 0 { 1161 const refillCount = len(pp.mspancache.buf) / 2 1162 for i := 0; i < refillCount; i++ { 1163 pp.mspancache.buf[i] = (*mspan)(h.spanalloc.alloc()) 1164 } 1165 pp.mspancache.len = refillCount 1166 } 1167 // Pull off the last entry in the cache. 1168 s := pp.mspancache.buf[pp.mspancache.len-1] 1169 pp.mspancache.len-- 1170 return s 1171 } 1172 1173 // freeMSpanLocked free an mspan object. 1174 // 1175 // h.lock must be held. 1176 // 1177 // freeMSpanLocked must be called on the system stack because 1178 // its caller holds the heap lock. See mheap for details. 1179 // Running on the system stack also ensures that we won't 1180 // switch Ps during this function. See tryAllocMSpan for details. 1181 // 1182 //go:systemstack 1183 func (h *mheap) freeMSpanLocked(s *mspan) { 1184 assertLockHeld(&h.lock) 1185 1186 pp := getg().m.p.ptr() 1187 // First try to free the mspan directly to the cache. 1188 if pp != nil && pp.mspancache.len < len(pp.mspancache.buf) { 1189 pp.mspancache.buf[pp.mspancache.len] = s 1190 pp.mspancache.len++ 1191 return 1192 } 1193 // Failing that (or if we don't have a p), just free it to 1194 // the heap. 1195 h.spanalloc.free(unsafe.Pointer(s)) 1196 } 1197 1198 // allocSpan allocates an mspan which owns npages worth of memory. 1199 // 1200 // If typ.manual() == false, allocSpan allocates a heap span of class spanclass 1201 // and updates heap accounting. If manual == true, allocSpan allocates a 1202 // manually-managed span (spanclass is ignored), and the caller is 1203 // responsible for any accounting related to its use of the span. Either 1204 // way, allocSpan will atomically add the bytes in the newly allocated 1205 // span to *sysStat. 1206 // 1207 // The returned span is fully initialized. 1208 // 1209 // h.lock must not be held. 1210 // 1211 // allocSpan must be called on the system stack both because it acquires 1212 // the heap lock and because it must block GC transitions. 1213 // 1214 //go:systemstack 1215 func (h *mheap) allocSpan(npages uintptr, typ spanAllocType, spanclass spanClass) (s *mspan) { 1216 // Function-global state. 1217 gp := getg() 1218 base, scav := uintptr(0), uintptr(0) 1219 growth := uintptr(0) 1220 1221 // On some platforms we need to provide physical page aligned stack 1222 // allocations. Where the page size is less than the physical page 1223 // size, we already manage to do this by default. 1224 needPhysPageAlign := physPageAlignedStacks && typ == spanAllocStack && pageSize < physPageSize 1225 1226 // If the allocation is small enough, try the page cache! 1227 // The page cache does not support aligned allocations, so we cannot use 1228 // it if we need to provide a physical page aligned stack allocation. 1229 pp := gp.m.p.ptr() 1230 if !needPhysPageAlign && pp != nil && npages < pageCachePages/4 { 1231 c := &pp.pcache 1232 1233 // If the cache is empty, refill it. 1234 if c.empty() { 1235 lock(&h.lock) 1236 *c = h.pages.allocToCache() 1237 unlock(&h.lock) 1238 } 1239 1240 // Try to allocate from the cache. 1241 base, scav = c.alloc(npages) 1242 if base != 0 { 1243 s = h.tryAllocMSpan() 1244 if s != nil { 1245 goto HaveSpan 1246 } 1247 // We have a base but no mspan, so we need 1248 // to lock the heap. 1249 } 1250 } 1251 1252 // For one reason or another, we couldn't get the 1253 // whole job done without the heap lock. 1254 lock(&h.lock) 1255 1256 if needPhysPageAlign { 1257 // Overallocate by a physical page to allow for later alignment. 1258 extraPages := physPageSize / pageSize 1259 1260 // Find a big enough region first, but then only allocate the 1261 // aligned portion. We can't just allocate and then free the 1262 // edges because we need to account for scavenged memory, and 1263 // that's difficult with alloc. 1264 // 1265 // Note that we skip updates to searchAddr here. It's OK if 1266 // it's stale and higher than normal; it'll operate correctly, 1267 // just come with a performance cost. 1268 base, _ = h.pages.find(npages + extraPages) 1269 if base == 0 { 1270 var ok bool 1271 growth, ok = h.grow(npages + extraPages) 1272 if !ok { 1273 unlock(&h.lock) 1274 return nil 1275 } 1276 base, _ = h.pages.find(npages + extraPages) 1277 if base == 0 { 1278 throw("grew heap, but no adequate free space found") 1279 } 1280 } 1281 base = alignUp(base, physPageSize) 1282 scav = h.pages.allocRange(base, npages) 1283 } 1284 1285 if base == 0 { 1286 // Try to acquire a base address. 1287 base, scav = h.pages.alloc(npages) 1288 if base == 0 { 1289 var ok bool 1290 growth, ok = h.grow(npages) 1291 if !ok { 1292 unlock(&h.lock) 1293 return nil 1294 } 1295 base, scav = h.pages.alloc(npages) 1296 if base == 0 { 1297 throw("grew heap, but no adequate free space found") 1298 } 1299 } 1300 } 1301 if s == nil { 1302 // We failed to get an mspan earlier, so grab 1303 // one now that we have the heap lock. 1304 s = h.allocMSpanLocked() 1305 } 1306 unlock(&h.lock) 1307 1308 HaveSpan: 1309 // Decide if we need to scavenge in response to what we just allocated. 1310 // Specifically, we track the maximum amount of memory to scavenge of all 1311 // the alternatives below, assuming that the maximum satisfies *all* 1312 // conditions we check (e.g. if we need to scavenge X to satisfy the 1313 // memory limit and Y to satisfy heap-growth scavenging, and Y > X, then 1314 // it's fine to pick Y, because the memory limit is still satisfied). 1315 // 1316 // It's fine to do this after allocating because we expect any scavenged 1317 // pages not to get touched until we return. Simultaneously, it's important 1318 // to do this before calling sysUsed because that may commit address space. 1319 bytesToScavenge := uintptr(0) 1320 forceScavenge := false 1321 if limit := gcController.memoryLimit.Load(); !gcCPULimiter.limiting() { 1322 // Assist with scavenging to maintain the memory limit by the amount 1323 // that we expect to page in. 1324 inuse := gcController.mappedReady.Load() 1325 // Be careful about overflow, especially with uintptrs. Even on 32-bit platforms 1326 // someone can set a really big memory limit that isn't math.MaxInt64. 1327 if uint64(scav)+inuse > uint64(limit) { 1328 bytesToScavenge = uintptr(uint64(scav) + inuse - uint64(limit)) 1329 forceScavenge = true 1330 } 1331 } 1332 if goal := scavenge.gcPercentGoal.Load(); goal != ^uint64(0) && growth > 0 { 1333 // We just caused a heap growth, so scavenge down what will soon be used. 1334 // By scavenging inline we deal with the failure to allocate out of 1335 // memory fragments by scavenging the memory fragments that are least 1336 // likely to be re-used. 1337 // 1338 // Only bother with this because we're not using a memory limit. We don't 1339 // care about heap growths as long as we're under the memory limit, and the 1340 // previous check for scaving already handles that. 1341 if retained := heapRetained(); retained+uint64(growth) > goal { 1342 // The scavenging algorithm requires the heap lock to be dropped so it 1343 // can acquire it only sparingly. This is a potentially expensive operation 1344 // so it frees up other goroutines to allocate in the meanwhile. In fact, 1345 // they can make use of the growth we just created. 1346 todo := growth 1347 if overage := uintptr(retained + uint64(growth) - goal); todo > overage { 1348 todo = overage 1349 } 1350 if todo > bytesToScavenge { 1351 bytesToScavenge = todo 1352 } 1353 } 1354 } 1355 // There are a few very limited circumstances where we won't have a P here. 1356 // It's OK to simply skip scavenging in these cases. Something else will notice 1357 // and pick up the tab. 1358 var now int64 1359 if pp != nil && bytesToScavenge > 0 { 1360 // Measure how long we spent scavenging and add that measurement to the assist 1361 // time so we can track it for the GC CPU limiter. 1362 // 1363 // Limiter event tracking might be disabled if we end up here 1364 // while on a mark worker. 1365 start := nanotime() 1366 track := pp.limiterEvent.start(limiterEventScavengeAssist, start) 1367 1368 // Scavenge, but back out if the limiter turns on. 1369 released := h.pages.scavenge(bytesToScavenge, func() bool { 1370 return gcCPULimiter.limiting() 1371 }, forceScavenge) 1372 1373 mheap_.pages.scav.releasedEager.Add(released) 1374 1375 // Finish up accounting. 1376 now = nanotime() 1377 if track { 1378 pp.limiterEvent.stop(limiterEventScavengeAssist, now) 1379 } 1380 scavenge.assistTime.Add(now - start) 1381 } 1382 1383 // Initialize the span. 1384 h.initSpan(s, typ, spanclass, base, npages, scav) 1385 1386 if valgrindenabled { 1387 valgrindMempoolMalloc(unsafe.Pointer(arenaBase(arenaIndex(base))), unsafe.Pointer(base), npages*pageSize) 1388 } 1389 1390 // Commit and account for any scavenged memory that the span now owns. 1391 nbytes := npages * pageSize 1392 if scav != 0 { 1393 // sysUsed all the pages that are actually available 1394 // in the span since some of them might be scavenged. 1395 sysUsed(unsafe.Pointer(base), nbytes, scav) 1396 gcController.heapReleased.add(-int64(scav)) 1397 } 1398 // Update stats. 1399 gcController.heapFree.add(-int64(nbytes - scav)) 1400 if typ == spanAllocHeap { 1401 gcController.heapInUse.add(int64(nbytes)) 1402 } 1403 // Update consistent stats. 1404 stats := memstats.heapStats.acquire() 1405 atomic.Xaddint64(&stats.committed, int64(scav)) 1406 atomic.Xaddint64(&stats.released, -int64(scav)) 1407 switch typ { 1408 case spanAllocHeap: 1409 atomic.Xaddint64(&stats.inHeap, int64(nbytes)) 1410 case spanAllocStack: 1411 atomic.Xaddint64(&stats.inStacks, int64(nbytes)) 1412 case spanAllocWorkBuf: 1413 atomic.Xaddint64(&stats.inWorkBufs, int64(nbytes)) 1414 } 1415 memstats.heapStats.release() 1416 1417 // Trace the span alloc. 1418 if traceAllocFreeEnabled() { 1419 trace := traceAcquire() 1420 if trace.ok() { 1421 trace.SpanAlloc(s) 1422 traceRelease(trace) 1423 } 1424 } 1425 return s 1426 } 1427 1428 // initSpan initializes a blank span s which will represent the range 1429 // [base, base+npages*pageSize). typ is the type of span being allocated. 1430 func (h *mheap) initSpan(s *mspan, typ spanAllocType, spanclass spanClass, base, npages, scav uintptr) { 1431 // At this point, both s != nil and base != 0, and the heap 1432 // lock is no longer held. Initialize the span. 1433 s.init(base, npages) 1434 // Always call allocNeedsZero to update the arena's zeroedBase watermark 1435 // and determine if the memory is considered dirty. 1436 needZero := h.allocNeedsZero(base, npages) 1437 // If these pages were scavenged (returned to the OS), the kernel guarantees 1438 // they will be zero-filled on next use (fault-in), so we can treat them as 1439 // already zeroed and skip explicit clearing. 1440 if (needZeroAfterSysUnused() || scav != npages*pageSize) && needZero { 1441 s.needzero = 1 1442 } 1443 nbytes := npages * pageSize 1444 if typ.manual() { 1445 s.manualFreeList = 0 1446 s.nelems = 0 1447 s.state.set(mSpanManual) 1448 } else { 1449 // We must set span properties before the span is published anywhere 1450 // since we're not holding the heap lock. 1451 s.spanclass = spanclass 1452 if sizeclass := spanclass.sizeclass(); sizeclass == 0 { 1453 s.elemsize = nbytes 1454 s.nelems = 1 1455 s.divMul = 0 1456 } else { 1457 s.elemsize = uintptr(gc.SizeClassToSize[sizeclass]) 1458 if goexperiment.GreenTeaGC { 1459 var reserve uintptr 1460 if gcUsesSpanInlineMarkBits(s.elemsize) { 1461 // Reserve space for the inline mark bits. 1462 reserve += unsafe.Sizeof(spanInlineMarkBits{}) 1463 } 1464 if heapBitsInSpan(s.elemsize) && !s.spanclass.noscan() { 1465 // Reserve space for the pointer/scan bitmap at the end. 1466 reserve += nbytes / goarch.PtrSize / 8 1467 } 1468 s.nelems = uint16((nbytes - reserve) / s.elemsize) 1469 } else { 1470 if !s.spanclass.noscan() && heapBitsInSpan(s.elemsize) { 1471 // Reserve space for the pointer/scan bitmap at the end. 1472 s.nelems = uint16((nbytes - (nbytes / goarch.PtrSize / 8)) / s.elemsize) 1473 } else { 1474 s.nelems = uint16(nbytes / s.elemsize) 1475 } 1476 } 1477 s.divMul = gc.SizeClassToDivMagic[sizeclass] 1478 } 1479 1480 // Initialize mark and allocation structures. 1481 s.freeindex = 0 1482 s.freeIndexForScan = 0 1483 s.allocCache = ^uint64(0) // all 1s indicating all free. 1484 s.gcmarkBits = newMarkBits(uintptr(s.nelems)) 1485 s.allocBits = newAllocBits(uintptr(s.nelems)) 1486 1487 // Adjust s.limit down to the object-containing part of the span. 1488 s.limit = s.base() + s.elemsize*uintptr(s.nelems) 1489 1490 // It's safe to access h.sweepgen without the heap lock because it's 1491 // only ever updated with the world stopped and we run on the 1492 // systemstack which blocks a STW transition. 1493 atomic.Store(&s.sweepgen, h.sweepgen) 1494 1495 // Now that the span is filled in, set its state. This 1496 // is a publication barrier for the other fields in 1497 // the span. While valid pointers into this span 1498 // should never be visible until the span is returned, 1499 // if the garbage collector finds an invalid pointer, 1500 // access to the span may race with initialization of 1501 // the span. We resolve this race by atomically 1502 // setting the state after the span is fully 1503 // initialized, and atomically checking the state in 1504 // any situation where a pointer is suspect. 1505 s.state.set(mSpanInUse) 1506 } 1507 1508 // Publish the span in various locations. 1509 1510 // This is safe to call without the lock held because the slots 1511 // related to this span will only ever be read or modified by 1512 // this thread until pointers into the span are published (and 1513 // we execute a publication barrier at the end of this function 1514 // before that happens) or pageInUse is updated. 1515 h.setSpans(s.base(), npages, s) 1516 1517 if !typ.manual() { 1518 // Mark in-use span in arena page bitmap. 1519 // 1520 // This publishes the span to the page sweeper, so 1521 // it's imperative that the span be completely initialized 1522 // prior to this line. 1523 arena, pageIdx, pageMask := pageIndexOf(s.base()) 1524 atomic.Or8(&arena.pageInUse[pageIdx], pageMask) 1525 1526 // Mark packed span. 1527 if gcUsesSpanInlineMarkBits(s.elemsize) { 1528 atomic.Or8(&arena.pageUseSpanInlineMarkBits[pageIdx], pageMask) 1529 } 1530 1531 // Update related page sweeper stats. 1532 h.pagesInUse.Add(npages) 1533 } 1534 1535 // Make sure the newly allocated span will be observed 1536 // by the GC before pointers into the span are published. 1537 publicationBarrier() 1538 } 1539 1540 // Try to add at least npage pages of memory to the heap, 1541 // returning how much the heap grew by and whether it worked. 1542 // 1543 // h.lock must be held. 1544 func (h *mheap) grow(npage uintptr) (uintptr, bool) { 1545 assertLockHeld(&h.lock) 1546 1547 firstGrow := h.curArena.base == 0 1548 1549 // We must grow the heap in whole palloc chunks. 1550 // We call sysMap below but note that because we 1551 // round up to pallocChunkPages which is on the order 1552 // of MiB (generally >= to the huge page size) we 1553 // won't be calling it too much. 1554 ask := alignUp(npage, pallocChunkPages) * pageSize 1555 1556 totalGrowth := uintptr(0) 1557 // This may overflow because ask could be very large 1558 // and is otherwise unrelated to h.curArena.base. 1559 end := h.curArena.base + ask 1560 nBase := alignUp(end, physPageSize) 1561 if nBase > h.curArena.end || /* overflow */ end < h.curArena.base { 1562 // Not enough room in the current arena. Allocate more 1563 // arena space. This may not be contiguous with the 1564 // current arena, so we have to request the full ask. 1565 av, asize := h.sysAlloc(ask, &h.arenaHints, &h.heapArenas) 1566 if av == nil { 1567 inUse := gcController.heapFree.load() + gcController.heapReleased.load() + gcController.heapInUse.load() 1568 print("runtime: out of memory: cannot allocate ", ask, "-byte block (", inUse, " in use)\n") 1569 return 0, false 1570 } 1571 1572 if uintptr(av) == h.curArena.end { 1573 // The new space is contiguous with the old 1574 // space, so just extend the current space. 1575 h.curArena.end = uintptr(av) + asize 1576 } else { 1577 // The new space is discontiguous. Track what 1578 // remains of the current space and switch to 1579 // the new space. This should be rare. 1580 if size := h.curArena.end - h.curArena.base; size != 0 { 1581 // Transition this space from Reserved to Prepared and mark it 1582 // as released since we'll be able to start using it after updating 1583 // the page allocator and releasing the lock at any time. 1584 sysMap(unsafe.Pointer(h.curArena.base), size, &gcController.heapReleased, "heap") 1585 // Update stats. 1586 stats := memstats.heapStats.acquire() 1587 atomic.Xaddint64(&stats.released, int64(size)) 1588 memstats.heapStats.release() 1589 // Update the page allocator's structures to make this 1590 // space ready for allocation. 1591 h.pages.grow(h.curArena.base, size) 1592 totalGrowth += size 1593 } 1594 // Switch to the new space. 1595 h.curArena.base = uintptr(av) 1596 h.curArena.end = uintptr(av) + asize 1597 1598 if firstGrow && randomizeHeapBase { 1599 // The top heapAddrBits-logHeapArenaBytes are randomized, we now 1600 // want to randomize the next 1601 // logHeapArenaBytes-log2(pallocChunkBytes) bits, making sure 1602 // h.curArena.base is aligned to pallocChunkBytes. 1603 bits := logHeapArenaBytes - logPallocChunkBytes 1604 offset := nextHeapRandBits(bits) 1605 h.curArena.base = alignDown(h.curArena.base|(offset<<logPallocChunkBytes), pallocChunkBytes) 1606 } 1607 } 1608 1609 // Recalculate nBase. 1610 // We know this won't overflow, because sysAlloc returned 1611 // a valid region starting at h.curArena.base which is at 1612 // least ask bytes in size. 1613 nBase = alignUp(h.curArena.base+ask, physPageSize) 1614 } 1615 1616 // Grow into the current arena. 1617 v := h.curArena.base 1618 h.curArena.base = nBase 1619 1620 // Transition the space we're going to use from Reserved to Prepared. 1621 // 1622 // The allocation is always aligned to the heap arena 1623 // size which is always > physPageSize, so its safe to 1624 // just add directly to heapReleased. 1625 sysMap(unsafe.Pointer(v), nBase-v, &gcController.heapReleased, "heap") 1626 1627 // The memory just allocated counts as both released 1628 // and idle, even though it's not yet backed by spans. 1629 stats := memstats.heapStats.acquire() 1630 atomic.Xaddint64(&stats.released, int64(nBase-v)) 1631 memstats.heapStats.release() 1632 1633 // Update the page allocator's structures to make this 1634 // space ready for allocation. 1635 h.pages.grow(v, nBase-v) 1636 totalGrowth += nBase - v 1637 1638 if firstGrow && randomizeHeapBase { 1639 // The top heapAddrBits-log2(pallocChunkBytes) bits are now randomized, 1640 // we finally want to randomize the next 1641 // log2(pallocChunkBytes)-log2(pageSize) bits, while maintaining 1642 // alignment to pageSize. We do this by calculating a random number of 1643 // pages into the current arena, and marking them as allocated. The 1644 // address of the next available page becomes our fully randomized base 1645 // heap address. 1646 randOffset := nextHeapRandBits(logPallocChunkBytes) 1647 randNumPages := alignDown(randOffset, pageSize) / pageSize 1648 if randNumPages != 0 { 1649 h.pages.markRandomPaddingPages(v, randNumPages) 1650 } 1651 } 1652 1653 return totalGrowth, true 1654 } 1655 1656 // Free the span back into the heap. 1657 func (h *mheap) freeSpan(s *mspan) { 1658 systemstack(func() { 1659 // Trace the span free. 1660 if traceAllocFreeEnabled() { 1661 trace := traceAcquire() 1662 if trace.ok() { 1663 trace.SpanFree(s) 1664 traceRelease(trace) 1665 } 1666 } 1667 1668 lock(&h.lock) 1669 if msanenabled { 1670 // Tell msan that this entire span is no longer in use. 1671 base := unsafe.Pointer(s.base()) 1672 bytes := s.npages << gc.PageShift 1673 msanfree(base, bytes) 1674 } 1675 if asanenabled { 1676 // Tell asan that this entire span is no longer in use. 1677 base := unsafe.Pointer(s.base()) 1678 bytes := s.npages << gc.PageShift 1679 asanpoison(base, bytes) 1680 } 1681 if valgrindenabled { 1682 base := s.base() 1683 valgrindMempoolFree(unsafe.Pointer(arenaBase(arenaIndex(base))), unsafe.Pointer(base)) 1684 } 1685 h.freeSpanLocked(s, spanAllocHeap) 1686 unlock(&h.lock) 1687 }) 1688 } 1689 1690 // freeManual frees a manually-managed span returned by allocManual. 1691 // typ must be the same as the spanAllocType passed to the allocManual that 1692 // allocated s. 1693 // 1694 // This must only be called when gcphase == _GCoff. See mSpanState for 1695 // an explanation. 1696 // 1697 // freeManual must be called on the system stack because it acquires 1698 // the heap lock. See mheap for details. 1699 // 1700 //go:systemstack 1701 func (h *mheap) freeManual(s *mspan, typ spanAllocType) { 1702 // Trace the span free. 1703 if traceAllocFreeEnabled() { 1704 trace := traceAcquire() 1705 if trace.ok() { 1706 trace.SpanFree(s) 1707 traceRelease(trace) 1708 } 1709 } 1710 1711 s.needzero = 1 1712 lock(&h.lock) 1713 if valgrindenabled { 1714 base := s.base() 1715 valgrindMempoolFree(unsafe.Pointer(arenaBase(arenaIndex(base))), unsafe.Pointer(base)) 1716 } 1717 h.freeSpanLocked(s, typ) 1718 unlock(&h.lock) 1719 } 1720 1721 func (h *mheap) freeSpanLocked(s *mspan, typ spanAllocType) { 1722 assertLockHeld(&h.lock) 1723 1724 switch s.state.get() { 1725 case mSpanManual: 1726 if s.allocCount != 0 { 1727 throw("mheap.freeSpanLocked - invalid stack free") 1728 } 1729 case mSpanInUse: 1730 if s.isUserArenaChunk { 1731 throw("mheap.freeSpanLocked - invalid free of user arena chunk") 1732 } 1733 if s.allocCount != 0 || s.sweepgen != h.sweepgen { 1734 print("mheap.freeSpanLocked - span ", s, " ptr ", hex(s.base()), " allocCount ", s.allocCount, " sweepgen ", s.sweepgen, "/", h.sweepgen, "\n") 1735 throw("mheap.freeSpanLocked - invalid free") 1736 } 1737 h.pagesInUse.Add(-s.npages) 1738 1739 // Clear in-use bit in arena page bitmap. 1740 arena, pageIdx, pageMask := pageIndexOf(s.base()) 1741 atomic.And8(&arena.pageInUse[pageIdx], ^pageMask) 1742 1743 // Clear small heap span bit if necessary. 1744 if gcUsesSpanInlineMarkBits(s.elemsize) { 1745 atomic.And8(&arena.pageUseSpanInlineMarkBits[pageIdx], ^pageMask) 1746 } 1747 default: 1748 throw("mheap.freeSpanLocked - invalid span state") 1749 } 1750 1751 // Update stats. 1752 // 1753 // Mirrors the code in allocSpan. 1754 nbytes := s.npages * pageSize 1755 gcController.heapFree.add(int64(nbytes)) 1756 if typ == spanAllocHeap { 1757 gcController.heapInUse.add(-int64(nbytes)) 1758 } 1759 // Update consistent stats. 1760 stats := memstats.heapStats.acquire() 1761 switch typ { 1762 case spanAllocHeap: 1763 atomic.Xaddint64(&stats.inHeap, -int64(nbytes)) 1764 case spanAllocStack: 1765 atomic.Xaddint64(&stats.inStacks, -int64(nbytes)) 1766 case spanAllocWorkBuf: 1767 atomic.Xaddint64(&stats.inWorkBufs, -int64(nbytes)) 1768 } 1769 memstats.heapStats.release() 1770 1771 // Mark the space as free. 1772 h.pages.free(s.base(), s.npages) 1773 1774 // Free the span structure. We no longer have a use for it. 1775 s.state.set(mSpanDead) 1776 h.freeMSpanLocked(s) 1777 } 1778 1779 // scavengeAll acquires the heap lock (blocking any additional 1780 // manipulation of the page allocator) and iterates over the whole 1781 // heap, scavenging every free page available. 1782 // 1783 // Must run on the system stack because it acquires the heap lock. 1784 // 1785 //go:systemstack 1786 func (h *mheap) scavengeAll() { 1787 // Disallow malloc or panic while holding the heap lock. We do 1788 // this here because this is a non-mallocgc entry-point to 1789 // the mheap API. 1790 gp := getg() 1791 gp.m.mallocing++ 1792 1793 // Force scavenge everything. 1794 released := h.pages.scavenge(^uintptr(0), nil, true) 1795 1796 gp.m.mallocing-- 1797 1798 if debug.scavtrace > 0 { 1799 printScavTrace(0, released, true) 1800 } 1801 } 1802 1803 //go:linkname runtime_debug_freeOSMemory runtime/debug.freeOSMemory 1804 func runtime_debug_freeOSMemory() { 1805 GC() 1806 systemstack(func() { mheap_.scavengeAll() }) 1807 } 1808 1809 // Initialize a new span with the given start and npages. 1810 func (span *mspan) init(base uintptr, npages uintptr) { 1811 // span is *not* zeroed. 1812 span.next = nil 1813 span.prev = nil 1814 span.list = nil 1815 span.startAddr = base 1816 span.npages = npages 1817 span.limit = base + npages*gc.PageSize // see go.dev/issue/74288; adjusted later for heap spans 1818 span.allocCount = 0 1819 span.spanclass = 0 1820 span.elemsize = 0 1821 span.speciallock.key = 0 1822 span.specials = nil 1823 span.needzero = 0 1824 span.freeindex = 0 1825 span.freeIndexForScan = 0 1826 span.allocBits = nil 1827 span.gcmarkBits = nil 1828 span.pinnerBits = nil 1829 span.state.set(mSpanDead) 1830 lockInit(&span.speciallock, lockRankMspanSpecial) 1831 } 1832 1833 func (span *mspan) inList() bool { 1834 return span.list != nil 1835 } 1836 1837 // mSpanList heads a linked list of spans. 1838 type mSpanList struct { 1839 _ sys.NotInHeap 1840 first *mspan // first span in list, or nil if none 1841 last *mspan // last span in list, or nil if none 1842 } 1843 1844 // Initialize an empty doubly-linked list. 1845 func (list *mSpanList) init() { 1846 list.first = nil 1847 list.last = nil 1848 } 1849 1850 func (list *mSpanList) remove(span *mspan) { 1851 if span.list != list { 1852 print("runtime: failed mSpanList.remove span.npages=", span.npages, 1853 " span=", span, " prev=", span.prev, " span.list=", span.list, " list=", list, "\n") 1854 throw("mSpanList.remove") 1855 } 1856 if list.first == span { 1857 list.first = span.next 1858 } else { 1859 span.prev.next = span.next 1860 } 1861 if list.last == span { 1862 list.last = span.prev 1863 } else { 1864 span.next.prev = span.prev 1865 } 1866 span.next = nil 1867 span.prev = nil 1868 span.list = nil 1869 } 1870 1871 func (list *mSpanList) isEmpty() bool { 1872 return list.first == nil 1873 } 1874 1875 func (list *mSpanList) insert(span *mspan) { 1876 if span.next != nil || span.prev != nil || span.list != nil { 1877 println("runtime: failed mSpanList.insert", span, span.next, span.prev, span.list) 1878 throw("mSpanList.insert") 1879 } 1880 span.next = list.first 1881 if list.first != nil { 1882 // The list contains at least one span; link it in. 1883 // The last span in the list doesn't change. 1884 list.first.prev = span 1885 } else { 1886 // The list contains no spans, so this is also the last span. 1887 list.last = span 1888 } 1889 list.first = span 1890 span.list = list 1891 } 1892 1893 func (list *mSpanList) insertBack(span *mspan) { 1894 if span.next != nil || span.prev != nil || span.list != nil { 1895 println("runtime: failed mSpanList.insertBack", span, span.next, span.prev, span.list) 1896 throw("mSpanList.insertBack") 1897 } 1898 span.prev = list.last 1899 if list.last != nil { 1900 // The list contains at least one span. 1901 list.last.next = span 1902 } else { 1903 // The list contains no spans, so this is also the first span. 1904 list.first = span 1905 } 1906 list.last = span 1907 span.list = list 1908 } 1909 1910 // takeAll removes all spans from other and inserts them at the front 1911 // of list. 1912 func (list *mSpanList) takeAll(other *mSpanList) { 1913 if other.isEmpty() { 1914 return 1915 } 1916 1917 // Reparent everything in other to list. 1918 for s := other.first; s != nil; s = s.next { 1919 s.list = list 1920 } 1921 1922 // Concatenate the lists. 1923 if list.isEmpty() { 1924 *list = *other 1925 } else { 1926 // Neither list is empty. Put other before list. 1927 other.last.next = list.first 1928 list.first.prev = other.last 1929 list.first = other.first 1930 } 1931 1932 other.first, other.last = nil, nil 1933 } 1934 1935 const ( 1936 // _KindSpecialTinyBlock indicates that a given allocation is a tiny block. 1937 // Ordered before KindSpecialFinalizer and KindSpecialCleanup so that it 1938 // always appears first in the specials list. 1939 // Used only if debug.checkfinalizers != 0. 1940 _KindSpecialTinyBlock = 1 1941 // _KindSpecialFinalizer is for tracking finalizers. 1942 _KindSpecialFinalizer = 2 1943 // _KindSpecialWeakHandle is used for creating weak pointers. 1944 _KindSpecialWeakHandle = 3 1945 // _KindSpecialProfile is for memory profiling. 1946 _KindSpecialProfile = 4 1947 // _KindSpecialReachable is a special used for tracking 1948 // reachability during testing. 1949 _KindSpecialReachable = 5 1950 // _KindSpecialPinCounter is a special used for objects that are pinned 1951 // multiple times 1952 _KindSpecialPinCounter = 6 1953 // _KindSpecialCleanup is for tracking cleanups. 1954 _KindSpecialCleanup = 7 1955 // _KindSpecialCheckFinalizer adds additional context to a finalizer or cleanup. 1956 // Used only if debug.checkfinalizers != 0. 1957 _KindSpecialCheckFinalizer = 8 1958 // _KindSpecialBubble is used to associate objects with synctest bubbles. 1959 _KindSpecialBubble = 9 1960 // _KindSpecialSecret is a special used to mark an object 1961 // as needing zeroing immediately upon freeing. 1962 _KindSpecialSecret = 10 1963 ) 1964 1965 type special struct { 1966 _ sys.NotInHeap 1967 next *special // linked list in span 1968 offset uintptr // span offset of object 1969 kind byte // kind of special 1970 } 1971 1972 // spanHasSpecials marks a span as having specials in the arena bitmap. 1973 // The caller must hold s.speciallock and have just added one special. 1974 func spanHasSpecials(s *mspan) { 1975 if s.specials.next != nil { 1976 // The span already had specials, so its bit is already set. 1977 return 1978 } 1979 arenaPage := (s.base() / pageSize) % pagesPerArena 1980 ai := arenaIndex(s.base()) 1981 ha := mheap_.arenas[ai.l1()][ai.l2()] 1982 atomic.Or8(&ha.pageSpecials[arenaPage/8], uint8(1)<<(arenaPage%8)) 1983 } 1984 1985 // spanHasNoSpecials marks a span as having no specials in the arena bitmap. 1986 func spanHasNoSpecials(s *mspan) { 1987 arenaPage := (s.base() / pageSize) % pagesPerArena 1988 ai := arenaIndex(s.base()) 1989 ha := mheap_.arenas[ai.l1()][ai.l2()] 1990 atomic.And8(&ha.pageSpecials[arenaPage/8], ^(uint8(1) << (arenaPage % 8))) 1991 } 1992 1993 // addspecial adds the special record s to the list of special records for 1994 // the object p. All fields of s should be filled in except for 1995 // offset & next, which this routine will fill in. 1996 // Returns true if the special was successfully added, false otherwise. 1997 // (The add will fail only if a record with the same p and s->kind 1998 // already exists unless force is set to true.) 1999 func addspecial(p unsafe.Pointer, s *special, force bool) bool { 2000 span := spanOfHeap(uintptr(p)) 2001 if span == nil { 2002 throw("addspecial on invalid pointer") 2003 } 2004 2005 // Ensure that the span is swept. 2006 // Sweeping accesses the specials list w/o locks, so we have 2007 // to synchronize with it. And it's just much safer. 2008 mp := acquirem() 2009 span.ensureSwept() 2010 2011 offset := uintptr(p) - span.base() 2012 kind := s.kind 2013 2014 lock(&span.speciallock) 2015 2016 // Find splice point, check for existing record. 2017 iter, exists := span.specialFindSplicePoint(offset, kind) 2018 if !exists || force { 2019 // Splice in record, fill in offset. 2020 s.offset = offset 2021 s.next = *iter 2022 *iter = s 2023 spanHasSpecials(span) 2024 } 2025 2026 unlock(&span.speciallock) 2027 releasem(mp) 2028 // We're converting p to a uintptr and looking it up, and we 2029 // don't want it to die and get swept while we're doing so. 2030 KeepAlive(p) 2031 return !exists || force // already exists or addition was forced 2032 } 2033 2034 // Removes the Special record of the given kind for the object p. 2035 // Returns the record if the record existed, nil otherwise. 2036 // The caller must FixAlloc_Free the result. 2037 func removespecial(p unsafe.Pointer, kind uint8) *special { 2038 span := spanOfHeap(uintptr(p)) 2039 if span == nil { 2040 throw("removespecial on invalid pointer") 2041 } 2042 2043 // Ensure that the span is swept. 2044 // Sweeping accesses the specials list w/o locks, so we have 2045 // to synchronize with it. And it's just much safer. 2046 mp := acquirem() 2047 span.ensureSwept() 2048 2049 offset := uintptr(p) - span.base() 2050 2051 var result *special 2052 lock(&span.speciallock) 2053 2054 iter, exists := span.specialFindSplicePoint(offset, kind) 2055 if exists { 2056 s := *iter 2057 *iter = s.next 2058 result = s 2059 } 2060 if span.specials == nil { 2061 spanHasNoSpecials(span) 2062 } 2063 unlock(&span.speciallock) 2064 releasem(mp) 2065 return result 2066 } 2067 2068 // Find a splice point in the sorted list and check for an already existing 2069 // record. Returns a pointer to the next-reference in the list predecessor. 2070 // Returns true, if the referenced item is an exact match. 2071 func (span *mspan) specialFindSplicePoint(offset uintptr, kind byte) (**special, bool) { 2072 // Find splice point, check for existing record. 2073 iter := &span.specials 2074 s := *iter 2075 for s != nil && s.offset < offset { 2076 iter = &s.next 2077 s = *iter 2078 } 2079 for s != nil && s.offset == offset { 2080 if s.kind >= kind { 2081 return iter, s.kind == kind 2082 } 2083 iter = &s.next 2084 s = *iter 2085 } 2086 return iter, false 2087 } 2088 2089 // The described object has a finalizer set for it. 2090 // 2091 // specialfinalizer is allocated from non-GC'd memory, so any heap 2092 // pointers must be specially handled. 2093 type specialfinalizer struct { 2094 _ sys.NotInHeap 2095 special special 2096 fn *funcval // May be a heap pointer. 2097 nret uintptr 2098 fint *_type // May be a heap pointer, but always live. 2099 ot *ptrtype // May be a heap pointer, but always live. 2100 } 2101 2102 // Adds a finalizer to the object p. Returns true if it succeeded. 2103 func addfinalizer(p unsafe.Pointer, f *funcval, nret uintptr, fint *_type, ot *ptrtype) bool { 2104 lock(&mheap_.speciallock) 2105 s := (*specialfinalizer)(mheap_.specialfinalizeralloc.alloc()) 2106 unlock(&mheap_.speciallock) 2107 s.special.kind = _KindSpecialFinalizer 2108 s.fn = f 2109 s.nret = nret 2110 s.fint = fint 2111 s.ot = ot 2112 if addspecial(p, &s.special, false) { 2113 // This is responsible for maintaining the same 2114 // GC-related invariants as markrootSpans in any 2115 // situation where it's possible that markrootSpans 2116 // has already run but mark termination hasn't yet. 2117 if gcphase != _GCoff { 2118 base, span, _ := findObject(uintptr(p), 0, 0) 2119 mp := acquirem() 2120 gcw := &mp.p.ptr().gcw 2121 // Mark everything reachable from the object 2122 // so it's retained for the finalizer. 2123 if !span.spanclass.noscan() { 2124 scanObject(base, gcw) 2125 } 2126 // Mark the finalizer itself, since the 2127 // special isn't part of the GC'd heap. 2128 scanblock(uintptr(unsafe.Pointer(&s.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil) 2129 releasem(mp) 2130 } 2131 return true 2132 } 2133 2134 // There was an old finalizer 2135 lock(&mheap_.speciallock) 2136 mheap_.specialfinalizeralloc.free(unsafe.Pointer(s)) 2137 unlock(&mheap_.speciallock) 2138 return false 2139 } 2140 2141 // Removes the finalizer (if any) from the object p. 2142 func removefinalizer(p unsafe.Pointer) { 2143 s := (*specialfinalizer)(unsafe.Pointer(removespecial(p, _KindSpecialFinalizer))) 2144 if s == nil { 2145 return // there wasn't a finalizer to remove 2146 } 2147 lock(&mheap_.speciallock) 2148 mheap_.specialfinalizeralloc.free(unsafe.Pointer(s)) 2149 unlock(&mheap_.speciallock) 2150 } 2151 2152 // The described object has a cleanup set for it. 2153 type specialCleanup struct { 2154 _ sys.NotInHeap 2155 special special 2156 cleanup cleanupFn 2157 // Globally unique ID for the cleanup, obtained from mheap_.cleanupID. 2158 id uint64 2159 } 2160 2161 // addCleanup attaches a cleanup function to the object. Multiple 2162 // cleanups are allowed on an object, and even the same pointer. 2163 // A cleanup id is returned which can be used to uniquely identify 2164 // the cleanup. 2165 func addCleanup(p unsafe.Pointer, c cleanupFn) uint64 { 2166 // TODO(mknyszek): Consider pooling specialCleanups on the P 2167 // so we don't have to take the lock every time. Just locking 2168 // is a considerable part of the cost of AddCleanup. This 2169 // would also require reserving some cleanup IDs on the P. 2170 lock(&mheap_.speciallock) 2171 s := (*specialCleanup)(mheap_.specialCleanupAlloc.alloc()) 2172 mheap_.cleanupID++ // Increment first. ID 0 is reserved. 2173 id := mheap_.cleanupID 2174 unlock(&mheap_.speciallock) 2175 s.special.kind = _KindSpecialCleanup 2176 s.cleanup = c 2177 s.id = id 2178 2179 mp := acquirem() 2180 addspecial(p, &s.special, true) 2181 // This is responsible for maintaining the same 2182 // GC-related invariants as markrootSpans in any 2183 // situation where it's possible that markrootSpans 2184 // has already run but mark termination hasn't yet. 2185 if gcphase != _GCoff { 2186 // Mark the cleanup itself, since the 2187 // special isn't part of the GC'd heap. 2188 gcScanCleanup(s, &mp.p.ptr().gcw) 2189 } 2190 releasem(mp) 2191 // Keep c and its referents alive. There's a window in this function 2192 // where it's only reachable via the special while the special hasn't 2193 // been added to the specials list yet. This is similar to a bug 2194 // discovered for weak handles, see #70455. 2195 KeepAlive(c) 2196 return id 2197 } 2198 2199 // Always paired with a specialCleanup or specialfinalizer, adds context. 2200 type specialCheckFinalizer struct { 2201 _ sys.NotInHeap 2202 special special 2203 cleanupID uint64 // Needed to disambiguate cleanups. 2204 createPC uintptr 2205 funcPC uintptr 2206 ptrType *_type 2207 } 2208 2209 // setFinalizerContext adds a specialCheckFinalizer to ptr. ptr must already have a 2210 // finalizer special attached. 2211 func setFinalizerContext(ptr unsafe.Pointer, ptrType *_type, createPC, funcPC uintptr) { 2212 setCleanupContext(ptr, ptrType, createPC, funcPC, 0) 2213 } 2214 2215 // setCleanupContext adds a specialCheckFinalizer to ptr. ptr must already have a 2216 // finalizer or cleanup special attached. Pass 0 for the cleanupID to indicate 2217 // a finalizer. 2218 func setCleanupContext(ptr unsafe.Pointer, ptrType *_type, createPC, funcPC uintptr, cleanupID uint64) { 2219 lock(&mheap_.speciallock) 2220 s := (*specialCheckFinalizer)(mheap_.specialCheckFinalizerAlloc.alloc()) 2221 unlock(&mheap_.speciallock) 2222 s.special.kind = _KindSpecialCheckFinalizer 2223 s.cleanupID = cleanupID 2224 s.createPC = createPC 2225 s.funcPC = funcPC 2226 s.ptrType = ptrType 2227 2228 mp := acquirem() 2229 addspecial(ptr, &s.special, true) 2230 releasem(mp) 2231 KeepAlive(ptr) 2232 } 2233 2234 func getCleanupContext(ptr uintptr, cleanupID uint64) *specialCheckFinalizer { 2235 assertWorldStopped() 2236 2237 span := spanOfHeap(ptr) 2238 if span == nil { 2239 return nil 2240 } 2241 var found *specialCheckFinalizer 2242 offset := ptr - span.base() 2243 iter, exists := span.specialFindSplicePoint(offset, _KindSpecialCheckFinalizer) 2244 if exists { 2245 for { 2246 s := *iter 2247 if s == nil { 2248 // Reached the end of the linked list. Stop searching at this point. 2249 break 2250 } 2251 if offset == s.offset && _KindSpecialCheckFinalizer == s.kind && 2252 (*specialCheckFinalizer)(unsafe.Pointer(s)).cleanupID == cleanupID { 2253 // The special is a cleanup and contains a matching cleanup id. 2254 *iter = s.next 2255 found = (*specialCheckFinalizer)(unsafe.Pointer(s)) 2256 break 2257 } 2258 if offset < s.offset || (offset == s.offset && _KindSpecialCheckFinalizer < s.kind) { 2259 // The special is outside the region specified for that kind of 2260 // special. The specials are sorted by kind. 2261 break 2262 } 2263 // Try the next special. 2264 iter = &s.next 2265 } 2266 } 2267 return found 2268 } 2269 2270 // clearFinalizerContext removes the specialCheckFinalizer for the given pointer, if any. 2271 func clearFinalizerContext(ptr uintptr) { 2272 clearCleanupContext(ptr, 0) 2273 } 2274 2275 // clearFinalizerContext removes the specialCheckFinalizer for the given pointer and cleanup ID, if any. 2276 func clearCleanupContext(ptr uintptr, cleanupID uint64) { 2277 // The following block removes the Special record of type cleanup for the object c.ptr. 2278 span := spanOfHeap(ptr) 2279 if span == nil { 2280 return 2281 } 2282 // Ensure that the span is swept. 2283 // Sweeping accesses the specials list w/o locks, so we have 2284 // to synchronize with it. And it's just much safer. 2285 mp := acquirem() 2286 span.ensureSwept() 2287 2288 offset := ptr - span.base() 2289 2290 var found *special 2291 lock(&span.speciallock) 2292 2293 iter, exists := span.specialFindSplicePoint(offset, _KindSpecialCheckFinalizer) 2294 if exists { 2295 for { 2296 s := *iter 2297 if s == nil { 2298 // Reached the end of the linked list. Stop searching at this point. 2299 break 2300 } 2301 if offset == s.offset && _KindSpecialCheckFinalizer == s.kind && 2302 (*specialCheckFinalizer)(unsafe.Pointer(s)).cleanupID == cleanupID { 2303 // The special is a cleanup and contains a matching cleanup id. 2304 *iter = s.next 2305 found = s 2306 break 2307 } 2308 if offset < s.offset || (offset == s.offset && _KindSpecialCheckFinalizer < s.kind) { 2309 // The special is outside the region specified for that kind of 2310 // special. The specials are sorted by kind. 2311 break 2312 } 2313 // Try the next special. 2314 iter = &s.next 2315 } 2316 } 2317 if span.specials == nil { 2318 spanHasNoSpecials(span) 2319 } 2320 unlock(&span.speciallock) 2321 releasem(mp) 2322 2323 if found == nil { 2324 return 2325 } 2326 lock(&mheap_.speciallock) 2327 mheap_.specialCheckFinalizerAlloc.free(unsafe.Pointer(found)) 2328 unlock(&mheap_.speciallock) 2329 } 2330 2331 // Indicates that an allocation is a tiny block. 2332 // Used only if debug.checkfinalizers != 0. 2333 type specialTinyBlock struct { 2334 _ sys.NotInHeap 2335 special special 2336 } 2337 2338 // setTinyBlockContext marks an allocation as a tiny block to diagnostics like 2339 // checkfinalizer. 2340 // 2341 // A tiny block is only marked if it actually contains more than one distinct 2342 // value, since we're using this for debugging. 2343 func setTinyBlockContext(ptr unsafe.Pointer) { 2344 lock(&mheap_.speciallock) 2345 s := (*specialTinyBlock)(mheap_.specialTinyBlockAlloc.alloc()) 2346 unlock(&mheap_.speciallock) 2347 s.special.kind = _KindSpecialTinyBlock 2348 2349 mp := acquirem() 2350 addspecial(ptr, &s.special, false) 2351 releasem(mp) 2352 KeepAlive(ptr) 2353 } 2354 2355 // inTinyBlock returns whether ptr is in a tiny alloc block, at one point grouped 2356 // with other distinct values. 2357 func inTinyBlock(ptr uintptr) bool { 2358 assertWorldStopped() 2359 2360 ptr = alignDown(ptr, maxTinySize) 2361 span := spanOfHeap(ptr) 2362 if span == nil { 2363 return false 2364 } 2365 offset := ptr - span.base() 2366 _, exists := span.specialFindSplicePoint(offset, _KindSpecialTinyBlock) 2367 return exists 2368 } 2369 2370 // The described object has a weak pointer. 2371 // 2372 // Weak pointers in the GC have the following invariants: 2373 // 2374 // - Strong-to-weak conversions must ensure the strong pointer 2375 // remains live until the weak handle is installed. This ensures 2376 // that creating a weak pointer cannot fail. 2377 // 2378 // - Weak-to-strong conversions require the weakly-referenced 2379 // object to be swept before the conversion may proceed. This 2380 // ensures that weak-to-strong conversions cannot resurrect 2381 // dead objects by sweeping them before that happens. 2382 // 2383 // - Weak handles are unique and canonical for each byte offset into 2384 // an object that a strong pointer may point to, until an object 2385 // becomes unreachable. 2386 // 2387 // - Weak handles contain nil as soon as an object becomes unreachable 2388 // the first time, before a finalizer makes it reachable again. New 2389 // weak handles created after resurrection are newly unique. 2390 // 2391 // specialWeakHandle is allocated from non-GC'd memory, so any heap 2392 // pointers must be specially handled. 2393 type specialWeakHandle struct { 2394 _ sys.NotInHeap 2395 special special 2396 // handle is a reference to the actual weak pointer. 2397 // It is always heap-allocated and must be explicitly kept 2398 // live so long as this special exists. 2399 handle *atomic.Uintptr 2400 } 2401 2402 //go:linkname internal_weak_runtime_registerWeakPointer weak.runtime_registerWeakPointer 2403 func internal_weak_runtime_registerWeakPointer(p unsafe.Pointer) unsafe.Pointer { 2404 return unsafe.Pointer(getOrAddWeakHandle(p)) 2405 } 2406 2407 //go:linkname internal_weak_runtime_makeStrongFromWeak weak.runtime_makeStrongFromWeak 2408 func internal_weak_runtime_makeStrongFromWeak(u unsafe.Pointer) unsafe.Pointer { 2409 handle := (*atomic.Uintptr)(u) 2410 2411 // Prevent preemption. We want to make sure that another GC cycle can't start 2412 // and that work.strongFromWeak.block can't change out from under us. 2413 mp := acquirem() 2414 2415 // Yield to the GC if necessary. 2416 if work.strongFromWeak.block { 2417 releasem(mp) 2418 2419 // Try to park and wait for mark termination. 2420 // N.B. gcParkStrongFromWeak calls acquirem before returning. 2421 mp = gcParkStrongFromWeak() 2422 } 2423 2424 p := handle.Load() 2425 if p == 0 { 2426 releasem(mp) 2427 return nil 2428 } 2429 // Be careful. p may or may not refer to valid memory anymore, as it could've been 2430 // swept and released already. It's always safe to ensure a span is swept, though, 2431 // even if it's just some random span. 2432 span := spanOfHeap(p) 2433 if span == nil { 2434 // If it's immortal, then just return the pointer. 2435 // 2436 // Stay non-preemptible so the GC can't see us convert this potentially 2437 // completely bogus value to an unsafe.Pointer. 2438 if isGoPointerWithoutSpan(unsafe.Pointer(p)) { 2439 releasem(mp) 2440 return unsafe.Pointer(p) 2441 } 2442 // It's heap-allocated, so the span probably just got swept and released. 2443 releasem(mp) 2444 return nil 2445 } 2446 // Ensure the span is swept. 2447 span.ensureSwept() 2448 2449 // Now we can trust whatever we get from handle, so make a strong pointer. 2450 // 2451 // Even if we just swept some random span that doesn't contain this object, because 2452 // this object is long dead and its memory has since been reused, we'll just observe nil. 2453 ptr := unsafe.Pointer(handle.Load()) 2454 2455 // This is responsible for maintaining the same GC-related 2456 // invariants as the Yuasa part of the write barrier. During 2457 // the mark phase, it's possible that we just created the only 2458 // valid pointer to the object pointed to by ptr. If it's only 2459 // ever referenced from our stack, and our stack is blackened 2460 // already, we could fail to mark it. So, mark it now. 2461 if gcphase != _GCoff { 2462 shade(uintptr(ptr)) 2463 } 2464 releasem(mp) 2465 2466 // Explicitly keep ptr alive. This seems unnecessary since we return ptr, 2467 // but let's be explicit since it's important we keep ptr alive across the 2468 // call to shade. 2469 KeepAlive(ptr) 2470 return ptr 2471 } 2472 2473 // gcParkStrongFromWeak puts the current goroutine on the weak->strong queue and parks. 2474 func gcParkStrongFromWeak() *m { 2475 // Prevent preemption as we check strongFromWeak, so it can't change out from under us. 2476 mp := acquirem() 2477 2478 for work.strongFromWeak.block { 2479 lock(&work.strongFromWeak.lock) 2480 releasem(mp) // N.B. Holding the lock prevents preemption. 2481 2482 // Queue ourselves up. 2483 work.strongFromWeak.q.pushBack(getg()) 2484 2485 // Park. 2486 goparkunlock(&work.strongFromWeak.lock, waitReasonGCWeakToStrongWait, traceBlockGCWeakToStrongWait, 2) 2487 2488 // Re-acquire the current M since we're going to check the condition again. 2489 mp = acquirem() 2490 2491 // Re-check condition. We may have awoken in the next GC's mark termination phase. 2492 } 2493 return mp 2494 } 2495 2496 // gcWakeAllStrongFromWeak wakes all currently blocked weak->strong 2497 // conversions. This is used at the end of a GC cycle. 2498 // 2499 // work.strongFromWeak.block must be false to prevent woken goroutines 2500 // from immediately going back to sleep. 2501 func gcWakeAllStrongFromWeak() { 2502 lock(&work.strongFromWeak.lock) 2503 list := work.strongFromWeak.q.popList() 2504 injectglist(&list) 2505 unlock(&work.strongFromWeak.lock) 2506 } 2507 2508 // Retrieves or creates a weak pointer handle for the object p. 2509 func getOrAddWeakHandle(p unsafe.Pointer) *atomic.Uintptr { 2510 if debug.sbrk != 0 { 2511 // debug.sbrk never frees memory, so it'll never go nil. However, we do still 2512 // need a weak handle that's specific to p. Use the immortal weak handle map. 2513 // Keep p alive across the call to getOrAdd defensively, though it doesn't 2514 // really matter in this particular case. 2515 handle := mheap_.immortalWeakHandles.getOrAdd(uintptr(p)) 2516 KeepAlive(p) 2517 return handle 2518 } 2519 2520 // First try to retrieve without allocating. 2521 if handle := getWeakHandle(p); handle != nil { 2522 // Keep p alive for the duration of the function to ensure 2523 // that it cannot die while we're trying to do this. 2524 KeepAlive(p) 2525 return handle 2526 } 2527 2528 lock(&mheap_.speciallock) 2529 s := (*specialWeakHandle)(mheap_.specialWeakHandleAlloc.alloc()) 2530 unlock(&mheap_.speciallock) 2531 2532 // N.B. Pad the weak handle to ensure it doesn't share a tiny 2533 // block with any other allocations. This can lead to leaks, such 2534 // as in go.dev/issue/76007. As an alternative, we could consider 2535 // using the currently-unused 8-byte noscan size class. 2536 type weakHandleBox struct { 2537 h atomic.Uintptr 2538 _ [maxTinySize - unsafe.Sizeof(atomic.Uintptr{})]byte 2539 } 2540 handle := &(new(weakHandleBox).h) 2541 s.special.kind = _KindSpecialWeakHandle 2542 s.handle = handle 2543 handle.Store(uintptr(p)) 2544 if addspecial(p, &s.special, false) { 2545 // This is responsible for maintaining the same 2546 // GC-related invariants as markrootSpans in any 2547 // situation where it's possible that markrootSpans 2548 // has already run but mark termination hasn't yet. 2549 if gcphase != _GCoff { 2550 mp := acquirem() 2551 gcw := &mp.p.ptr().gcw 2552 // Mark the weak handle itself, since the 2553 // special isn't part of the GC'd heap. 2554 scanblock(uintptr(unsafe.Pointer(&s.handle)), goarch.PtrSize, &oneptrmask[0], gcw, nil) 2555 releasem(mp) 2556 } 2557 2558 // Keep p alive for the duration of the function to ensure 2559 // that it cannot die while we're trying to do this. 2560 // 2561 // Same for handle, which is only stored in the special. 2562 // There's a window where it might die if we don't keep it 2563 // alive explicitly. Returning it here is probably good enough, 2564 // but let's be defensive and explicit. See #70455. 2565 KeepAlive(p) 2566 KeepAlive(handle) 2567 return handle 2568 } 2569 2570 // There was an existing handle. Free the special 2571 // and try again. We must succeed because we're explicitly 2572 // keeping p live until the end of this function. Either 2573 // we, or someone else, must have succeeded, because we can 2574 // only fail in the event of a race, and p will still be 2575 // be valid no matter how much time we spend here. 2576 lock(&mheap_.speciallock) 2577 mheap_.specialWeakHandleAlloc.free(unsafe.Pointer(s)) 2578 unlock(&mheap_.speciallock) 2579 2580 handle = getWeakHandle(p) 2581 if handle == nil { 2582 throw("failed to get or create weak handle") 2583 } 2584 2585 // Keep p alive for the duration of the function to ensure 2586 // that it cannot die while we're trying to do this. 2587 // 2588 // Same for handle, just to be defensive. 2589 KeepAlive(p) 2590 KeepAlive(handle) 2591 return handle 2592 } 2593 2594 func getWeakHandle(p unsafe.Pointer) *atomic.Uintptr { 2595 span := spanOfHeap(uintptr(p)) 2596 if span == nil { 2597 if isGoPointerWithoutSpan(p) { 2598 return mheap_.immortalWeakHandles.getOrAdd(uintptr(p)) 2599 } 2600 throw("getWeakHandle on invalid pointer") 2601 } 2602 2603 // Ensure that the span is swept. 2604 // Sweeping accesses the specials list w/o locks, so we have 2605 // to synchronize with it. And it's just much safer. 2606 mp := acquirem() 2607 span.ensureSwept() 2608 2609 offset := uintptr(p) - span.base() 2610 2611 lock(&span.speciallock) 2612 2613 // Find the existing record and return the handle if one exists. 2614 var handle *atomic.Uintptr 2615 iter, exists := span.specialFindSplicePoint(offset, _KindSpecialWeakHandle) 2616 if exists { 2617 handle = ((*specialWeakHandle)(unsafe.Pointer(*iter))).handle 2618 } 2619 unlock(&span.speciallock) 2620 releasem(mp) 2621 2622 // Keep p alive for the duration of the function to ensure 2623 // that it cannot die while we're trying to do this. 2624 KeepAlive(p) 2625 return handle 2626 } 2627 2628 type immortalWeakHandleMap struct { 2629 root atomic.UnsafePointer // *immortalWeakHandle (can't use generics because it's notinheap) 2630 } 2631 2632 // immortalWeakHandle is a lock-free append-only hash-trie. 2633 // 2634 // Key features: 2635 // - 2-ary trie. Child nodes are indexed by the highest bit (remaining) of the hash of the address. 2636 // - New nodes are placed at the first empty level encountered. 2637 // - When the first child is added to a node, the existing value is not moved into a child. 2638 // This means that we must check the value at each level, not just at the leaf. 2639 // - No deletion or rebalancing. 2640 // - Intentionally devolves into a linked list on hash collisions (the hash bits will all 2641 // get shifted out during iteration, and new nodes will just be appended to the 0th child). 2642 type immortalWeakHandle struct { 2643 _ sys.NotInHeap 2644 2645 children [2]atomic.UnsafePointer // *immortalObjectMapNode (can't use generics because it's notinheap) 2646 ptr uintptr // &ptr is the weak handle 2647 } 2648 2649 // handle returns a canonical weak handle. 2650 func (h *immortalWeakHandle) handle() *atomic.Uintptr { 2651 // N.B. Since we just need an *atomic.Uintptr that never changes, we can trivially 2652 // reference ptr to save on some memory in immortalWeakHandle and avoid extra atomics 2653 // in getOrAdd. 2654 return (*atomic.Uintptr)(unsafe.Pointer(&h.ptr)) 2655 } 2656 2657 // getOrAdd introduces p, which must be a pointer to immortal memory (for example, a linker-allocated 2658 // object) and returns a weak handle. The weak handle will never become nil. 2659 func (tab *immortalWeakHandleMap) getOrAdd(p uintptr) *atomic.Uintptr { 2660 var newNode *immortalWeakHandle 2661 m := &tab.root 2662 hash := memhash(abi.NoEscape(unsafe.Pointer(&p)), 0, goarch.PtrSize) 2663 hashIter := hash 2664 for { 2665 n := (*immortalWeakHandle)(m.Load()) 2666 if n == nil { 2667 // Try to insert a new map node. We may end up discarding 2668 // this node if we fail to insert because it turns out the 2669 // value is already in the map. 2670 // 2671 // The discard will only happen if two threads race on inserting 2672 // the same value. Both might create nodes, but only one will 2673 // succeed on insertion. If two threads race to insert two 2674 // different values, then both nodes will *always* get inserted, 2675 // because the equality checking below will always fail. 2676 // 2677 // Performance note: contention on insertion is likely to be 2678 // higher for small maps, but since this data structure is 2679 // append-only, either the map stays small because there isn't 2680 // much activity, or the map gets big and races to insert on 2681 // the same node are much less likely. 2682 if newNode == nil { 2683 newNode = (*immortalWeakHandle)(persistentalloc(unsafe.Sizeof(immortalWeakHandle{}), goarch.PtrSize, &memstats.gcMiscSys)) 2684 newNode.ptr = p 2685 } 2686 if m.CompareAndSwapNoWB(nil, unsafe.Pointer(newNode)) { 2687 return newNode.handle() 2688 } 2689 // Reload n. Because pointers are only stored once, 2690 // we must have lost the race, and therefore n is not nil 2691 // anymore. 2692 n = (*immortalWeakHandle)(m.Load()) 2693 } 2694 if n.ptr == p { 2695 return n.handle() 2696 } 2697 m = &n.children[hashIter>>(8*goarch.PtrSize-1)] 2698 hashIter <<= 1 2699 } 2700 } 2701 2702 // The described object is being heap profiled. 2703 type specialprofile struct { 2704 _ sys.NotInHeap 2705 special special 2706 b *bucket 2707 } 2708 2709 // Set the heap profile bucket associated with addr to b. 2710 func setprofilebucket(p unsafe.Pointer, b *bucket) { 2711 lock(&mheap_.speciallock) 2712 s := (*specialprofile)(mheap_.specialprofilealloc.alloc()) 2713 unlock(&mheap_.speciallock) 2714 s.special.kind = _KindSpecialProfile 2715 s.b = b 2716 if !addspecial(p, &s.special, false) { 2717 throw("setprofilebucket: profile already set") 2718 } 2719 } 2720 2721 // specialReachable tracks whether an object is reachable on the next 2722 // GC cycle. This is used by testing. 2723 type specialReachable struct { 2724 special special 2725 done bool 2726 reachable bool 2727 } 2728 2729 // specialPinCounter tracks whether an object is pinned multiple times. 2730 type specialPinCounter struct { 2731 special special 2732 counter uintptr 2733 } 2734 2735 // specialSecret tracks whether we need to zero an object immediately 2736 // upon freeing. 2737 type specialSecret struct { 2738 _ sys.NotInHeap 2739 special special 2740 size uintptr 2741 } 2742 2743 // specialsIter helps iterate over specials lists. 2744 type specialsIter struct { 2745 pprev **special 2746 s *special 2747 } 2748 2749 func newSpecialsIter(span *mspan) specialsIter { 2750 return specialsIter{&span.specials, span.specials} 2751 } 2752 2753 func (i *specialsIter) valid() bool { 2754 return i.s != nil 2755 } 2756 2757 func (i *specialsIter) next() { 2758 i.pprev = &i.s.next 2759 i.s = *i.pprev 2760 } 2761 2762 // unlinkAndNext removes the current special from the list and moves 2763 // the iterator to the next special. It returns the unlinked special. 2764 func (i *specialsIter) unlinkAndNext() *special { 2765 cur := i.s 2766 i.s = cur.next 2767 *i.pprev = i.s 2768 return cur 2769 } 2770 2771 // freeSpecial performs any cleanup on special s and deallocates it. 2772 // s must already be unlinked from the specials list. 2773 // TODO(mknyszek): p and size together DO NOT represent a valid allocation. 2774 // size is the size of the allocation block in the span (mspan.elemsize), and p is 2775 // whatever pointer the special was attached to, which need not point to the 2776 // beginning of the block, though it may. 2777 // Consider passing the arguments differently to avoid giving the impression 2778 // that p and size together represent an address range. 2779 func freeSpecial(s *special, p unsafe.Pointer, size uintptr) { 2780 switch s.kind { 2781 case _KindSpecialFinalizer: 2782 sf := (*specialfinalizer)(unsafe.Pointer(s)) 2783 queuefinalizer(p, sf.fn, sf.nret, sf.fint, sf.ot) 2784 lock(&mheap_.speciallock) 2785 mheap_.specialfinalizeralloc.free(unsafe.Pointer(sf)) 2786 unlock(&mheap_.speciallock) 2787 case _KindSpecialWeakHandle: 2788 sw := (*specialWeakHandle)(unsafe.Pointer(s)) 2789 sw.handle.Store(0) 2790 lock(&mheap_.speciallock) 2791 mheap_.specialWeakHandleAlloc.free(unsafe.Pointer(s)) 2792 unlock(&mheap_.speciallock) 2793 case _KindSpecialProfile: 2794 sp := (*specialprofile)(unsafe.Pointer(s)) 2795 mProf_Free(sp.b) 2796 lock(&mheap_.speciallock) 2797 mheap_.specialprofilealloc.free(unsafe.Pointer(sp)) 2798 unlock(&mheap_.speciallock) 2799 case _KindSpecialReachable: 2800 sp := (*specialReachable)(unsafe.Pointer(s)) 2801 sp.done = true 2802 // The creator frees these. 2803 case _KindSpecialPinCounter: 2804 lock(&mheap_.speciallock) 2805 mheap_.specialPinCounterAlloc.free(unsafe.Pointer(s)) 2806 unlock(&mheap_.speciallock) 2807 case _KindSpecialCleanup: 2808 sc := (*specialCleanup)(unsafe.Pointer(s)) 2809 // Cleanups, unlike finalizers, do not resurrect the objects 2810 // they're attached to, so we only need to pass the cleanup 2811 // function, not the object. 2812 gcCleanups.enqueue(sc.cleanup) 2813 lock(&mheap_.speciallock) 2814 mheap_.specialCleanupAlloc.free(unsafe.Pointer(sc)) 2815 unlock(&mheap_.speciallock) 2816 case _KindSpecialCheckFinalizer: 2817 sc := (*specialCheckFinalizer)(unsafe.Pointer(s)) 2818 lock(&mheap_.speciallock) 2819 mheap_.specialCheckFinalizerAlloc.free(unsafe.Pointer(sc)) 2820 unlock(&mheap_.speciallock) 2821 case _KindSpecialTinyBlock: 2822 st := (*specialTinyBlock)(unsafe.Pointer(s)) 2823 lock(&mheap_.speciallock) 2824 mheap_.specialTinyBlockAlloc.free(unsafe.Pointer(st)) 2825 unlock(&mheap_.speciallock) 2826 case _KindSpecialBubble: 2827 st := (*specialBubble)(unsafe.Pointer(s)) 2828 lock(&mheap_.speciallock) 2829 mheap_.specialBubbleAlloc.free(unsafe.Pointer(st)) 2830 unlock(&mheap_.speciallock) 2831 case _KindSpecialSecret: 2832 ss := (*specialSecret)(unsafe.Pointer(s)) 2833 // p is the actual byte location that the special was 2834 // attached to, but the size argument is the span 2835 // element size. If we were to zero out using the size 2836 // argument, we'd trounce over adjacent memory in cases 2837 // where the allocation contains a header. Hence, we use 2838 // the user-visible size which we stash in the special itself. 2839 // 2840 // p always points to the beginning of the user-visible 2841 // allocation since the only way to attach a secret special 2842 // is via the allocation path. This isn't universal for 2843 // tiny allocs, but we avoid them in mallocgc anyway. 2844 memclrNoHeapPointers(p, ss.size) 2845 lock(&mheap_.speciallock) 2846 mheap_.specialSecretAlloc.free(unsafe.Pointer(s)) 2847 unlock(&mheap_.speciallock) 2848 default: 2849 throw("bad special kind") 2850 panic("not reached") 2851 } 2852 } 2853 2854 // gcBits is an alloc/mark bitmap. This is always used as gcBits.x. 2855 type gcBits struct { 2856 _ sys.NotInHeap 2857 x uint8 2858 } 2859 2860 // bytep returns a pointer to the n'th byte of b. 2861 func (b *gcBits) bytep(n uintptr) *uint8 { 2862 return addb(&b.x, n) 2863 } 2864 2865 // bitp returns a pointer to the byte containing bit n and a mask for 2866 // selecting that bit from *bytep. 2867 func (b *gcBits) bitp(n uintptr) (bytep *uint8, mask uint8) { 2868 return b.bytep(n / 8), 1 << (n % 8) 2869 } 2870 2871 const gcBitsChunkBytes = uintptr(64 << 10) 2872 const gcBitsHeaderBytes = unsafe.Sizeof(gcBitsHeader{}) 2873 2874 type gcBitsHeader struct { 2875 free uintptr // free is the index into bits of the next free byte. 2876 next uintptr // *gcBits triggers recursive type bug. (issue 14620) 2877 } 2878 2879 type gcBitsArena struct { 2880 _ sys.NotInHeap 2881 // gcBitsHeader // side step recursive type bug (issue 14620) by including fields by hand. 2882 free uintptr // free is the index into bits of the next free byte; read/write atomically 2883 next *gcBitsArena 2884 bits [gcBitsChunkBytes - gcBitsHeaderBytes]gcBits 2885 } 2886 2887 var gcBitsArenas struct { 2888 lock mutex 2889 free *gcBitsArena 2890 next *gcBitsArena // Read atomically. Write atomically under lock. 2891 current *gcBitsArena 2892 previous *gcBitsArena 2893 } 2894 2895 // tryAlloc allocates from b or returns nil if b does not have enough room. 2896 // This is safe to call concurrently. 2897 func (b *gcBitsArena) tryAlloc(bytes uintptr) *gcBits { 2898 if b == nil || atomic.Loaduintptr(&b.free)+bytes > uintptr(len(b.bits)) { 2899 return nil 2900 } 2901 // Try to allocate from this block. 2902 end := atomic.Xadduintptr(&b.free, bytes) 2903 if end > uintptr(len(b.bits)) { 2904 return nil 2905 } 2906 // There was enough room. 2907 start := end - bytes 2908 return &b.bits[start] 2909 } 2910 2911 // newMarkBits returns a pointer to 8 byte aligned bytes 2912 // to be used for a span's mark bits. 2913 func newMarkBits(nelems uintptr) *gcBits { 2914 blocksNeeded := (nelems + 63) / 64 2915 bytesNeeded := blocksNeeded * 8 2916 2917 // Try directly allocating from the current head arena. 2918 head := (*gcBitsArena)(atomic.Loadp(unsafe.Pointer(&gcBitsArenas.next))) 2919 if p := head.tryAlloc(bytesNeeded); p != nil { 2920 return p 2921 } 2922 2923 // There's not enough room in the head arena. We may need to 2924 // allocate a new arena. 2925 lock(&gcBitsArenas.lock) 2926 // Try the head arena again, since it may have changed. Now 2927 // that we hold the lock, the list head can't change, but its 2928 // free position still can. 2929 if p := gcBitsArenas.next.tryAlloc(bytesNeeded); p != nil { 2930 unlock(&gcBitsArenas.lock) 2931 return p 2932 } 2933 2934 // Allocate a new arena. This may temporarily drop the lock. 2935 fresh := newArenaMayUnlock() 2936 // If newArenaMayUnlock dropped the lock, another thread may 2937 // have put a fresh arena on the "next" list. Try allocating 2938 // from next again. 2939 if p := gcBitsArenas.next.tryAlloc(bytesNeeded); p != nil { 2940 // Put fresh back on the free list. 2941 // TODO: Mark it "already zeroed" 2942 fresh.next = gcBitsArenas.free 2943 gcBitsArenas.free = fresh 2944 unlock(&gcBitsArenas.lock) 2945 return p 2946 } 2947 2948 // Allocate from the fresh arena. We haven't linked it in yet, so 2949 // this cannot race and is guaranteed to succeed. 2950 p := fresh.tryAlloc(bytesNeeded) 2951 if p == nil { 2952 throw("markBits overflow") 2953 } 2954 2955 // Add the fresh arena to the "next" list. 2956 fresh.next = gcBitsArenas.next 2957 atomic.StorepNoWB(unsafe.Pointer(&gcBitsArenas.next), unsafe.Pointer(fresh)) 2958 2959 unlock(&gcBitsArenas.lock) 2960 return p 2961 } 2962 2963 // newAllocBits returns a pointer to 8 byte aligned bytes 2964 // to be used for this span's alloc bits. 2965 // newAllocBits is used to provide newly initialized spans 2966 // allocation bits. For spans not being initialized the 2967 // mark bits are repurposed as allocation bits when 2968 // the span is swept. 2969 func newAllocBits(nelems uintptr) *gcBits { 2970 return newMarkBits(nelems) 2971 } 2972 2973 // nextMarkBitArenaEpoch establishes a new epoch for the arenas 2974 // holding the mark bits. The arenas are named relative to the 2975 // current GC cycle which is demarcated by the call to finishweep_m. 2976 // 2977 // All current spans have been swept. 2978 // During that sweep each span allocated room for its gcmarkBits in 2979 // gcBitsArenas.next block. gcBitsArenas.next becomes the gcBitsArenas.current 2980 // where the GC will mark objects and after each span is swept these bits 2981 // will be used to allocate objects. 2982 // gcBitsArenas.current becomes gcBitsArenas.previous where the span's 2983 // gcAllocBits live until all the spans have been swept during this GC cycle. 2984 // The span's sweep extinguishes all the references to gcBitsArenas.previous 2985 // by pointing gcAllocBits into the gcBitsArenas.current. 2986 // The gcBitsArenas.previous is released to the gcBitsArenas.free list. 2987 func nextMarkBitArenaEpoch() { 2988 lock(&gcBitsArenas.lock) 2989 if gcBitsArenas.previous != nil { 2990 if gcBitsArenas.free == nil { 2991 gcBitsArenas.free = gcBitsArenas.previous 2992 } else { 2993 // Find end of previous arenas. 2994 last := gcBitsArenas.previous 2995 for last = gcBitsArenas.previous; last.next != nil; last = last.next { 2996 } 2997 last.next = gcBitsArenas.free 2998 gcBitsArenas.free = gcBitsArenas.previous 2999 } 3000 } 3001 gcBitsArenas.previous = gcBitsArenas.current 3002 gcBitsArenas.current = gcBitsArenas.next 3003 atomic.StorepNoWB(unsafe.Pointer(&gcBitsArenas.next), nil) // newMarkBits calls newArena when needed 3004 unlock(&gcBitsArenas.lock) 3005 } 3006 3007 // newArenaMayUnlock allocates and zeroes a gcBits arena. 3008 // The caller must hold gcBitsArena.lock. This may temporarily release it. 3009 func newArenaMayUnlock() *gcBitsArena { 3010 var result *gcBitsArena 3011 if gcBitsArenas.free == nil { 3012 unlock(&gcBitsArenas.lock) 3013 result = (*gcBitsArena)(sysAlloc(gcBitsChunkBytes, &memstats.gcMiscSys, "gc bits")) 3014 if result == nil { 3015 throw("runtime: cannot allocate memory") 3016 } 3017 lock(&gcBitsArenas.lock) 3018 } else { 3019 result = gcBitsArenas.free 3020 gcBitsArenas.free = gcBitsArenas.free.next 3021 memclrNoHeapPointers(unsafe.Pointer(result), gcBitsChunkBytes) 3022 } 3023 result.next = nil 3024 // If result.bits is not 8 byte aligned adjust index so 3025 // that &result.bits[result.free] is 8 byte aligned. 3026 if unsafe.Offsetof(gcBitsArena{}.bits)&7 == 0 { 3027 result.free = 0 3028 } else { 3029 result.free = 8 - (uintptr(unsafe.Pointer(&result.bits[0])) & 7) 3030 } 3031 return result 3032 } 3033