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