github.com/aloncn/graphics-go@v0.0.1/src/runtime/mbitmap.go (about) 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 // Garbage collector: type and heap bitmaps. 6 // 7 // Stack, data, and bss bitmaps 8 // 9 // Stack frames and global variables in the data and bss sections are described 10 // by 1-bit bitmaps in which 0 means uninteresting and 1 means live pointer 11 // to be visited during GC. The bits in each byte are consumed starting with 12 // the low bit: 1<<0, 1<<1, and so on. 13 // 14 // Heap bitmap 15 // 16 // The allocated heap comes from a subset of the memory in the range [start, used), 17 // where start == mheap_.arena_start and used == mheap_.arena_used. 18 // The heap bitmap comprises 2 bits for each pointer-sized word in that range, 19 // stored in bytes indexed backward in memory from start. 20 // That is, the byte at address start-1 holds the 2-bit entries for the four words 21 // start through start+3*ptrSize, the byte at start-2 holds the entries for 22 // start+4*ptrSize through start+7*ptrSize, and so on. 23 // 24 // In each 2-bit entry, the lower bit holds the same information as in the 1-bit 25 // bitmaps: 0 means uninteresting and 1 means live pointer to be visited during GC. 26 // The meaning of the high bit depends on the position of the word being described 27 // in its allocated object. In the first word, the high bit is the GC ``marked'' bit. 28 // In the second word, the high bit is the GC ``checkmarked'' bit (see below). 29 // In the third and later words, the high bit indicates that the object is still 30 // being described. In these words, if a bit pair with a high bit 0 is encountered, 31 // the low bit can also be assumed to be 0, and the object description is over. 32 // This 00 is called the ``dead'' encoding: it signals that the rest of the words 33 // in the object are uninteresting to the garbage collector. 34 // 35 // The 2-bit entries are split when written into the byte, so that the top half 36 // of the byte contains 4 mark bits and the bottom half contains 4 pointer bits. 37 // This form allows a copy from the 1-bit to the 4-bit form to keep the 38 // pointer bits contiguous, instead of having to space them out. 39 // 40 // The code makes use of the fact that the zero value for a heap bitmap 41 // has no live pointer bit set and is (depending on position), not marked, 42 // not checkmarked, and is the dead encoding. 43 // These properties must be preserved when modifying the encoding. 44 // 45 // Checkmarks 46 // 47 // In a concurrent garbage collector, one worries about failing to mark 48 // a live object due to mutations without write barriers or bugs in the 49 // collector implementation. As a sanity check, the GC has a 'checkmark' 50 // mode that retraverses the object graph with the world stopped, to make 51 // sure that everything that should be marked is marked. 52 // In checkmark mode, in the heap bitmap, the high bit of the 2-bit entry 53 // for the second word of the object holds the checkmark bit. 54 // When not in checkmark mode, this bit is set to 1. 55 // 56 // The smallest possible allocation is 8 bytes. On a 32-bit machine, that 57 // means every allocated object has two words, so there is room for the 58 // checkmark bit. On a 64-bit machine, however, the 8-byte allocation is 59 // just one word, so the second bit pair is not available for encoding the 60 // checkmark. However, because non-pointer allocations are combined 61 // into larger 16-byte (maxTinySize) allocations, a plain 8-byte allocation 62 // must be a pointer, so the type bit in the first word is not actually needed. 63 // It is still used in general, except in checkmark the type bit is repurposed 64 // as the checkmark bit and then reinitialized (to 1) as the type bit when 65 // finished. 66 67 package runtime 68 69 import ( 70 "runtime/internal/atomic" 71 "runtime/internal/sys" 72 "unsafe" 73 ) 74 75 const ( 76 bitPointer = 1 << 0 77 bitMarked = 1 << 4 78 79 heapBitsShift = 1 // shift offset between successive bitPointer or bitMarked entries 80 heapBitmapScale = sys.PtrSize * (8 / 2) // number of data bytes described by one heap bitmap byte 81 82 // all mark/pointer bits in a byte 83 bitMarkedAll = bitMarked | bitMarked<<heapBitsShift | bitMarked<<(2*heapBitsShift) | bitMarked<<(3*heapBitsShift) 84 bitPointerAll = bitPointer | bitPointer<<heapBitsShift | bitPointer<<(2*heapBitsShift) | bitPointer<<(3*heapBitsShift) 85 ) 86 87 // addb returns the byte pointer p+n. 88 //go:nowritebarrier 89 func addb(p *byte, n uintptr) *byte { 90 // Note: wrote out full expression instead of calling add(p, n) 91 // to reduce the number of temporaries generated by the 92 // compiler for this trivial expression during inlining. 93 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n)) 94 } 95 96 // subtractb returns the byte pointer p-n. 97 //go:nowritebarrier 98 func subtractb(p *byte, n uintptr) *byte { 99 // Note: wrote out full expression instead of calling add(p, -n) 100 // to reduce the number of temporaries generated by the 101 // compiler for this trivial expression during inlining. 102 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - n)) 103 } 104 105 // add1 returns the byte pointer p+1. 106 //go:nowritebarrier 107 func add1(p *byte) *byte { 108 // Note: wrote out full expression instead of calling addb(p, 1) 109 // to reduce the number of temporaries generated by the 110 // compiler for this trivial expression during inlining. 111 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1)) 112 } 113 114 // subtract1 returns the byte pointer p-1. 115 //go:nowritebarrier 116 // 117 // nosplit because it is used during write barriers and must not be preempted. 118 //go:nosplit 119 func subtract1(p *byte) *byte { 120 // Note: wrote out full expression instead of calling subtractb(p, 1) 121 // to reduce the number of temporaries generated by the 122 // compiler for this trivial expression during inlining. 123 return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - 1)) 124 } 125 126 // mHeap_MapBits is called each time arena_used is extended. 127 // It maps any additional bitmap memory needed for the new arena memory. 128 // It must be called with the expected new value of arena_used, 129 // *before* h.arena_used has been updated. 130 // Waiting to update arena_used until after the memory has been mapped 131 // avoids faults when other threads try access the bitmap immediately 132 // after observing the change to arena_used. 133 // 134 //go:nowritebarrier 135 func (h *mheap) mapBits(arena_used uintptr) { 136 // Caller has added extra mappings to the arena. 137 // Add extra mappings of bitmap words as needed. 138 // We allocate extra bitmap pieces in chunks of bitmapChunk. 139 const bitmapChunk = 8192 140 141 n := (arena_used - mheap_.arena_start) / heapBitmapScale 142 n = round(n, bitmapChunk) 143 n = round(n, sys.PhysPageSize) 144 if h.bitmap_mapped >= n { 145 return 146 } 147 148 sysMap(unsafe.Pointer(h.arena_start-n), n-h.bitmap_mapped, h.arena_reserved, &memstats.gc_sys) 149 h.bitmap_mapped = n 150 } 151 152 // heapBits provides access to the bitmap bits for a single heap word. 153 // The methods on heapBits take value receivers so that the compiler 154 // can more easily inline calls to those methods and registerize the 155 // struct fields independently. 156 type heapBits struct { 157 bitp *uint8 158 shift uint32 159 } 160 161 // heapBitsForAddr returns the heapBits for the address addr. 162 // The caller must have already checked that addr is in the range [mheap_.arena_start, mheap_.arena_used). 163 // 164 // nosplit because it is used during write barriers and must not be preempted. 165 //go:nosplit 166 func heapBitsForAddr(addr uintptr) heapBits { 167 // 2 bits per work, 4 pairs per byte, and a mask is hard coded. 168 off := (addr - mheap_.arena_start) / sys.PtrSize 169 return heapBits{(*uint8)(unsafe.Pointer(mheap_.arena_start - off/4 - 1)), uint32(off & 3)} 170 } 171 172 // heapBitsForSpan returns the heapBits for the span base address base. 173 func heapBitsForSpan(base uintptr) (hbits heapBits) { 174 if base < mheap_.arena_start || base >= mheap_.arena_used { 175 throw("heapBitsForSpan: base out of range") 176 } 177 hbits = heapBitsForAddr(base) 178 if hbits.shift != 0 { 179 throw("heapBitsForSpan: unaligned start") 180 } 181 return hbits 182 } 183 184 // heapBitsForObject returns the base address for the heap object 185 // containing the address p, along with the heapBits for base. 186 // If p does not point into a heap object, 187 // return base == 0 188 // otherwise return the base of the object. 189 // 190 // refBase and refOff optionally give the base address of the object 191 // in which the pointer p was found and the byte offset at which it 192 // was found. These are used for error reporting. 193 func heapBitsForObject(p, refBase, refOff uintptr) (base uintptr, hbits heapBits, s *mspan) { 194 arenaStart := mheap_.arena_start 195 if p < arenaStart || p >= mheap_.arena_used { 196 return 197 } 198 off := p - arenaStart 199 idx := off >> _PageShift 200 // p points into the heap, but possibly to the middle of an object. 201 // Consult the span table to find the block beginning. 202 k := p >> _PageShift 203 s = h_spans[idx] 204 if s == nil || pageID(k) < s.start || p >= s.limit || s.state != mSpanInUse { 205 if s == nil || s.state == _MSpanStack { 206 // If s is nil, the virtual address has never been part of the heap. 207 // This pointer may be to some mmap'd region, so we allow it. 208 // Pointers into stacks are also ok, the runtime manages these explicitly. 209 return 210 } 211 212 // The following ensures that we are rigorous about what data 213 // structures hold valid pointers. 214 if debug.invalidptr != 0 { 215 // Typically this indicates an incorrect use 216 // of unsafe or cgo to store a bad pointer in 217 // the Go heap. It may also indicate a runtime 218 // bug. 219 // 220 // TODO(austin): We could be more aggressive 221 // and detect pointers to unallocated objects 222 // in allocated spans. 223 printlock() 224 print("runtime: pointer ", hex(p)) 225 if s.state != mSpanInUse { 226 print(" to unallocated span") 227 } else { 228 print(" to unused region of span") 229 } 230 print("idx=", hex(idx), " span.start=", hex(s.start<<_PageShift), " span.limit=", hex(s.limit), " span.state=", s.state, "\n") 231 if refBase != 0 { 232 print("runtime: found in object at *(", hex(refBase), "+", hex(refOff), ")\n") 233 gcDumpObject("object", refBase, refOff) 234 } 235 throw("found bad pointer in Go heap (incorrect use of unsafe or cgo?)") 236 } 237 return 238 } 239 // If this span holds object of a power of 2 size, just mask off the bits to 240 // the interior of the object. Otherwise use the size to get the base. 241 if s.baseMask != 0 { 242 // optimize for power of 2 sized objects. 243 base = s.base() 244 base = base + (p-base)&s.baseMask 245 // base = p & s.baseMask is faster for small spans, 246 // but doesn't work for large spans. 247 // Overall, it's faster to use the more general computation above. 248 } else { 249 base = s.base() 250 if p-base >= s.elemsize { 251 // n := (p - base) / s.elemsize, using division by multiplication 252 n := uintptr(uint64(p-base) >> s.divShift * uint64(s.divMul) >> s.divShift2) 253 base += n * s.elemsize 254 } 255 } 256 // Now that we know the actual base, compute heapBits to return to caller. 257 hbits = heapBitsForAddr(base) 258 return 259 } 260 261 // prefetch the bits. 262 func (h heapBits) prefetch() { 263 prefetchnta(uintptr(unsafe.Pointer((h.bitp)))) 264 } 265 266 // next returns the heapBits describing the next pointer-sized word in memory. 267 // That is, if h describes address p, h.next() describes p+ptrSize. 268 // Note that next does not modify h. The caller must record the result. 269 // 270 // nosplit because it is used during write barriers and must not be preempted. 271 //go:nosplit 272 func (h heapBits) next() heapBits { 273 if h.shift < 3*heapBitsShift { 274 return heapBits{h.bitp, h.shift + heapBitsShift} 275 } 276 return heapBits{subtract1(h.bitp), 0} 277 } 278 279 // forward returns the heapBits describing n pointer-sized words ahead of h in memory. 280 // That is, if h describes address p, h.forward(n) describes p+n*ptrSize. 281 // h.forward(1) is equivalent to h.next(), just slower. 282 // Note that forward does not modify h. The caller must record the result. 283 // bits returns the heap bits for the current word. 284 func (h heapBits) forward(n uintptr) heapBits { 285 n += uintptr(h.shift) / heapBitsShift 286 return heapBits{subtractb(h.bitp, n/4), uint32(n%4) * heapBitsShift} 287 } 288 289 // The caller can test isMarked and isPointer by &-ing with bitMarked and bitPointer. 290 // The result includes in its higher bits the bits for subsequent words 291 // described by the same bitmap byte. 292 func (h heapBits) bits() uint32 { 293 return uint32(*h.bitp) >> h.shift 294 } 295 296 // isMarked reports whether the heap bits have the marked bit set. 297 // h must describe the initial word of the object. 298 func (h heapBits) isMarked() bool { 299 return *h.bitp&(bitMarked<<h.shift) != 0 300 } 301 302 // setMarked sets the marked bit in the heap bits, atomically. 303 // h must describe the initial word of the object. 304 func (h heapBits) setMarked() { 305 // Each byte of GC bitmap holds info for four words. 306 // Might be racing with other updates, so use atomic update always. 307 // We used to be clever here and use a non-atomic update in certain 308 // cases, but it's not worth the risk. 309 atomic.Or8(h.bitp, bitMarked<<h.shift) 310 } 311 312 // setMarkedNonAtomic sets the marked bit in the heap bits, non-atomically. 313 // h must describe the initial word of the object. 314 func (h heapBits) setMarkedNonAtomic() { 315 *h.bitp |= bitMarked << h.shift 316 } 317 318 // isPointer reports whether the heap bits describe a pointer word. 319 // h must describe the initial word of the object. 320 // 321 // nosplit because it is used during write barriers and must not be preempted. 322 //go:nosplit 323 func (h heapBits) isPointer() bool { 324 return (*h.bitp>>h.shift)&bitPointer != 0 325 } 326 327 // hasPointers reports whether the given object has any pointers. 328 // It must be told how large the object at h is, so that it does not read too 329 // far into the bitmap. 330 // h must describe the initial word of the object. 331 func (h heapBits) hasPointers(size uintptr) bool { 332 if size == sys.PtrSize { // 1-word objects are always pointers 333 return true 334 } 335 // Otherwise, at least a 2-word object, and at least 2-word aligned, 336 // so h.shift is either 0 or 2, so we know we can get the bits for the 337 // first two words out of *h.bitp. 338 // If either of the first two words is a pointer, not pointer free. 339 b := uint32(*h.bitp >> h.shift) 340 if b&(bitPointer|bitPointer<<heapBitsShift) != 0 { 341 return true 342 } 343 if size == 2*sys.PtrSize { 344 return false 345 } 346 // At least a 4-word object. Check scan bit (aka marked bit) in third word. 347 if h.shift == 0 { 348 return b&(bitMarked<<(2*heapBitsShift)) != 0 349 } 350 return uint32(*subtract1(h.bitp))&bitMarked != 0 351 } 352 353 // isCheckmarked reports whether the heap bits have the checkmarked bit set. 354 // It must be told how large the object at h is, because the encoding of the 355 // checkmark bit varies by size. 356 // h must describe the initial word of the object. 357 func (h heapBits) isCheckmarked(size uintptr) bool { 358 if size == sys.PtrSize { 359 return (*h.bitp>>h.shift)&bitPointer != 0 360 } 361 // All multiword objects are 2-word aligned, 362 // so we know that the initial word's 2-bit pair 363 // and the second word's 2-bit pair are in the 364 // same heap bitmap byte, *h.bitp. 365 return (*h.bitp>>(heapBitsShift+h.shift))&bitMarked != 0 366 } 367 368 // setCheckmarked sets the checkmarked bit. 369 // It must be told how large the object at h is, because the encoding of the 370 // checkmark bit varies by size. 371 // h must describe the initial word of the object. 372 func (h heapBits) setCheckmarked(size uintptr) { 373 if size == sys.PtrSize { 374 atomic.Or8(h.bitp, bitPointer<<h.shift) 375 return 376 } 377 atomic.Or8(h.bitp, bitMarked<<(heapBitsShift+h.shift)) 378 } 379 380 // heapBitsBulkBarrier executes writebarrierptr_nostore 381 // for every pointer slot in the memory range [p, p+size), 382 // using the heap bitmap to locate those pointer slots. 383 // This executes the write barriers necessary after a memmove. 384 // Both p and size must be pointer-aligned. 385 // The range [p, p+size) must lie within a single allocation. 386 // 387 // Callers should call heapBitsBulkBarrier immediately after 388 // calling memmove(p, src, size). This function is marked nosplit 389 // to avoid being preempted; the GC must not stop the goroutine 390 // between the memmove and the execution of the barriers. 391 // 392 // The heap bitmap is not maintained for allocations containing 393 // no pointers at all; any caller of heapBitsBulkBarrier must first 394 // make sure the underlying allocation contains pointers, usually 395 // by checking typ.kind&kindNoPointers. 396 // 397 //go:nosplit 398 func heapBitsBulkBarrier(p, size uintptr) { 399 if (p|size)&(sys.PtrSize-1) != 0 { 400 throw("heapBitsBulkBarrier: unaligned arguments") 401 } 402 if !writeBarrier.needed { 403 return 404 } 405 if !inheap(p) { 406 // If p is on the stack and in a higher frame than the 407 // caller, we either need to execute write barriers on 408 // it (which is what happens for normal stack writes 409 // through pointers to higher frames), or we need to 410 // force the mark termination stack scan to scan the 411 // frame containing p. 412 // 413 // Executing write barriers on p is complicated in the 414 // general case because we either need to unwind the 415 // stack to get the stack map, or we need the type's 416 // bitmap, which may be a GC program. 417 // 418 // Hence, we opt for forcing the re-scan to scan the 419 // frame containing p, which we can do by simply 420 // unwinding the stack barriers between the current SP 421 // and p's frame. 422 gp := getg().m.curg 423 if gp != nil && gp.stack.lo <= p && p < gp.stack.hi { 424 // Run on the system stack to give it more 425 // stack space. 426 systemstack(func() { 427 gcUnwindBarriers(gp, p) 428 }) 429 } 430 return 431 } 432 433 h := heapBitsForAddr(p) 434 for i := uintptr(0); i < size; i += sys.PtrSize { 435 if h.isPointer() { 436 x := (*uintptr)(unsafe.Pointer(p + i)) 437 writebarrierptr_nostore(x, *x) 438 } 439 h = h.next() 440 } 441 } 442 443 // typeBitsBulkBarrier executes writebarrierptr_nostore 444 // for every pointer slot in the memory range [p, p+size), 445 // using the type bitmap to locate those pointer slots. 446 // The type typ must correspond exactly to [p, p+size). 447 // This executes the write barriers necessary after a copy. 448 // Both p and size must be pointer-aligned. 449 // The type typ must have a plain bitmap, not a GC program. 450 // The only use of this function is in channel sends, and the 451 // 64 kB channel element limit takes care of this for us. 452 // 453 // Must not be preempted because it typically runs right after memmove, 454 // and the GC must not complete between those two. 455 // 456 //go:nosplit 457 func typeBitsBulkBarrier(typ *_type, p, size uintptr) { 458 if typ == nil { 459 throw("runtime: typeBitsBulkBarrier without type") 460 } 461 if typ.size != size { 462 println("runtime: typeBitsBulkBarrier with type ", *typ._string, " of size ", typ.size, " but memory size", size) 463 throw("runtime: invalid typeBitsBulkBarrier") 464 } 465 if typ.kind&kindGCProg != 0 { 466 println("runtime: typeBitsBulkBarrier with type ", *typ._string, " with GC prog") 467 throw("runtime: invalid typeBitsBulkBarrier") 468 } 469 if !writeBarrier.needed { 470 return 471 } 472 ptrmask := typ.gcdata 473 var bits uint32 474 for i := uintptr(0); i < typ.ptrdata; i += sys.PtrSize { 475 if i&(sys.PtrSize*8-1) == 0 { 476 bits = uint32(*ptrmask) 477 ptrmask = addb(ptrmask, 1) 478 } else { 479 bits = bits >> 1 480 } 481 if bits&1 != 0 { 482 x := (*uintptr)(unsafe.Pointer(p + i)) 483 writebarrierptr_nostore(x, *x) 484 } 485 } 486 } 487 488 // The methods operating on spans all require that h has been returned 489 // by heapBitsForSpan and that size, n, total are the span layout description 490 // returned by the mspan's layout method. 491 // If total > size*n, it means that there is extra leftover memory in the span, 492 // usually due to rounding. 493 // 494 // TODO(rsc): Perhaps introduce a different heapBitsSpan type. 495 496 // initSpan initializes the heap bitmap for a span. 497 func (h heapBits) initSpan(size, n, total uintptr) { 498 if total%heapBitmapScale != 0 { 499 throw("initSpan: unaligned length") 500 } 501 nbyte := total / heapBitmapScale 502 if sys.PtrSize == 8 && size == sys.PtrSize { 503 end := h.bitp 504 bitp := subtractb(end, nbyte-1) 505 for { 506 *bitp = bitPointerAll 507 if bitp == end { 508 break 509 } 510 bitp = add1(bitp) 511 } 512 return 513 } 514 memclr(unsafe.Pointer(subtractb(h.bitp, nbyte-1)), nbyte) 515 } 516 517 // initCheckmarkSpan initializes a span for being checkmarked. 518 // It clears the checkmark bits, which are set to 1 in normal operation. 519 func (h heapBits) initCheckmarkSpan(size, n, total uintptr) { 520 // The ptrSize == 8 is a compile-time constant false on 32-bit and eliminates this code entirely. 521 if sys.PtrSize == 8 && size == sys.PtrSize { 522 // Checkmark bit is type bit, bottom bit of every 2-bit entry. 523 // Only possible on 64-bit system, since minimum size is 8. 524 // Must clear type bit (checkmark bit) of every word. 525 // The type bit is the lower of every two-bit pair. 526 bitp := h.bitp 527 for i := uintptr(0); i < n; i += 4 { 528 *bitp &^= bitPointerAll 529 bitp = subtract1(bitp) 530 } 531 return 532 } 533 for i := uintptr(0); i < n; i++ { 534 *h.bitp &^= bitMarked << (heapBitsShift + h.shift) 535 h = h.forward(size / sys.PtrSize) 536 } 537 } 538 539 // clearCheckmarkSpan undoes all the checkmarking in a span. 540 // The actual checkmark bits are ignored, so the only work to do 541 // is to fix the pointer bits. (Pointer bits are ignored by scanobject 542 // but consulted by typedmemmove.) 543 func (h heapBits) clearCheckmarkSpan(size, n, total uintptr) { 544 // The ptrSize == 8 is a compile-time constant false on 32-bit and eliminates this code entirely. 545 if sys.PtrSize == 8 && size == sys.PtrSize { 546 // Checkmark bit is type bit, bottom bit of every 2-bit entry. 547 // Only possible on 64-bit system, since minimum size is 8. 548 // Must clear type bit (checkmark bit) of every word. 549 // The type bit is the lower of every two-bit pair. 550 bitp := h.bitp 551 for i := uintptr(0); i < n; i += 4 { 552 *bitp |= bitPointerAll 553 bitp = subtract1(bitp) 554 } 555 } 556 } 557 558 // heapBitsSweepSpan coordinates the sweeping of a span by reading 559 // and updating the corresponding heap bitmap entries. 560 // For each free object in the span, heapBitsSweepSpan sets the type 561 // bits for the first two words (or one for single-word objects) to typeDead 562 // and then calls f(p), where p is the object's base address. 563 // f is expected to add the object to a free list. 564 // For non-free objects, heapBitsSweepSpan turns off the marked bit. 565 func heapBitsSweepSpan(base, size, n uintptr, f func(uintptr)) { 566 h := heapBitsForSpan(base) 567 switch { 568 default: 569 throw("heapBitsSweepSpan") 570 case sys.PtrSize == 8 && size == sys.PtrSize: 571 // Consider mark bits in all four 2-bit entries of each bitmap byte. 572 bitp := h.bitp 573 for i := uintptr(0); i < n; i += 4 { 574 x := uint32(*bitp) 575 // Note that unlike the other size cases, we leave the pointer bits set here. 576 // These are initialized during initSpan when the span is created and left 577 // in place the whole time the span is used for pointer-sized objects. 578 // That lets heapBitsSetType avoid an atomic update to set the pointer bit 579 // during allocation. 580 if x&bitMarked != 0 { 581 x &^= bitMarked 582 } else { 583 f(base + i*sys.PtrSize) 584 } 585 if x&(bitMarked<<heapBitsShift) != 0 { 586 x &^= bitMarked << heapBitsShift 587 } else { 588 f(base + (i+1)*sys.PtrSize) 589 } 590 if x&(bitMarked<<(2*heapBitsShift)) != 0 { 591 x &^= bitMarked << (2 * heapBitsShift) 592 } else { 593 f(base + (i+2)*sys.PtrSize) 594 } 595 if x&(bitMarked<<(3*heapBitsShift)) != 0 { 596 x &^= bitMarked << (3 * heapBitsShift) 597 } else { 598 f(base + (i+3)*sys.PtrSize) 599 } 600 *bitp = uint8(x) 601 bitp = subtract1(bitp) 602 } 603 604 case size%(4*sys.PtrSize) == 0: 605 // Mark bit is in first word of each object. 606 // Each object starts at bit 0 of a heap bitmap byte. 607 bitp := h.bitp 608 step := size / heapBitmapScale 609 for i := uintptr(0); i < n; i++ { 610 x := uint32(*bitp) 611 if x&bitMarked != 0 { 612 x &^= bitMarked 613 } else { 614 x = 0 615 f(base + i*size) 616 } 617 *bitp = uint8(x) 618 bitp = subtractb(bitp, step) 619 } 620 621 case size%(4*sys.PtrSize) == 2*sys.PtrSize: 622 // Mark bit is in first word of each object, 623 // but every other object starts halfway through a heap bitmap byte. 624 // Unroll loop 2x to handle alternating shift count and step size. 625 bitp := h.bitp 626 step := size / heapBitmapScale 627 var i uintptr 628 for i = uintptr(0); i < n; i += 2 { 629 x := uint32(*bitp) 630 if x&bitMarked != 0 { 631 x &^= bitMarked 632 } else { 633 x &^= bitMarked | bitPointer | (bitMarked|bitPointer)<<heapBitsShift 634 f(base + i*size) 635 if size > 2*sys.PtrSize { 636 x = 0 637 } 638 } 639 *bitp = uint8(x) 640 if i+1 >= n { 641 break 642 } 643 bitp = subtractb(bitp, step) 644 x = uint32(*bitp) 645 if x&(bitMarked<<(2*heapBitsShift)) != 0 { 646 x &^= bitMarked << (2 * heapBitsShift) 647 } else { 648 x &^= (bitMarked|bitPointer)<<(2*heapBitsShift) | (bitMarked|bitPointer)<<(3*heapBitsShift) 649 f(base + (i+1)*size) 650 if size > 2*sys.PtrSize { 651 *subtract1(bitp) = 0 652 } 653 } 654 *bitp = uint8(x) 655 bitp = subtractb(bitp, step+1) 656 } 657 } 658 } 659 660 // heapBitsSetType records that the new allocation [x, x+size) 661 // holds in [x, x+dataSize) one or more values of type typ. 662 // (The number of values is given by dataSize / typ.size.) 663 // If dataSize < size, the fragment [x+dataSize, x+size) is 664 // recorded as non-pointer data. 665 // It is known that the type has pointers somewhere; 666 // malloc does not call heapBitsSetType when there are no pointers, 667 // because all free objects are marked as noscan during 668 // heapBitsSweepSpan. 669 // There can only be one allocation from a given span active at a time, 670 // so this code is not racing with other instances of itself, 671 // and we don't allocate from a span until it has been swept, 672 // so this code is not racing with heapBitsSweepSpan. 673 // It is, however, racing with the concurrent GC mark phase, 674 // which can be setting the mark bit in the leading 2-bit entry 675 // of an allocated block. The block we are modifying is not quite 676 // allocated yet, so the GC marker is not racing with updates to x's bits, 677 // but if the start or end of x shares a bitmap byte with an adjacent 678 // object, the GC marker is racing with updates to those object's mark bits. 679 func heapBitsSetType(x, size, dataSize uintptr, typ *_type) { 680 const doubleCheck = false // slow but helpful; enable to test modifications to this code 681 682 // dataSize is always size rounded up to the next malloc size class, 683 // except in the case of allocating a defer block, in which case 684 // size is sizeof(_defer{}) (at least 6 words) and dataSize may be 685 // arbitrarily larger. 686 // 687 // The checks for size == ptrSize and size == 2*ptrSize can therefore 688 // assume that dataSize == size without checking it explicitly. 689 690 if sys.PtrSize == 8 && size == sys.PtrSize { 691 // It's one word and it has pointers, it must be a pointer. 692 // In general we'd need an atomic update here if the 693 // concurrent GC were marking objects in this span, 694 // because each bitmap byte describes 3 other objects 695 // in addition to the one being allocated. 696 // However, since all allocated one-word objects are pointers 697 // (non-pointers are aggregated into tinySize allocations), 698 // initSpan sets the pointer bits for us. Nothing to do here. 699 if doubleCheck { 700 h := heapBitsForAddr(x) 701 if !h.isPointer() { 702 throw("heapBitsSetType: pointer bit missing") 703 } 704 } 705 return 706 } 707 708 h := heapBitsForAddr(x) 709 ptrmask := typ.gcdata // start of 1-bit pointer mask (or GC program, handled below) 710 711 // Heap bitmap bits for 2-word object are only 4 bits, 712 // so also shared with objects next to it; use atomic updates. 713 // This is called out as a special case primarily for 32-bit systems, 714 // so that on 32-bit systems the code below can assume all objects 715 // are 4-word aligned (because they're all 16-byte aligned). 716 if size == 2*sys.PtrSize { 717 if typ.size == sys.PtrSize { 718 // We're allocating a block big enough to hold two pointers. 719 // On 64-bit, that means the actual object must be two pointers, 720 // or else we'd have used the one-pointer-sized block. 721 // On 32-bit, however, this is the 8-byte block, the smallest one. 722 // So it could be that we're allocating one pointer and this was 723 // just the smallest block available. Distinguish by checking dataSize. 724 // (In general the number of instances of typ being allocated is 725 // dataSize/typ.size.) 726 if sys.PtrSize == 4 && dataSize == sys.PtrSize { 727 // 1 pointer. 728 if gcphase == _GCoff { 729 *h.bitp |= bitPointer << h.shift 730 } else { 731 atomic.Or8(h.bitp, bitPointer<<h.shift) 732 } 733 } else { 734 // 2-element slice of pointer. 735 if gcphase == _GCoff { 736 *h.bitp |= (bitPointer | bitPointer<<heapBitsShift) << h.shift 737 } else { 738 atomic.Or8(h.bitp, (bitPointer|bitPointer<<heapBitsShift)<<h.shift) 739 } 740 } 741 return 742 } 743 // Otherwise typ.size must be 2*ptrSize, and typ.kind&kindGCProg == 0. 744 if doubleCheck { 745 if typ.size != 2*sys.PtrSize || typ.kind&kindGCProg != 0 { 746 print("runtime: heapBitsSetType size=", size, " but typ.size=", typ.size, " gcprog=", typ.kind&kindGCProg != 0, "\n") 747 throw("heapBitsSetType") 748 } 749 } 750 b := uint32(*ptrmask) 751 hb := b & 3 752 if gcphase == _GCoff { 753 *h.bitp |= uint8(hb << h.shift) 754 } else { 755 atomic.Or8(h.bitp, uint8(hb<<h.shift)) 756 } 757 return 758 } 759 760 // Copy from 1-bit ptrmask into 2-bit bitmap. 761 // The basic approach is to use a single uintptr as a bit buffer, 762 // alternating between reloading the buffer and writing bitmap bytes. 763 // In general, one load can supply two bitmap byte writes. 764 // This is a lot of lines of code, but it compiles into relatively few 765 // machine instructions. 766 767 var ( 768 // Ptrmask input. 769 p *byte // last ptrmask byte read 770 b uintptr // ptrmask bits already loaded 771 nb uintptr // number of bits in b at next read 772 endp *byte // final ptrmask byte to read (then repeat) 773 endnb uintptr // number of valid bits in *endp 774 pbits uintptr // alternate source of bits 775 776 // Heap bitmap output. 777 w uintptr // words processed 778 nw uintptr // number of words to process 779 hbitp *byte // next heap bitmap byte to write 780 hb uintptr // bits being prepared for *hbitp 781 ) 782 783 hbitp = h.bitp 784 785 // Handle GC program. Delayed until this part of the code 786 // so that we can use the same double-checking mechanism 787 // as the 1-bit case. Nothing above could have encountered 788 // GC programs: the cases were all too small. 789 if typ.kind&kindGCProg != 0 { 790 heapBitsSetTypeGCProg(h, typ.ptrdata, typ.size, dataSize, size, addb(typ.gcdata, 4)) 791 if doubleCheck { 792 // Double-check the heap bits written by GC program 793 // by running the GC program to create a 1-bit pointer mask 794 // and then jumping to the double-check code below. 795 // This doesn't catch bugs shared between the 1-bit and 4-bit 796 // GC program execution, but it does catch mistakes specific 797 // to just one of those and bugs in heapBitsSetTypeGCProg's 798 // implementation of arrays. 799 lock(&debugPtrmask.lock) 800 if debugPtrmask.data == nil { 801 debugPtrmask.data = (*byte)(persistentalloc(1<<20, 1, &memstats.other_sys)) 802 } 803 ptrmask = debugPtrmask.data 804 runGCProg(addb(typ.gcdata, 4), nil, ptrmask, 1) 805 goto Phase4 806 } 807 return 808 } 809 810 // Note about sizes: 811 // 812 // typ.size is the number of words in the object, 813 // and typ.ptrdata is the number of words in the prefix 814 // of the object that contains pointers. That is, the final 815 // typ.size - typ.ptrdata words contain no pointers. 816 // This allows optimization of a common pattern where 817 // an object has a small header followed by a large scalar 818 // buffer. If we know the pointers are over, we don't have 819 // to scan the buffer's heap bitmap at all. 820 // The 1-bit ptrmasks are sized to contain only bits for 821 // the typ.ptrdata prefix, zero padded out to a full byte 822 // of bitmap. This code sets nw (below) so that heap bitmap 823 // bits are only written for the typ.ptrdata prefix; if there is 824 // more room in the allocated object, the next heap bitmap 825 // entry is a 00, indicating that there are no more pointers 826 // to scan. So only the ptrmask for the ptrdata bytes is needed. 827 // 828 // Replicated copies are not as nice: if there is an array of 829 // objects with scalar tails, all but the last tail does have to 830 // be initialized, because there is no way to say "skip forward". 831 // However, because of the possibility of a repeated type with 832 // size not a multiple of 4 pointers (one heap bitmap byte), 833 // the code already must handle the last ptrmask byte specially 834 // by treating it as containing only the bits for endnb pointers, 835 // where endnb <= 4. We represent large scalar tails that must 836 // be expanded in the replication by setting endnb larger than 4. 837 // This will have the effect of reading many bits out of b, 838 // but once the real bits are shifted out, b will supply as many 839 // zero bits as we try to read, which is exactly what we need. 840 841 p = ptrmask 842 if typ.size < dataSize { 843 // Filling in bits for an array of typ. 844 // Set up for repetition of ptrmask during main loop. 845 // Note that ptrmask describes only a prefix of 846 const maxBits = sys.PtrSize*8 - 7 847 if typ.ptrdata/sys.PtrSize <= maxBits { 848 // Entire ptrmask fits in uintptr with room for a byte fragment. 849 // Load into pbits and never read from ptrmask again. 850 // This is especially important when the ptrmask has 851 // fewer than 8 bits in it; otherwise the reload in the middle 852 // of the Phase 2 loop would itself need to loop to gather 853 // at least 8 bits. 854 855 // Accumulate ptrmask into b. 856 // ptrmask is sized to describe only typ.ptrdata, but we record 857 // it as describing typ.size bytes, since all the high bits are zero. 858 nb = typ.ptrdata / sys.PtrSize 859 for i := uintptr(0); i < nb; i += 8 { 860 b |= uintptr(*p) << i 861 p = add1(p) 862 } 863 nb = typ.size / sys.PtrSize 864 865 // Replicate ptrmask to fill entire pbits uintptr. 866 // Doubling and truncating is fewer steps than 867 // iterating by nb each time. (nb could be 1.) 868 // Since we loaded typ.ptrdata/ptrSize bits 869 // but are pretending to have typ.size/ptrSize, 870 // there might be no replication necessary/possible. 871 pbits = b 872 endnb = nb 873 if nb+nb <= maxBits { 874 for endnb <= sys.PtrSize*8 { 875 pbits |= pbits << endnb 876 endnb += endnb 877 } 878 // Truncate to a multiple of original ptrmask. 879 endnb = maxBits / nb * nb 880 pbits &= 1<<endnb - 1 881 b = pbits 882 nb = endnb 883 } 884 885 // Clear p and endp as sentinel for using pbits. 886 // Checked during Phase 2 loop. 887 p = nil 888 endp = nil 889 } else { 890 // Ptrmask is larger. Read it multiple times. 891 n := (typ.ptrdata/sys.PtrSize+7)/8 - 1 892 endp = addb(ptrmask, n) 893 endnb = typ.size/sys.PtrSize - n*8 894 } 895 } 896 if p != nil { 897 b = uintptr(*p) 898 p = add1(p) 899 nb = 8 900 } 901 902 if typ.size == dataSize { 903 // Single entry: can stop once we reach the non-pointer data. 904 nw = typ.ptrdata / sys.PtrSize 905 } else { 906 // Repeated instances of typ in an array. 907 // Have to process first N-1 entries in full, but can stop 908 // once we reach the non-pointer data in the final entry. 909 nw = ((dataSize/typ.size-1)*typ.size + typ.ptrdata) / sys.PtrSize 910 } 911 if nw == 0 { 912 // No pointers! Caller was supposed to check. 913 println("runtime: invalid type ", *typ._string) 914 throw("heapBitsSetType: called with non-pointer type") 915 return 916 } 917 if nw < 2 { 918 // Must write at least 2 words, because the "no scan" 919 // encoding doesn't take effect until the third word. 920 nw = 2 921 } 922 923 // Phase 1: Special case for leading byte (shift==0) or half-byte (shift==4). 924 // The leading byte is special because it contains the bits for words 0 and 1, 925 // which do not have the marked bits set. 926 // The leading half-byte is special because it's a half a byte and must be 927 // manipulated atomically. 928 switch { 929 default: 930 throw("heapBitsSetType: unexpected shift") 931 932 case h.shift == 0: 933 // Ptrmask and heap bitmap are aligned. 934 // Handle first byte of bitmap specially. 935 // The first byte we write out contains the first two words of the object. 936 // In those words, the mark bits are mark and checkmark, respectively, 937 // and must not be set. In all following words, we want to set the mark bit 938 // as a signal that the object continues to the next 2-bit entry in the bitmap. 939 hb = b & bitPointerAll 940 hb |= bitMarked<<(2*heapBitsShift) | bitMarked<<(3*heapBitsShift) 941 if w += 4; w >= nw { 942 goto Phase3 943 } 944 *hbitp = uint8(hb) 945 hbitp = subtract1(hbitp) 946 b >>= 4 947 nb -= 4 948 949 case sys.PtrSize == 8 && h.shift == 2: 950 // Ptrmask and heap bitmap are misaligned. 951 // The bits for the first two words are in a byte shared with another object 952 // and must be updated atomically. 953 // NOTE(rsc): The atomic here may not be necessary. 954 // We took care of 1-word and 2-word objects above, 955 // so this is at least a 6-word object, so our start bits 956 // are shared only with the type bits of another object, 957 // not with its mark bit. Since there is only one allocation 958 // from a given span at a time, we should be able to set 959 // these bits non-atomically. Not worth the risk right now. 960 hb = (b & 3) << (2 * heapBitsShift) 961 b >>= 2 962 nb -= 2 963 // Note: no bitMarker in hb because the first two words don't get markers from us. 964 if gcphase == _GCoff { 965 *hbitp |= uint8(hb) 966 } else { 967 atomic.Or8(hbitp, uint8(hb)) 968 } 969 hbitp = subtract1(hbitp) 970 if w += 2; w >= nw { 971 // We know that there is more data, because we handled 2-word objects above. 972 // This must be at least a 6-word object. If we're out of pointer words, 973 // mark no scan in next bitmap byte and finish. 974 hb = 0 975 w += 4 976 goto Phase3 977 } 978 } 979 980 // Phase 2: Full bytes in bitmap, up to but not including write to last byte (full or partial) in bitmap. 981 // The loop computes the bits for that last write but does not execute the write; 982 // it leaves the bits in hb for processing by phase 3. 983 // To avoid repeated adjustment of nb, we subtract out the 4 bits we're going to 984 // use in the first half of the loop right now, and then we only adjust nb explicitly 985 // if the 8 bits used by each iteration isn't balanced by 8 bits loaded mid-loop. 986 nb -= 4 987 for { 988 // Emit bitmap byte. 989 // b has at least nb+4 bits, with one exception: 990 // if w+4 >= nw, then b has only nw-w bits, 991 // but we'll stop at the break and then truncate 992 // appropriately in Phase 3. 993 hb = b & bitPointerAll 994 hb |= bitMarkedAll 995 if w += 4; w >= nw { 996 break 997 } 998 *hbitp = uint8(hb) 999 hbitp = subtract1(hbitp) 1000 b >>= 4 1001 1002 // Load more bits. b has nb right now. 1003 if p != endp { 1004 // Fast path: keep reading from ptrmask. 1005 // nb unmodified: we just loaded 8 bits, 1006 // and the next iteration will consume 8 bits, 1007 // leaving us with the same nb the next time we're here. 1008 if nb < 8 { 1009 b |= uintptr(*p) << nb 1010 p = add1(p) 1011 } else { 1012 // Reduce the number of bits in b. 1013 // This is important if we skipped 1014 // over a scalar tail, since nb could 1015 // be larger than the bit width of b. 1016 nb -= 8 1017 } 1018 } else if p == nil { 1019 // Almost as fast path: track bit count and refill from pbits. 1020 // For short repetitions. 1021 if nb < 8 { 1022 b |= pbits << nb 1023 nb += endnb 1024 } 1025 nb -= 8 // for next iteration 1026 } else { 1027 // Slow path: reached end of ptrmask. 1028 // Process final partial byte and rewind to start. 1029 b |= uintptr(*p) << nb 1030 nb += endnb 1031 if nb < 8 { 1032 b |= uintptr(*ptrmask) << nb 1033 p = add1(ptrmask) 1034 } else { 1035 nb -= 8 1036 p = ptrmask 1037 } 1038 } 1039 1040 // Emit bitmap byte. 1041 hb = b & bitPointerAll 1042 hb |= bitMarkedAll 1043 if w += 4; w >= nw { 1044 break 1045 } 1046 *hbitp = uint8(hb) 1047 hbitp = subtract1(hbitp) 1048 b >>= 4 1049 } 1050 1051 Phase3: 1052 // Phase 3: Write last byte or partial byte and zero the rest of the bitmap entries. 1053 if w > nw { 1054 // Counting the 4 entries in hb not yet written to memory, 1055 // there are more entries than possible pointer slots. 1056 // Discard the excess entries (can't be more than 3). 1057 mask := uintptr(1)<<(4-(w-nw)) - 1 1058 hb &= mask | mask<<4 // apply mask to both pointer bits and mark bits 1059 } 1060 1061 // Change nw from counting possibly-pointer words to total words in allocation. 1062 nw = size / sys.PtrSize 1063 1064 // Write whole bitmap bytes. 1065 // The first is hb, the rest are zero. 1066 if w <= nw { 1067 *hbitp = uint8(hb) 1068 hbitp = subtract1(hbitp) 1069 hb = 0 // for possible final half-byte below 1070 for w += 4; w <= nw; w += 4 { 1071 *hbitp = 0 1072 hbitp = subtract1(hbitp) 1073 } 1074 } 1075 1076 // Write final partial bitmap byte if any. 1077 // We know w > nw, or else we'd still be in the loop above. 1078 // It can be bigger only due to the 4 entries in hb that it counts. 1079 // If w == nw+4 then there's nothing left to do: we wrote all nw entries 1080 // and can discard the 4 sitting in hb. 1081 // But if w == nw+2, we need to write first two in hb. 1082 // The byte is shared with the next object so we may need an atomic. 1083 if w == nw+2 { 1084 if gcphase == _GCoff { 1085 *hbitp = *hbitp&^(bitPointer|bitMarked|(bitPointer|bitMarked)<<heapBitsShift) | uint8(hb) 1086 } else { 1087 atomic.And8(hbitp, ^uint8(bitPointer|bitMarked|(bitPointer|bitMarked)<<heapBitsShift)) 1088 atomic.Or8(hbitp, uint8(hb)) 1089 } 1090 } 1091 1092 Phase4: 1093 // Phase 4: all done, but perhaps double check. 1094 if doubleCheck { 1095 end := heapBitsForAddr(x + size) 1096 if typ.kind&kindGCProg == 0 && (hbitp != end.bitp || (w == nw+2) != (end.shift == 2)) { 1097 println("ended at wrong bitmap byte for", *typ._string, "x", dataSize/typ.size) 1098 print("typ.size=", typ.size, " typ.ptrdata=", typ.ptrdata, " dataSize=", dataSize, " size=", size, "\n") 1099 print("w=", w, " nw=", nw, " b=", hex(b), " nb=", nb, " hb=", hex(hb), "\n") 1100 h0 := heapBitsForAddr(x) 1101 print("initial bits h0.bitp=", h0.bitp, " h0.shift=", h0.shift, "\n") 1102 print("ended at hbitp=", hbitp, " but next starts at bitp=", end.bitp, " shift=", end.shift, "\n") 1103 throw("bad heapBitsSetType") 1104 } 1105 1106 // Double-check that bits to be written were written correctly. 1107 // Does not check that other bits were not written, unfortunately. 1108 h := heapBitsForAddr(x) 1109 nptr := typ.ptrdata / sys.PtrSize 1110 ndata := typ.size / sys.PtrSize 1111 count := dataSize / typ.size 1112 totalptr := ((count-1)*typ.size + typ.ptrdata) / sys.PtrSize 1113 for i := uintptr(0); i < size/sys.PtrSize; i++ { 1114 j := i % ndata 1115 var have, want uint8 1116 have = (*h.bitp >> h.shift) & (bitPointer | bitMarked) 1117 if i >= totalptr { 1118 want = 0 // deadmarker 1119 if typ.kind&kindGCProg != 0 && i < (totalptr+3)/4*4 { 1120 want = bitMarked 1121 } 1122 } else { 1123 if j < nptr && (*addb(ptrmask, j/8)>>(j%8))&1 != 0 { 1124 want |= bitPointer 1125 } 1126 if i >= 2 { 1127 want |= bitMarked 1128 } else { 1129 have &^= bitMarked 1130 } 1131 } 1132 if have != want { 1133 println("mismatch writing bits for", *typ._string, "x", dataSize/typ.size) 1134 print("typ.size=", typ.size, " typ.ptrdata=", typ.ptrdata, " dataSize=", dataSize, " size=", size, "\n") 1135 print("kindGCProg=", typ.kind&kindGCProg != 0, "\n") 1136 print("w=", w, " nw=", nw, " b=", hex(b), " nb=", nb, " hb=", hex(hb), "\n") 1137 h0 := heapBitsForAddr(x) 1138 print("initial bits h0.bitp=", h0.bitp, " h0.shift=", h0.shift, "\n") 1139 print("current bits h.bitp=", h.bitp, " h.shift=", h.shift, " *h.bitp=", hex(*h.bitp), "\n") 1140 print("ptrmask=", ptrmask, " p=", p, " endp=", endp, " endnb=", endnb, " pbits=", hex(pbits), " b=", hex(b), " nb=", nb, "\n") 1141 println("at word", i, "offset", i*sys.PtrSize, "have", have, "want", want) 1142 if typ.kind&kindGCProg != 0 { 1143 println("GC program:") 1144 dumpGCProg(addb(typ.gcdata, 4)) 1145 } 1146 throw("bad heapBitsSetType") 1147 } 1148 h = h.next() 1149 } 1150 if ptrmask == debugPtrmask.data { 1151 unlock(&debugPtrmask.lock) 1152 } 1153 } 1154 } 1155 1156 var debugPtrmask struct { 1157 lock mutex 1158 data *byte 1159 } 1160 1161 // heapBitsSetTypeGCProg implements heapBitsSetType using a GC program. 1162 // progSize is the size of the memory described by the program. 1163 // elemSize is the size of the element that the GC program describes (a prefix of). 1164 // dataSize is the total size of the intended data, a multiple of elemSize. 1165 // allocSize is the total size of the allocated memory. 1166 // 1167 // GC programs are only used for large allocations. 1168 // heapBitsSetType requires that allocSize is a multiple of 4 words, 1169 // so that the relevant bitmap bytes are not shared with surrounding 1170 // objects and need not be accessed with atomic instructions. 1171 func heapBitsSetTypeGCProg(h heapBits, progSize, elemSize, dataSize, allocSize uintptr, prog *byte) { 1172 if sys.PtrSize == 8 && allocSize%(4*sys.PtrSize) != 0 { 1173 // Alignment will be wrong. 1174 throw("heapBitsSetTypeGCProg: small allocation") 1175 } 1176 var totalBits uintptr 1177 if elemSize == dataSize { 1178 totalBits = runGCProg(prog, nil, h.bitp, 2) 1179 if totalBits*sys.PtrSize != progSize { 1180 println("runtime: heapBitsSetTypeGCProg: total bits", totalBits, "but progSize", progSize) 1181 throw("heapBitsSetTypeGCProg: unexpected bit count") 1182 } 1183 } else { 1184 count := dataSize / elemSize 1185 1186 // Piece together program trailer to run after prog that does: 1187 // literal(0) 1188 // repeat(1, elemSize-progSize-1) // zeros to fill element size 1189 // repeat(elemSize, count-1) // repeat that element for count 1190 // This zero-pads the data remaining in the first element and then 1191 // repeats that first element to fill the array. 1192 var trailer [40]byte // 3 varints (max 10 each) + some bytes 1193 i := 0 1194 if n := elemSize/sys.PtrSize - progSize/sys.PtrSize; n > 0 { 1195 // literal(0) 1196 trailer[i] = 0x01 1197 i++ 1198 trailer[i] = 0 1199 i++ 1200 if n > 1 { 1201 // repeat(1, n-1) 1202 trailer[i] = 0x81 1203 i++ 1204 n-- 1205 for ; n >= 0x80; n >>= 7 { 1206 trailer[i] = byte(n | 0x80) 1207 i++ 1208 } 1209 trailer[i] = byte(n) 1210 i++ 1211 } 1212 } 1213 // repeat(elemSize/ptrSize, count-1) 1214 trailer[i] = 0x80 1215 i++ 1216 n := elemSize / sys.PtrSize 1217 for ; n >= 0x80; n >>= 7 { 1218 trailer[i] = byte(n | 0x80) 1219 i++ 1220 } 1221 trailer[i] = byte(n) 1222 i++ 1223 n = count - 1 1224 for ; n >= 0x80; n >>= 7 { 1225 trailer[i] = byte(n | 0x80) 1226 i++ 1227 } 1228 trailer[i] = byte(n) 1229 i++ 1230 trailer[i] = 0 1231 i++ 1232 1233 runGCProg(prog, &trailer[0], h.bitp, 2) 1234 1235 // Even though we filled in the full array just now, 1236 // record that we only filled in up to the ptrdata of the 1237 // last element. This will cause the code below to 1238 // memclr the dead section of the final array element, 1239 // so that scanobject can stop early in the final element. 1240 totalBits = (elemSize*(count-1) + progSize) / sys.PtrSize 1241 } 1242 endProg := unsafe.Pointer(subtractb(h.bitp, (totalBits+3)/4)) 1243 endAlloc := unsafe.Pointer(subtractb(h.bitp, allocSize/heapBitmapScale)) 1244 memclr(add(endAlloc, 1), uintptr(endProg)-uintptr(endAlloc)) 1245 } 1246 1247 // progToPointerMask returns the 1-bit pointer mask output by the GC program prog. 1248 // size the size of the region described by prog, in bytes. 1249 // The resulting bitvector will have no more than size/ptrSize bits. 1250 func progToPointerMask(prog *byte, size uintptr) bitvector { 1251 n := (size/sys.PtrSize + 7) / 8 1252 x := (*[1 << 30]byte)(persistentalloc(n+1, 1, &memstats.buckhash_sys))[:n+1] 1253 x[len(x)-1] = 0xa1 // overflow check sentinel 1254 n = runGCProg(prog, nil, &x[0], 1) 1255 if x[len(x)-1] != 0xa1 { 1256 throw("progToPointerMask: overflow") 1257 } 1258 return bitvector{int32(n), &x[0]} 1259 } 1260 1261 // Packed GC pointer bitmaps, aka GC programs. 1262 // 1263 // For large types containing arrays, the type information has a 1264 // natural repetition that can be encoded to save space in the 1265 // binary and in the memory representation of the type information. 1266 // 1267 // The encoding is a simple Lempel-Ziv style bytecode machine 1268 // with the following instructions: 1269 // 1270 // 00000000: stop 1271 // 0nnnnnnn: emit n bits copied from the next (n+7)/8 bytes 1272 // 10000000 n c: repeat the previous n bits c times; n, c are varints 1273 // 1nnnnnnn c: repeat the previous n bits c times; c is a varint 1274 1275 // runGCProg executes the GC program prog, and then trailer if non-nil, 1276 // writing to dst with entries of the given size. 1277 // If size == 1, dst is a 1-bit pointer mask laid out moving forward from dst. 1278 // If size == 2, dst is the 2-bit heap bitmap, and writes move backward 1279 // starting at dst (because the heap bitmap does). In this case, the caller guarantees 1280 // that only whole bytes in dst need to be written. 1281 // 1282 // runGCProg returns the number of 1- or 2-bit entries written to memory. 1283 func runGCProg(prog, trailer, dst *byte, size int) uintptr { 1284 dstStart := dst 1285 1286 // Bits waiting to be written to memory. 1287 var bits uintptr 1288 var nbits uintptr 1289 1290 p := prog 1291 Run: 1292 for { 1293 // Flush accumulated full bytes. 1294 // The rest of the loop assumes that nbits <= 7. 1295 for ; nbits >= 8; nbits -= 8 { 1296 if size == 1 { 1297 *dst = uint8(bits) 1298 dst = add1(dst) 1299 bits >>= 8 1300 } else { 1301 v := bits&bitPointerAll | bitMarkedAll 1302 *dst = uint8(v) 1303 dst = subtract1(dst) 1304 bits >>= 4 1305 v = bits&bitPointerAll | bitMarkedAll 1306 *dst = uint8(v) 1307 dst = subtract1(dst) 1308 bits >>= 4 1309 } 1310 } 1311 1312 // Process one instruction. 1313 inst := uintptr(*p) 1314 p = add1(p) 1315 n := inst & 0x7F 1316 if inst&0x80 == 0 { 1317 // Literal bits; n == 0 means end of program. 1318 if n == 0 { 1319 // Program is over; continue in trailer if present. 1320 if trailer != nil { 1321 //println("trailer") 1322 p = trailer 1323 trailer = nil 1324 continue 1325 } 1326 //println("done") 1327 break Run 1328 } 1329 //println("lit", n, dst) 1330 nbyte := n / 8 1331 for i := uintptr(0); i < nbyte; i++ { 1332 bits |= uintptr(*p) << nbits 1333 p = add1(p) 1334 if size == 1 { 1335 *dst = uint8(bits) 1336 dst = add1(dst) 1337 bits >>= 8 1338 } else { 1339 v := bits&0xf | bitMarkedAll 1340 *dst = uint8(v) 1341 dst = subtract1(dst) 1342 bits >>= 4 1343 v = bits&0xf | bitMarkedAll 1344 *dst = uint8(v) 1345 dst = subtract1(dst) 1346 bits >>= 4 1347 } 1348 } 1349 if n %= 8; n > 0 { 1350 bits |= uintptr(*p) << nbits 1351 p = add1(p) 1352 nbits += n 1353 } 1354 continue Run 1355 } 1356 1357 // Repeat. If n == 0, it is encoded in a varint in the next bytes. 1358 if n == 0 { 1359 for off := uint(0); ; off += 7 { 1360 x := uintptr(*p) 1361 p = add1(p) 1362 n |= (x & 0x7F) << off 1363 if x&0x80 == 0 { 1364 break 1365 } 1366 } 1367 } 1368 1369 // Count is encoded in a varint in the next bytes. 1370 c := uintptr(0) 1371 for off := uint(0); ; off += 7 { 1372 x := uintptr(*p) 1373 p = add1(p) 1374 c |= (x & 0x7F) << off 1375 if x&0x80 == 0 { 1376 break 1377 } 1378 } 1379 c *= n // now total number of bits to copy 1380 1381 // If the number of bits being repeated is small, load them 1382 // into a register and use that register for the entire loop 1383 // instead of repeatedly reading from memory. 1384 // Handling fewer than 8 bits here makes the general loop simpler. 1385 // The cutoff is ptrSize*8 - 7 to guarantee that when we add 1386 // the pattern to a bit buffer holding at most 7 bits (a partial byte) 1387 // it will not overflow. 1388 src := dst 1389 const maxBits = sys.PtrSize*8 - 7 1390 if n <= maxBits { 1391 // Start with bits in output buffer. 1392 pattern := bits 1393 npattern := nbits 1394 1395 // If we need more bits, fetch them from memory. 1396 if size == 1 { 1397 src = subtract1(src) 1398 for npattern < n { 1399 pattern <<= 8 1400 pattern |= uintptr(*src) 1401 src = subtract1(src) 1402 npattern += 8 1403 } 1404 } else { 1405 src = add1(src) 1406 for npattern < n { 1407 pattern <<= 4 1408 pattern |= uintptr(*src) & 0xf 1409 src = add1(src) 1410 npattern += 4 1411 } 1412 } 1413 1414 // We started with the whole bit output buffer, 1415 // and then we loaded bits from whole bytes. 1416 // Either way, we might now have too many instead of too few. 1417 // Discard the extra. 1418 if npattern > n { 1419 pattern >>= npattern - n 1420 npattern = n 1421 } 1422 1423 // Replicate pattern to at most maxBits. 1424 if npattern == 1 { 1425 // One bit being repeated. 1426 // If the bit is 1, make the pattern all 1s. 1427 // If the bit is 0, the pattern is already all 0s, 1428 // but we can claim that the number of bits 1429 // in the word is equal to the number we need (c), 1430 // because right shift of bits will zero fill. 1431 if pattern == 1 { 1432 pattern = 1<<maxBits - 1 1433 npattern = maxBits 1434 } else { 1435 npattern = c 1436 } 1437 } else { 1438 b := pattern 1439 nb := npattern 1440 if nb+nb <= maxBits { 1441 // Double pattern until the whole uintptr is filled. 1442 for nb <= sys.PtrSize*8 { 1443 b |= b << nb 1444 nb += nb 1445 } 1446 // Trim away incomplete copy of original pattern in high bits. 1447 // TODO(rsc): Replace with table lookup or loop on systems without divide? 1448 nb = maxBits / npattern * npattern 1449 b &= 1<<nb - 1 1450 pattern = b 1451 npattern = nb 1452 } 1453 } 1454 1455 // Add pattern to bit buffer and flush bit buffer, c/npattern times. 1456 // Since pattern contains >8 bits, there will be full bytes to flush 1457 // on each iteration. 1458 for ; c >= npattern; c -= npattern { 1459 bits |= pattern << nbits 1460 nbits += npattern 1461 if size == 1 { 1462 for nbits >= 8 { 1463 *dst = uint8(bits) 1464 dst = add1(dst) 1465 bits >>= 8 1466 nbits -= 8 1467 } 1468 } else { 1469 for nbits >= 4 { 1470 *dst = uint8(bits&0xf | bitMarkedAll) 1471 dst = subtract1(dst) 1472 bits >>= 4 1473 nbits -= 4 1474 } 1475 } 1476 } 1477 1478 // Add final fragment to bit buffer. 1479 if c > 0 { 1480 pattern &= 1<<c - 1 1481 bits |= pattern << nbits 1482 nbits += c 1483 } 1484 continue Run 1485 } 1486 1487 // Repeat; n too large to fit in a register. 1488 // Since nbits <= 7, we know the first few bytes of repeated data 1489 // are already written to memory. 1490 off := n - nbits // n > nbits because n > maxBits and nbits <= 7 1491 if size == 1 { 1492 // Leading src fragment. 1493 src = subtractb(src, (off+7)/8) 1494 if frag := off & 7; frag != 0 { 1495 bits |= uintptr(*src) >> (8 - frag) << nbits 1496 src = add1(src) 1497 nbits += frag 1498 c -= frag 1499 } 1500 // Main loop: load one byte, write another. 1501 // The bits are rotating through the bit buffer. 1502 for i := c / 8; i > 0; i-- { 1503 bits |= uintptr(*src) << nbits 1504 src = add1(src) 1505 *dst = uint8(bits) 1506 dst = add1(dst) 1507 bits >>= 8 1508 } 1509 // Final src fragment. 1510 if c %= 8; c > 0 { 1511 bits |= (uintptr(*src) & (1<<c - 1)) << nbits 1512 nbits += c 1513 } 1514 } else { 1515 // Leading src fragment. 1516 src = addb(src, (off+3)/4) 1517 if frag := off & 3; frag != 0 { 1518 bits |= (uintptr(*src) & 0xf) >> (4 - frag) << nbits 1519 src = subtract1(src) 1520 nbits += frag 1521 c -= frag 1522 } 1523 // Main loop: load one byte, write another. 1524 // The bits are rotating through the bit buffer. 1525 for i := c / 4; i > 0; i-- { 1526 bits |= (uintptr(*src) & 0xf) << nbits 1527 src = subtract1(src) 1528 *dst = uint8(bits&0xf | bitMarkedAll) 1529 dst = subtract1(dst) 1530 bits >>= 4 1531 } 1532 // Final src fragment. 1533 if c %= 4; c > 0 { 1534 bits |= (uintptr(*src) & (1<<c - 1)) << nbits 1535 nbits += c 1536 } 1537 } 1538 } 1539 1540 // Write any final bits out, using full-byte writes, even for the final byte. 1541 var totalBits uintptr 1542 if size == 1 { 1543 totalBits = (uintptr(unsafe.Pointer(dst))-uintptr(unsafe.Pointer(dstStart)))*8 + nbits 1544 nbits += -nbits & 7 1545 for ; nbits > 0; nbits -= 8 { 1546 *dst = uint8(bits) 1547 dst = add1(dst) 1548 bits >>= 8 1549 } 1550 } else { 1551 totalBits = (uintptr(unsafe.Pointer(dstStart))-uintptr(unsafe.Pointer(dst)))*4 + nbits 1552 nbits += -nbits & 3 1553 for ; nbits > 0; nbits -= 4 { 1554 v := bits&0xf | bitMarkedAll 1555 *dst = uint8(v) 1556 dst = subtract1(dst) 1557 bits >>= 4 1558 } 1559 // Clear the mark bits in the first two entries. 1560 // They are the actual mark and checkmark bits, 1561 // not non-dead markers. It simplified the code 1562 // above to set the marker in every bit written and 1563 // then clear these two as a special case at the end. 1564 *dstStart &^= bitMarked | bitMarked<<heapBitsShift 1565 } 1566 return totalBits 1567 } 1568 1569 func dumpGCProg(p *byte) { 1570 nptr := 0 1571 for { 1572 x := *p 1573 p = add1(p) 1574 if x == 0 { 1575 print("\t", nptr, " end\n") 1576 break 1577 } 1578 if x&0x80 == 0 { 1579 print("\t", nptr, " lit ", x, ":") 1580 n := int(x+7) / 8 1581 for i := 0; i < n; i++ { 1582 print(" ", hex(*p)) 1583 p = add1(p) 1584 } 1585 print("\n") 1586 nptr += int(x) 1587 } else { 1588 nbit := int(x &^ 0x80) 1589 if nbit == 0 { 1590 for nb := uint(0); ; nb += 7 { 1591 x := *p 1592 p = add1(p) 1593 nbit |= int(x&0x7f) << nb 1594 if x&0x80 == 0 { 1595 break 1596 } 1597 } 1598 } 1599 count := 0 1600 for nb := uint(0); ; nb += 7 { 1601 x := *p 1602 p = add1(p) 1603 count |= int(x&0x7f) << nb 1604 if x&0x80 == 0 { 1605 break 1606 } 1607 } 1608 print("\t", nptr, " repeat ", nbit, " × ", count, "\n") 1609 nptr += nbit * count 1610 } 1611 } 1612 } 1613 1614 // Testing. 1615 1616 func getgcmaskcb(frame *stkframe, ctxt unsafe.Pointer) bool { 1617 target := (*stkframe)(ctxt) 1618 if frame.sp <= target.sp && target.sp < frame.varp { 1619 *target = *frame 1620 return false 1621 } 1622 return true 1623 } 1624 1625 // gcbits returns the GC type info for x, for testing. 1626 // The result is the bitmap entries (0 or 1), one entry per byte. 1627 //go:linkname reflect_gcbits reflect.gcbits 1628 func reflect_gcbits(x interface{}) []byte { 1629 ret := getgcmask(x) 1630 typ := (*ptrtype)(unsafe.Pointer(efaceOf(&x)._type)).elem 1631 nptr := typ.ptrdata / sys.PtrSize 1632 for uintptr(len(ret)) > nptr && ret[len(ret)-1] == 0 { 1633 ret = ret[:len(ret)-1] 1634 } 1635 return ret 1636 } 1637 1638 // Returns GC type info for object p for testing. 1639 func getgcmask(ep interface{}) (mask []byte) { 1640 e := *efaceOf(&ep) 1641 p := e.data 1642 t := e._type 1643 // data or bss 1644 for datap := &firstmoduledata; datap != nil; datap = datap.next { 1645 // data 1646 if datap.data <= uintptr(p) && uintptr(p) < datap.edata { 1647 bitmap := datap.gcdatamask.bytedata 1648 n := (*ptrtype)(unsafe.Pointer(t)).elem.size 1649 mask = make([]byte, n/sys.PtrSize) 1650 for i := uintptr(0); i < n; i += sys.PtrSize { 1651 off := (uintptr(p) + i - datap.data) / sys.PtrSize 1652 mask[i/sys.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1 1653 } 1654 return 1655 } 1656 1657 // bss 1658 if datap.bss <= uintptr(p) && uintptr(p) < datap.ebss { 1659 bitmap := datap.gcbssmask.bytedata 1660 n := (*ptrtype)(unsafe.Pointer(t)).elem.size 1661 mask = make([]byte, n/sys.PtrSize) 1662 for i := uintptr(0); i < n; i += sys.PtrSize { 1663 off := (uintptr(p) + i - datap.bss) / sys.PtrSize 1664 mask[i/sys.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1 1665 } 1666 return 1667 } 1668 } 1669 1670 // heap 1671 var n uintptr 1672 var base uintptr 1673 if mlookup(uintptr(p), &base, &n, nil) != 0 { 1674 mask = make([]byte, n/sys.PtrSize) 1675 for i := uintptr(0); i < n; i += sys.PtrSize { 1676 hbits := heapBitsForAddr(base + i) 1677 if hbits.isPointer() { 1678 mask[i/sys.PtrSize] = 1 1679 } 1680 if i >= 2*sys.PtrSize && !hbits.isMarked() { 1681 mask = mask[:i/sys.PtrSize] 1682 break 1683 } 1684 } 1685 return 1686 } 1687 1688 // stack 1689 if _g_ := getg(); _g_.m.curg.stack.lo <= uintptr(p) && uintptr(p) < _g_.m.curg.stack.hi { 1690 var frame stkframe 1691 frame.sp = uintptr(p) 1692 _g_ := getg() 1693 gentraceback(_g_.m.curg.sched.pc, _g_.m.curg.sched.sp, 0, _g_.m.curg, 0, nil, 1000, getgcmaskcb, noescape(unsafe.Pointer(&frame)), 0) 1694 if frame.fn != nil { 1695 f := frame.fn 1696 targetpc := frame.continpc 1697 if targetpc == 0 { 1698 return 1699 } 1700 if targetpc != f.entry { 1701 targetpc-- 1702 } 1703 pcdata := pcdatavalue(f, _PCDATA_StackMapIndex, targetpc, nil) 1704 if pcdata == -1 { 1705 return 1706 } 1707 stkmap := (*stackmap)(funcdata(f, _FUNCDATA_LocalsPointerMaps)) 1708 if stkmap == nil || stkmap.n <= 0 { 1709 return 1710 } 1711 bv := stackmapdata(stkmap, pcdata) 1712 size := uintptr(bv.n) * sys.PtrSize 1713 n := (*ptrtype)(unsafe.Pointer(t)).elem.size 1714 mask = make([]byte, n/sys.PtrSize) 1715 for i := uintptr(0); i < n; i += sys.PtrSize { 1716 bitmap := bv.bytedata 1717 off := (uintptr(p) + i - frame.varp + size) / sys.PtrSize 1718 mask[i/sys.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1 1719 } 1720 } 1721 return 1722 } 1723 1724 // otherwise, not something the GC knows about. 1725 // possibly read-only data, like malloc(0). 1726 // must not have pointers 1727 return 1728 }