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