...

Source file src/runtime/mbitmap.go

Documentation: runtime

     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
    10  // described by bitmaps with 1 bit per pointer-sized word. A "1" bit
    11  // means the word is a live pointer to be visited by the GC (referred to
    12  // as "pointer"). A "0" bit means the word should be ignored by GC
    13  // (referred to as "scalar", though it could be a dead pointer value).
    14  //
    15  // Heap bitmap
    16  //
    17  // The heap bitmap comprises 2 bits for each pointer-sized word in the heap,
    18  // stored in the heapArena metadata backing each heap arena.
    19  // That is, if ha is the heapArena for the arena starting a start,
    20  // then ha.bitmap[0] holds the 2-bit entries for the four words start
    21  // through start+3*ptrSize, ha.bitmap[1] 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 is a pointer/scalar bit, just
    25  // like in the stack/data bitmaps described above. The upper bit
    26  // indicates scan/dead: a "1" value ("scan") indicates that there may
    27  // be pointers in later words of the allocation, and a "0" value
    28  // ("dead") indicates there are no more pointers in the allocation. If
    29  // the upper bit is 0, the lower bit must also be 0, and this
    30  // indicates scanning can ignore the rest of the allocation.
    31  //
    32  // The 2-bit entries are split when written into the byte, so that the top half
    33  // of the byte contains 4 high (scan) bits and the bottom half contains 4 low
    34  // (pointer) bits. This form allows a copy from the 1-bit to the 4-bit form to
    35  // keep the pointer bits contiguous, instead of having to space them out.
    36  //
    37  // The code makes use of the fact that the zero value for a heap
    38  // bitmap means scalar/dead. This property must be preserved when
    39  // modifying the encoding.
    40  //
    41  // The bitmap for noscan spans is not maintained. Code must ensure
    42  // that an object is scannable before consulting its bitmap by
    43  // checking either the noscan bit in the span or by consulting its
    44  // type's information.
    45  
    46  package runtime
    47  
    48  import (
    49  	"internal/goarch"
    50  	"runtime/internal/atomic"
    51  	"runtime/internal/sys"
    52  	"unsafe"
    53  )
    54  
    55  const (
    56  	bitPointer = 1 << 0
    57  	bitScan    = 1 << 4
    58  
    59  	heapBitsShift      = 1     // shift offset between successive bitPointer or bitScan entries
    60  	wordsPerBitmapByte = 8 / 2 // heap words described by one bitmap byte
    61  
    62  	// all scan/pointer bits in a byte
    63  	bitScanAll    = bitScan | bitScan<<heapBitsShift | bitScan<<(2*heapBitsShift) | bitScan<<(3*heapBitsShift)
    64  	bitPointerAll = bitPointer | bitPointer<<heapBitsShift | bitPointer<<(2*heapBitsShift) | bitPointer<<(3*heapBitsShift)
    65  )
    66  
    67  // addb returns the byte pointer p+n.
    68  //
    69  //go:nowritebarrier
    70  //go:nosplit
    71  func addb(p *byte, n uintptr) *byte {
    72  	// Note: wrote out full expression instead of calling add(p, n)
    73  	// to reduce the number of temporaries generated by the
    74  	// compiler for this trivial expression during inlining.
    75  	return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n))
    76  }
    77  
    78  // subtractb returns the byte pointer p-n.
    79  //
    80  //go:nowritebarrier
    81  //go:nosplit
    82  func subtractb(p *byte, n uintptr) *byte {
    83  	// Note: wrote out full expression instead of calling add(p, -n)
    84  	// to reduce the number of temporaries generated by the
    85  	// compiler for this trivial expression during inlining.
    86  	return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - n))
    87  }
    88  
    89  // add1 returns the byte pointer p+1.
    90  //
    91  //go:nowritebarrier
    92  //go:nosplit
    93  func add1(p *byte) *byte {
    94  	// Note: wrote out full expression instead of calling addb(p, 1)
    95  	// to reduce the number of temporaries generated by the
    96  	// compiler for this trivial expression during inlining.
    97  	return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1))
    98  }
    99  
   100  // subtract1 returns the byte pointer p-1.
   101  //
   102  // nosplit because it is used during write barriers and must not be preempted.
   103  //
   104  //go:nowritebarrier
   105  //go:nosplit
   106  func subtract1(p *byte) *byte {
   107  	// Note: wrote out full expression instead of calling subtractb(p, 1)
   108  	// to reduce the number of temporaries generated by the
   109  	// compiler for this trivial expression during inlining.
   110  	return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - 1))
   111  }
   112  
   113  // heapBits provides access to the bitmap bits for a single heap word.
   114  // The methods on heapBits take value receivers so that the compiler
   115  // can more easily inline calls to those methods and registerize the
   116  // struct fields independently.
   117  type heapBits struct {
   118  	bitp  *uint8
   119  	shift uint32
   120  	arena uint32 // Index of heap arena containing bitp
   121  	last  *uint8 // Last byte arena's bitmap
   122  }
   123  
   124  // Make the compiler check that heapBits.arena is large enough to hold
   125  // the maximum arena frame number.
   126  var _ = heapBits{arena: (1<<heapAddrBits)/heapArenaBytes - 1}
   127  
   128  // markBits provides access to the mark bit for an object in the heap.
   129  // bytep points to the byte holding the mark bit.
   130  // mask is a byte with a single bit set that can be &ed with *bytep
   131  // to see if the bit has been set.
   132  // *m.byte&m.mask != 0 indicates the mark bit is set.
   133  // index can be used along with span information to generate
   134  // the address of the object in the heap.
   135  // We maintain one set of mark bits for allocation and one for
   136  // marking purposes.
   137  type markBits struct {
   138  	bytep *uint8
   139  	mask  uint8
   140  	index uintptr
   141  }
   142  
   143  //go:nosplit
   144  func (s *mspan) allocBitsForIndex(allocBitIndex uintptr) markBits {
   145  	bytep, mask := s.allocBits.bitp(allocBitIndex)
   146  	return markBits{bytep, mask, allocBitIndex}
   147  }
   148  
   149  // refillAllocCache takes 8 bytes s.allocBits starting at whichByte
   150  // and negates them so that ctz (count trailing zeros) instructions
   151  // can be used. It then places these 8 bytes into the cached 64 bit
   152  // s.allocCache.
   153  func (s *mspan) refillAllocCache(whichByte uintptr) {
   154  	bytes := (*[8]uint8)(unsafe.Pointer(s.allocBits.bytep(whichByte)))
   155  	aCache := uint64(0)
   156  	aCache |= uint64(bytes[0])
   157  	aCache |= uint64(bytes[1]) << (1 * 8)
   158  	aCache |= uint64(bytes[2]) << (2 * 8)
   159  	aCache |= uint64(bytes[3]) << (3 * 8)
   160  	aCache |= uint64(bytes[4]) << (4 * 8)
   161  	aCache |= uint64(bytes[5]) << (5 * 8)
   162  	aCache |= uint64(bytes[6]) << (6 * 8)
   163  	aCache |= uint64(bytes[7]) << (7 * 8)
   164  	s.allocCache = ^aCache
   165  }
   166  
   167  // nextFreeIndex returns the index of the next free object in s at
   168  // or after s.freeindex.
   169  // There are hardware instructions that can be used to make this
   170  // faster if profiling warrants it.
   171  func (s *mspan) nextFreeIndex() uintptr {
   172  	sfreeindex := s.freeindex
   173  	snelems := s.nelems
   174  	if sfreeindex == snelems {
   175  		return sfreeindex
   176  	}
   177  	if sfreeindex > snelems {
   178  		throw("s.freeindex > s.nelems")
   179  	}
   180  
   181  	aCache := s.allocCache
   182  
   183  	bitIndex := sys.Ctz64(aCache)
   184  	for bitIndex == 64 {
   185  		// Move index to start of next cached bits.
   186  		sfreeindex = (sfreeindex + 64) &^ (64 - 1)
   187  		if sfreeindex >= snelems {
   188  			s.freeindex = snelems
   189  			return snelems
   190  		}
   191  		whichByte := sfreeindex / 8
   192  		// Refill s.allocCache with the next 64 alloc bits.
   193  		s.refillAllocCache(whichByte)
   194  		aCache = s.allocCache
   195  		bitIndex = sys.Ctz64(aCache)
   196  		// nothing available in cached bits
   197  		// grab the next 8 bytes and try again.
   198  	}
   199  	result := sfreeindex + uintptr(bitIndex)
   200  	if result >= snelems {
   201  		s.freeindex = snelems
   202  		return snelems
   203  	}
   204  
   205  	s.allocCache >>= uint(bitIndex + 1)
   206  	sfreeindex = result + 1
   207  
   208  	if sfreeindex%64 == 0 && sfreeindex != snelems {
   209  		// We just incremented s.freeindex so it isn't 0.
   210  		// As each 1 in s.allocCache was encountered and used for allocation
   211  		// it was shifted away. At this point s.allocCache contains all 0s.
   212  		// Refill s.allocCache so that it corresponds
   213  		// to the bits at s.allocBits starting at s.freeindex.
   214  		whichByte := sfreeindex / 8
   215  		s.refillAllocCache(whichByte)
   216  	}
   217  	s.freeindex = sfreeindex
   218  	return result
   219  }
   220  
   221  // isFree reports whether the index'th object in s is unallocated.
   222  //
   223  // The caller must ensure s.state is mSpanInUse, and there must have
   224  // been no preemption points since ensuring this (which could allow a
   225  // GC transition, which would allow the state to change).
   226  func (s *mspan) isFree(index uintptr) bool {
   227  	if index < s.freeIndexForScan {
   228  		return false
   229  	}
   230  	bytep, mask := s.allocBits.bitp(index)
   231  	return *bytep&mask == 0
   232  }
   233  
   234  // divideByElemSize returns n/s.elemsize.
   235  // n must be within [0, s.npages*_PageSize),
   236  // or may be exactly s.npages*_PageSize
   237  // if s.elemsize is from sizeclasses.go.
   238  func (s *mspan) divideByElemSize(n uintptr) uintptr {
   239  	const doubleCheck = false
   240  
   241  	// See explanation in mksizeclasses.go's computeDivMagic.
   242  	q := uintptr((uint64(n) * uint64(s.divMul)) >> 32)
   243  
   244  	if doubleCheck && q != n/s.elemsize {
   245  		println(n, "/", s.elemsize, "should be", n/s.elemsize, "but got", q)
   246  		throw("bad magic division")
   247  	}
   248  	return q
   249  }
   250  
   251  func (s *mspan) objIndex(p uintptr) uintptr {
   252  	return s.divideByElemSize(p - s.base())
   253  }
   254  
   255  func markBitsForAddr(p uintptr) markBits {
   256  	s := spanOf(p)
   257  	objIndex := s.objIndex(p)
   258  	return s.markBitsForIndex(objIndex)
   259  }
   260  
   261  func (s *mspan) markBitsForIndex(objIndex uintptr) markBits {
   262  	bytep, mask := s.gcmarkBits.bitp(objIndex)
   263  	return markBits{bytep, mask, objIndex}
   264  }
   265  
   266  func (s *mspan) markBitsForBase() markBits {
   267  	return markBits{(*uint8)(s.gcmarkBits), uint8(1), 0}
   268  }
   269  
   270  // isMarked reports whether mark bit m is set.
   271  func (m markBits) isMarked() bool {
   272  	return *m.bytep&m.mask != 0
   273  }
   274  
   275  // setMarked sets the marked bit in the markbits, atomically.
   276  func (m markBits) setMarked() {
   277  	// Might be racing with other updates, so use atomic update always.
   278  	// We used to be clever here and use a non-atomic update in certain
   279  	// cases, but it's not worth the risk.
   280  	atomic.Or8(m.bytep, m.mask)
   281  }
   282  
   283  // setMarkedNonAtomic sets the marked bit in the markbits, non-atomically.
   284  func (m markBits) setMarkedNonAtomic() {
   285  	*m.bytep |= m.mask
   286  }
   287  
   288  // clearMarked clears the marked bit in the markbits, atomically.
   289  func (m markBits) clearMarked() {
   290  	// Might be racing with other updates, so use atomic update always.
   291  	// We used to be clever here and use a non-atomic update in certain
   292  	// cases, but it's not worth the risk.
   293  	atomic.And8(m.bytep, ^m.mask)
   294  }
   295  
   296  // markBitsForSpan returns the markBits for the span base address base.
   297  func markBitsForSpan(base uintptr) (mbits markBits) {
   298  	mbits = markBitsForAddr(base)
   299  	if mbits.mask != 1 {
   300  		throw("markBitsForSpan: unaligned start")
   301  	}
   302  	return mbits
   303  }
   304  
   305  // advance advances the markBits to the next object in the span.
   306  func (m *markBits) advance() {
   307  	if m.mask == 1<<7 {
   308  		m.bytep = (*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(m.bytep)) + 1))
   309  		m.mask = 1
   310  	} else {
   311  		m.mask = m.mask << 1
   312  	}
   313  	m.index++
   314  }
   315  
   316  // heapBitsForAddr returns the heapBits for the address addr.
   317  // The caller must ensure addr is in an allocated span.
   318  // In particular, be careful not to point past the end of an object.
   319  //
   320  // nosplit because it is used during write barriers and must not be preempted.
   321  //
   322  //go:nosplit
   323  func heapBitsForAddr(addr uintptr) (h heapBits) {
   324  	// 2 bits per word, 4 pairs per byte, and a mask is hard coded.
   325  	arena := arenaIndex(addr)
   326  	ha := mheap_.arenas[arena.l1()][arena.l2()]
   327  	// The compiler uses a load for nil checking ha, but in this
   328  	// case we'll almost never hit that cache line again, so it
   329  	// makes more sense to do a value check.
   330  	if ha == nil {
   331  		// addr is not in the heap. Return nil heapBits, which
   332  		// we expect to crash in the caller.
   333  		return
   334  	}
   335  	h.bitp = &ha.bitmap[(addr/(goarch.PtrSize*4))%heapArenaBitmapBytes]
   336  	h.shift = uint32((addr / goarch.PtrSize) & 3)
   337  	h.arena = uint32(arena)
   338  	h.last = &ha.bitmap[len(ha.bitmap)-1]
   339  	return
   340  }
   341  
   342  // clobberdeadPtr is a special value that is used by the compiler to
   343  // clobber dead stack slots, when -clobberdead flag is set.
   344  const clobberdeadPtr = uintptr(0xdeaddead | 0xdeaddead<<((^uintptr(0)>>63)*32))
   345  
   346  // badPointer throws bad pointer in heap panic.
   347  func badPointer(s *mspan, p, refBase, refOff uintptr) {
   348  	// Typically this indicates an incorrect use
   349  	// of unsafe or cgo to store a bad pointer in
   350  	// the Go heap. It may also indicate a runtime
   351  	// bug.
   352  	//
   353  	// TODO(austin): We could be more aggressive
   354  	// and detect pointers to unallocated objects
   355  	// in allocated spans.
   356  	printlock()
   357  	print("runtime: pointer ", hex(p))
   358  	if s != nil {
   359  		state := s.state.get()
   360  		if state != mSpanInUse {
   361  			print(" to unallocated span")
   362  		} else {
   363  			print(" to unused region of span")
   364  		}
   365  		print(" span.base()=", hex(s.base()), " span.limit=", hex(s.limit), " span.state=", state)
   366  	}
   367  	print("\n")
   368  	if refBase != 0 {
   369  		print("runtime: found in object at *(", hex(refBase), "+", hex(refOff), ")\n")
   370  		gcDumpObject("object", refBase, refOff)
   371  	}
   372  	getg().m.traceback = 2
   373  	throw("found bad pointer in Go heap (incorrect use of unsafe or cgo?)")
   374  }
   375  
   376  // findObject returns the base address for the heap object containing
   377  // the address p, the object's span, and the index of the object in s.
   378  // If p does not point into a heap object, it returns base == 0.
   379  //
   380  // If p points is an invalid heap pointer and debug.invalidptr != 0,
   381  // findObject panics.
   382  //
   383  // refBase and refOff optionally give the base address of the object
   384  // in which the pointer p was found and the byte offset at which it
   385  // was found. These are used for error reporting.
   386  //
   387  // It is nosplit so it is safe for p to be a pointer to the current goroutine's stack.
   388  // Since p is a uintptr, it would not be adjusted if the stack were to move.
   389  //
   390  //go:nosplit
   391  func findObject(p, refBase, refOff uintptr) (base uintptr, s *mspan, objIndex uintptr) {
   392  	s = spanOf(p)
   393  	// If s is nil, the virtual address has never been part of the heap.
   394  	// This pointer may be to some mmap'd region, so we allow it.
   395  	if s == nil {
   396  		if (GOARCH == "amd64" || GOARCH == "arm64") && p == clobberdeadPtr && debug.invalidptr != 0 {
   397  			// Crash if clobberdeadPtr is seen. Only on AMD64 and ARM64 for now,
   398  			// as they are the only platform where compiler's clobberdead mode is
   399  			// implemented. On these platforms clobberdeadPtr cannot be a valid address.
   400  			badPointer(s, p, refBase, refOff)
   401  		}
   402  		return
   403  	}
   404  	// If p is a bad pointer, it may not be in s's bounds.
   405  	//
   406  	// Check s.state to synchronize with span initialization
   407  	// before checking other fields. See also spanOfHeap.
   408  	if state := s.state.get(); state != mSpanInUse || p < s.base() || p >= s.limit {
   409  		// Pointers into stacks are also ok, the runtime manages these explicitly.
   410  		if state == mSpanManual {
   411  			return
   412  		}
   413  		// The following ensures that we are rigorous about what data
   414  		// structures hold valid pointers.
   415  		if debug.invalidptr != 0 {
   416  			badPointer(s, p, refBase, refOff)
   417  		}
   418  		return
   419  	}
   420  
   421  	objIndex = s.objIndex(p)
   422  	base = s.base() + objIndex*s.elemsize
   423  	return
   424  }
   425  
   426  // verifyNotInHeapPtr reports whether converting the not-in-heap pointer into a unsafe.Pointer is ok.
   427  //
   428  //go:linkname reflect_verifyNotInHeapPtr reflect.verifyNotInHeapPtr
   429  func reflect_verifyNotInHeapPtr(p uintptr) bool {
   430  	// Conversion to a pointer is ok as long as findObject above does not call badPointer.
   431  	// Since we're already promised that p doesn't point into the heap, just disallow heap
   432  	// pointers and the special clobbered pointer.
   433  	return spanOf(p) == nil && p != clobberdeadPtr
   434  }
   435  
   436  // next returns the heapBits describing the next pointer-sized word in memory.
   437  // That is, if h describes address p, h.next() describes p+ptrSize.
   438  // Note that next does not modify h. The caller must record the result.
   439  //
   440  // nosplit because it is used during write barriers and must not be preempted.
   441  //
   442  //go:nosplit
   443  func (h heapBits) next() heapBits {
   444  	if h.shift < 3*heapBitsShift {
   445  		h.shift += heapBitsShift
   446  	} else if h.bitp != h.last {
   447  		h.bitp, h.shift = add1(h.bitp), 0
   448  	} else {
   449  		// Move to the next arena.
   450  		return h.nextArena()
   451  	}
   452  	return h
   453  }
   454  
   455  // nextArena advances h to the beginning of the next heap arena.
   456  //
   457  // This is a slow-path helper to next. gc's inliner knows that
   458  // heapBits.next can be inlined even though it calls this. This is
   459  // marked noinline so it doesn't get inlined into next and cause next
   460  // to be too big to inline.
   461  //
   462  //go:nosplit
   463  //go:noinline
   464  func (h heapBits) nextArena() heapBits {
   465  	h.arena++
   466  	ai := arenaIdx(h.arena)
   467  	l2 := mheap_.arenas[ai.l1()]
   468  	if l2 == nil {
   469  		// We just passed the end of the object, which
   470  		// was also the end of the heap. Poison h. It
   471  		// should never be dereferenced at this point.
   472  		return heapBits{}
   473  	}
   474  	ha := l2[ai.l2()]
   475  	if ha == nil {
   476  		return heapBits{}
   477  	}
   478  	h.bitp, h.shift = &ha.bitmap[0], 0
   479  	h.last = &ha.bitmap[len(ha.bitmap)-1]
   480  	return h
   481  }
   482  
   483  // forward returns the heapBits describing n pointer-sized words ahead of h in memory.
   484  // That is, if h describes address p, h.forward(n) describes p+n*ptrSize.
   485  // h.forward(1) is equivalent to h.next(), just slower.
   486  // Note that forward does not modify h. The caller must record the result.
   487  // bits returns the heap bits for the current word.
   488  //
   489  //go:nosplit
   490  func (h heapBits) forward(n uintptr) heapBits {
   491  	n += uintptr(h.shift) / heapBitsShift
   492  	nbitp := uintptr(unsafe.Pointer(h.bitp)) + n/4
   493  	h.shift = uint32(n%4) * heapBitsShift
   494  	if nbitp <= uintptr(unsafe.Pointer(h.last)) {
   495  		h.bitp = (*uint8)(unsafe.Pointer(nbitp))
   496  		return h
   497  	}
   498  
   499  	// We're in a new heap arena.
   500  	past := nbitp - (uintptr(unsafe.Pointer(h.last)) + 1)
   501  	h.arena += 1 + uint32(past/heapArenaBitmapBytes)
   502  	ai := arenaIdx(h.arena)
   503  	if l2 := mheap_.arenas[ai.l1()]; l2 != nil && l2[ai.l2()] != nil {
   504  		a := l2[ai.l2()]
   505  		h.bitp = &a.bitmap[past%heapArenaBitmapBytes]
   506  		h.last = &a.bitmap[len(a.bitmap)-1]
   507  	} else {
   508  		h.bitp, h.last = nil, nil
   509  	}
   510  	return h
   511  }
   512  
   513  // forwardOrBoundary is like forward, but stops at boundaries between
   514  // contiguous sections of the bitmap. It returns the number of words
   515  // advanced over, which will be <= n.
   516  func (h heapBits) forwardOrBoundary(n uintptr) (heapBits, uintptr) {
   517  	maxn := 4 * ((uintptr(unsafe.Pointer(h.last)) + 1) - uintptr(unsafe.Pointer(h.bitp)))
   518  	if n > maxn {
   519  		n = maxn
   520  	}
   521  	return h.forward(n), n
   522  }
   523  
   524  // The caller can test morePointers and isPointer by &-ing with bitScan and bitPointer.
   525  // The result includes in its higher bits the bits for subsequent words
   526  // described by the same bitmap byte.
   527  //
   528  // nosplit because it is used during write barriers and must not be preempted.
   529  //
   530  //go:nosplit
   531  func (h heapBits) bits() uint32 {
   532  	// The (shift & 31) eliminates a test and conditional branch
   533  	// from the generated code.
   534  	return uint32(*h.bitp) >> (h.shift & 31)
   535  }
   536  
   537  // morePointers reports whether this word and all remaining words in this object
   538  // are scalars.
   539  // h must not describe the second word of the object.
   540  func (h heapBits) morePointers() bool {
   541  	return h.bits()&bitScan != 0
   542  }
   543  
   544  // isPointer reports whether the heap bits describe a pointer word.
   545  //
   546  // nosplit because it is used during write barriers and must not be preempted.
   547  //
   548  //go:nosplit
   549  func (h heapBits) isPointer() bool {
   550  	return h.bits()&bitPointer != 0
   551  }
   552  
   553  // bulkBarrierPreWrite executes a write barrier
   554  // for every pointer slot in the memory range [src, src+size),
   555  // using pointer/scalar information from [dst, dst+size).
   556  // This executes the write barriers necessary before a memmove.
   557  // src, dst, and size must be pointer-aligned.
   558  // The range [dst, dst+size) must lie within a single object.
   559  // It does not perform the actual writes.
   560  //
   561  // As a special case, src == 0 indicates that this is being used for a
   562  // memclr. bulkBarrierPreWrite will pass 0 for the src of each write
   563  // barrier.
   564  //
   565  // Callers should call bulkBarrierPreWrite immediately before
   566  // calling memmove(dst, src, size). This function is marked nosplit
   567  // to avoid being preempted; the GC must not stop the goroutine
   568  // between the memmove and the execution of the barriers.
   569  // The caller is also responsible for cgo pointer checks if this
   570  // may be writing Go pointers into non-Go memory.
   571  //
   572  // The pointer bitmap is not maintained for allocations containing
   573  // no pointers at all; any caller of bulkBarrierPreWrite must first
   574  // make sure the underlying allocation contains pointers, usually
   575  // by checking typ.ptrdata.
   576  //
   577  // Callers must perform cgo checks if writeBarrier.cgo.
   578  //
   579  //go:nosplit
   580  func bulkBarrierPreWrite(dst, src, size uintptr) {
   581  	if (dst|src|size)&(goarch.PtrSize-1) != 0 {
   582  		throw("bulkBarrierPreWrite: unaligned arguments")
   583  	}
   584  	if !writeBarrier.needed {
   585  		return
   586  	}
   587  	if s := spanOf(dst); s == nil {
   588  		// If dst is a global, use the data or BSS bitmaps to
   589  		// execute write barriers.
   590  		for _, datap := range activeModules() {
   591  			if datap.data <= dst && dst < datap.edata {
   592  				bulkBarrierBitmap(dst, src, size, dst-datap.data, datap.gcdatamask.bytedata)
   593  				return
   594  			}
   595  		}
   596  		for _, datap := range activeModules() {
   597  			if datap.bss <= dst && dst < datap.ebss {
   598  				bulkBarrierBitmap(dst, src, size, dst-datap.bss, datap.gcbssmask.bytedata)
   599  				return
   600  			}
   601  		}
   602  		return
   603  	} else if s.state.get() != mSpanInUse || dst < s.base() || s.limit <= dst {
   604  		// dst was heap memory at some point, but isn't now.
   605  		// It can't be a global. It must be either our stack,
   606  		// or in the case of direct channel sends, it could be
   607  		// another stack. Either way, no need for barriers.
   608  		// This will also catch if dst is in a freed span,
   609  		// though that should never have.
   610  		return
   611  	}
   612  
   613  	buf := &getg().m.p.ptr().wbBuf
   614  	h := heapBitsForAddr(dst)
   615  	if src == 0 {
   616  		for i := uintptr(0); i < size; i += goarch.PtrSize {
   617  			if h.isPointer() {
   618  				dstx := (*uintptr)(unsafe.Pointer(dst + i))
   619  				if !buf.putFast(*dstx, 0) {
   620  					wbBufFlush(nil, 0)
   621  				}
   622  			}
   623  			h = h.next()
   624  		}
   625  	} else {
   626  		for i := uintptr(0); i < size; i += goarch.PtrSize {
   627  			if h.isPointer() {
   628  				dstx := (*uintptr)(unsafe.Pointer(dst + i))
   629  				srcx := (*uintptr)(unsafe.Pointer(src + i))
   630  				if !buf.putFast(*dstx, *srcx) {
   631  					wbBufFlush(nil, 0)
   632  				}
   633  			}
   634  			h = h.next()
   635  		}
   636  	}
   637  }
   638  
   639  // bulkBarrierPreWriteSrcOnly is like bulkBarrierPreWrite but
   640  // does not execute write barriers for [dst, dst+size).
   641  //
   642  // In addition to the requirements of bulkBarrierPreWrite
   643  // callers need to ensure [dst, dst+size) is zeroed.
   644  //
   645  // This is used for special cases where e.g. dst was just
   646  // created and zeroed with malloc.
   647  //
   648  //go:nosplit
   649  func bulkBarrierPreWriteSrcOnly(dst, src, size uintptr) {
   650  	if (dst|src|size)&(goarch.PtrSize-1) != 0 {
   651  		throw("bulkBarrierPreWrite: unaligned arguments")
   652  	}
   653  	if !writeBarrier.needed {
   654  		return
   655  	}
   656  	buf := &getg().m.p.ptr().wbBuf
   657  	h := heapBitsForAddr(dst)
   658  	for i := uintptr(0); i < size; i += goarch.PtrSize {
   659  		if h.isPointer() {
   660  			srcx := (*uintptr)(unsafe.Pointer(src + i))
   661  			if !buf.putFast(0, *srcx) {
   662  				wbBufFlush(nil, 0)
   663  			}
   664  		}
   665  		h = h.next()
   666  	}
   667  }
   668  
   669  // bulkBarrierBitmap executes write barriers for copying from [src,
   670  // src+size) to [dst, dst+size) using a 1-bit pointer bitmap. src is
   671  // assumed to start maskOffset bytes into the data covered by the
   672  // bitmap in bits (which may not be a multiple of 8).
   673  //
   674  // This is used by bulkBarrierPreWrite for writes to data and BSS.
   675  //
   676  //go:nosplit
   677  func bulkBarrierBitmap(dst, src, size, maskOffset uintptr, bits *uint8) {
   678  	word := maskOffset / goarch.PtrSize
   679  	bits = addb(bits, word/8)
   680  	mask := uint8(1) << (word % 8)
   681  
   682  	buf := &getg().m.p.ptr().wbBuf
   683  	for i := uintptr(0); i < size; i += goarch.PtrSize {
   684  		if mask == 0 {
   685  			bits = addb(bits, 1)
   686  			if *bits == 0 {
   687  				// Skip 8 words.
   688  				i += 7 * goarch.PtrSize
   689  				continue
   690  			}
   691  			mask = 1
   692  		}
   693  		if *bits&mask != 0 {
   694  			dstx := (*uintptr)(unsafe.Pointer(dst + i))
   695  			if src == 0 {
   696  				if !buf.putFast(*dstx, 0) {
   697  					wbBufFlush(nil, 0)
   698  				}
   699  			} else {
   700  				srcx := (*uintptr)(unsafe.Pointer(src + i))
   701  				if !buf.putFast(*dstx, *srcx) {
   702  					wbBufFlush(nil, 0)
   703  				}
   704  			}
   705  		}
   706  		mask <<= 1
   707  	}
   708  }
   709  
   710  // typeBitsBulkBarrier executes a write barrier for every
   711  // pointer that would be copied from [src, src+size) to [dst,
   712  // dst+size) by a memmove using the type bitmap to locate those
   713  // pointer slots.
   714  //
   715  // The type typ must correspond exactly to [src, src+size) and [dst, dst+size).
   716  // dst, src, and size must be pointer-aligned.
   717  // The type typ must have a plain bitmap, not a GC program.
   718  // The only use of this function is in channel sends, and the
   719  // 64 kB channel element limit takes care of this for us.
   720  //
   721  // Must not be preempted because it typically runs right before memmove,
   722  // and the GC must observe them as an atomic action.
   723  //
   724  // Callers must perform cgo checks if writeBarrier.cgo.
   725  //
   726  //go:nosplit
   727  func typeBitsBulkBarrier(typ *_type, dst, src, size uintptr) {
   728  	if typ == nil {
   729  		throw("runtime: typeBitsBulkBarrier without type")
   730  	}
   731  	if typ.size != size {
   732  		println("runtime: typeBitsBulkBarrier with type ", typ.string(), " of size ", typ.size, " but memory size", size)
   733  		throw("runtime: invalid typeBitsBulkBarrier")
   734  	}
   735  	if typ.kind&kindGCProg != 0 {
   736  		println("runtime: typeBitsBulkBarrier with type ", typ.string(), " with GC prog")
   737  		throw("runtime: invalid typeBitsBulkBarrier")
   738  	}
   739  	if !writeBarrier.needed {
   740  		return
   741  	}
   742  	ptrmask := typ.gcdata
   743  	buf := &getg().m.p.ptr().wbBuf
   744  	var bits uint32
   745  	for i := uintptr(0); i < typ.ptrdata; i += goarch.PtrSize {
   746  		if i&(goarch.PtrSize*8-1) == 0 {
   747  			bits = uint32(*ptrmask)
   748  			ptrmask = addb(ptrmask, 1)
   749  		} else {
   750  			bits = bits >> 1
   751  		}
   752  		if bits&1 != 0 {
   753  			dstx := (*uintptr)(unsafe.Pointer(dst + i))
   754  			srcx := (*uintptr)(unsafe.Pointer(src + i))
   755  			if !buf.putFast(*dstx, *srcx) {
   756  				wbBufFlush(nil, 0)
   757  			}
   758  		}
   759  	}
   760  }
   761  
   762  // The methods operating on spans all require that h has been returned
   763  // by heapBitsForSpan and that size, n, total are the span layout description
   764  // returned by the mspan's layout method.
   765  // If total > size*n, it means that there is extra leftover memory in the span,
   766  // usually due to rounding.
   767  //
   768  // TODO(rsc): Perhaps introduce a different heapBitsSpan type.
   769  
   770  // initSpan initializes the heap bitmap for a span.
   771  // If this is a span of pointer-sized objects, it initializes all
   772  // words to pointer/scan.
   773  // Otherwise, it initializes all words to scalar/dead.
   774  func (h heapBits) initSpan(s *mspan) {
   775  	// Clear bits corresponding to objects.
   776  	nw := (s.npages << _PageShift) / goarch.PtrSize
   777  	if nw%wordsPerBitmapByte != 0 {
   778  		throw("initSpan: unaligned length")
   779  	}
   780  	if h.shift != 0 {
   781  		throw("initSpan: unaligned base")
   782  	}
   783  	isPtrs := goarch.PtrSize == 8 && s.elemsize == goarch.PtrSize
   784  	for nw > 0 {
   785  		hNext, anw := h.forwardOrBoundary(nw)
   786  		nbyte := anw / wordsPerBitmapByte
   787  		if isPtrs {
   788  			bitp := h.bitp
   789  			for i := uintptr(0); i < nbyte; i++ {
   790  				*bitp = bitPointerAll | bitScanAll
   791  				bitp = add1(bitp)
   792  			}
   793  		} else {
   794  			memclrNoHeapPointers(unsafe.Pointer(h.bitp), nbyte)
   795  		}
   796  		h = hNext
   797  		nw -= anw
   798  	}
   799  }
   800  
   801  // countAlloc returns the number of objects allocated in span s by
   802  // scanning the allocation bitmap.
   803  func (s *mspan) countAlloc() int {
   804  	count := 0
   805  	bytes := divRoundUp(s.nelems, 8)
   806  	// Iterate over each 8-byte chunk and count allocations
   807  	// with an intrinsic. Note that newMarkBits guarantees that
   808  	// gcmarkBits will be 8-byte aligned, so we don't have to
   809  	// worry about edge cases, irrelevant bits will simply be zero.
   810  	for i := uintptr(0); i < bytes; i += 8 {
   811  		// Extract 64 bits from the byte pointer and get a OnesCount.
   812  		// Note that the unsafe cast here doesn't preserve endianness,
   813  		// but that's OK. We only care about how many bits are 1, not
   814  		// about the order we discover them in.
   815  		mrkBits := *(*uint64)(unsafe.Pointer(s.gcmarkBits.bytep(i)))
   816  		count += sys.OnesCount64(mrkBits)
   817  	}
   818  	return count
   819  }
   820  
   821  // heapBitsSetType records that the new allocation [x, x+size)
   822  // holds in [x, x+dataSize) one or more values of type typ.
   823  // (The number of values is given by dataSize / typ.size.)
   824  // If dataSize < size, the fragment [x+dataSize, x+size) is
   825  // recorded as non-pointer data.
   826  // It is known that the type has pointers somewhere;
   827  // malloc does not call heapBitsSetType when there are no pointers,
   828  // because all free objects are marked as noscan during
   829  // heapBitsSweepSpan.
   830  //
   831  // There can only be one allocation from a given span active at a time,
   832  // and the bitmap for a span always falls on byte boundaries,
   833  // so there are no write-write races for access to the heap bitmap.
   834  // Hence, heapBitsSetType can access the bitmap without atomics.
   835  //
   836  // There can be read-write races between heapBitsSetType and things
   837  // that read the heap bitmap like scanobject. However, since
   838  // heapBitsSetType is only used for objects that have not yet been
   839  // made reachable, readers will ignore bits being modified by this
   840  // function. This does mean this function cannot transiently modify
   841  // bits that belong to neighboring objects. Also, on weakly-ordered
   842  // machines, callers must execute a store/store (publication) barrier
   843  // between calling this function and making the object reachable.
   844  func heapBitsSetType(x, size, dataSize uintptr, typ *_type) {
   845  	const doubleCheck = false // slow but helpful; enable to test modifications to this code
   846  
   847  	const (
   848  		mask1 = bitPointer | bitScan                        // 00010001
   849  		mask2 = bitPointer | bitScan | mask1<<heapBitsShift // 00110011
   850  		mask3 = bitPointer | bitScan | mask2<<heapBitsShift // 01110111
   851  	)
   852  
   853  	// dataSize is always size rounded up to the next malloc size class,
   854  	// except in the case of allocating a defer block, in which case
   855  	// size is sizeof(_defer{}) (at least 6 words) and dataSize may be
   856  	// arbitrarily larger.
   857  	//
   858  	// The checks for size == goarch.PtrSize and size == 2*goarch.PtrSize can therefore
   859  	// assume that dataSize == size without checking it explicitly.
   860  
   861  	if goarch.PtrSize == 8 && size == goarch.PtrSize {
   862  		// It's one word and it has pointers, it must be a pointer.
   863  		// Since all allocated one-word objects are pointers
   864  		// (non-pointers are aggregated into tinySize allocations),
   865  		// initSpan sets the pointer bits for us. Nothing to do here.
   866  		if doubleCheck {
   867  			h := heapBitsForAddr(x)
   868  			if !h.isPointer() {
   869  				throw("heapBitsSetType: pointer bit missing")
   870  			}
   871  			if !h.morePointers() {
   872  				throw("heapBitsSetType: scan bit missing")
   873  			}
   874  		}
   875  		return
   876  	}
   877  
   878  	h := heapBitsForAddr(x)
   879  	ptrmask := typ.gcdata // start of 1-bit pointer mask (or GC program, handled below)
   880  
   881  	// 2-word objects only have 4 bitmap bits and 3-word objects only have 6 bitmap bits.
   882  	// Therefore, these objects share a heap bitmap byte with the objects next to them.
   883  	// These are called out as a special case primarily so the code below can assume all
   884  	// objects are at least 4 words long and that their bitmaps start either at the beginning
   885  	// of a bitmap byte, or half-way in (h.shift of 0 and 2 respectively).
   886  
   887  	if size == 2*goarch.PtrSize {
   888  		if typ.size == goarch.PtrSize {
   889  			// We're allocating a block big enough to hold two pointers.
   890  			// On 64-bit, that means the actual object must be two pointers,
   891  			// or else we'd have used the one-pointer-sized block.
   892  			// On 32-bit, however, this is the 8-byte block, the smallest one.
   893  			// So it could be that we're allocating one pointer and this was
   894  			// just the smallest block available. Distinguish by checking dataSize.
   895  			// (In general the number of instances of typ being allocated is
   896  			// dataSize/typ.size.)
   897  			if goarch.PtrSize == 4 && dataSize == goarch.PtrSize {
   898  				// 1 pointer object. On 32-bit machines clear the bit for the
   899  				// unused second word.
   900  				*h.bitp &^= (bitPointer | bitScan | (bitPointer|bitScan)<<heapBitsShift) << h.shift
   901  				*h.bitp |= (bitPointer | bitScan) << h.shift
   902  			} else {
   903  				// 2-element array of pointer.
   904  				*h.bitp |= (bitPointer | bitScan | (bitPointer|bitScan)<<heapBitsShift) << h.shift
   905  			}
   906  			return
   907  		}
   908  		// Otherwise typ.size must be 2*goarch.PtrSize,
   909  		// and typ.kind&kindGCProg == 0.
   910  		if doubleCheck {
   911  			if typ.size != 2*goarch.PtrSize || typ.kind&kindGCProg != 0 {
   912  				print("runtime: heapBitsSetType size=", size, " but typ.size=", typ.size, " gcprog=", typ.kind&kindGCProg != 0, "\n")
   913  				throw("heapBitsSetType")
   914  			}
   915  		}
   916  		b := uint32(*ptrmask)
   917  		hb := b & 3
   918  		hb |= bitScanAll & ((bitScan << (typ.ptrdata / goarch.PtrSize)) - 1)
   919  		// Clear the bits for this object so we can set the
   920  		// appropriate ones.
   921  		*h.bitp &^= (bitPointer | bitScan | ((bitPointer | bitScan) << heapBitsShift)) << h.shift
   922  		*h.bitp |= uint8(hb << h.shift)
   923  		return
   924  	} else if size == 3*goarch.PtrSize {
   925  		b := uint8(*ptrmask)
   926  		if doubleCheck {
   927  			if b == 0 {
   928  				println("runtime: invalid type ", typ.string())
   929  				throw("heapBitsSetType: called with non-pointer type")
   930  			}
   931  			if goarch.PtrSize != 8 {
   932  				throw("heapBitsSetType: unexpected 3 pointer wide size class on 32 bit")
   933  			}
   934  			if typ.kind&kindGCProg != 0 {
   935  				throw("heapBitsSetType: unexpected GC prog for 3 pointer wide size class")
   936  			}
   937  			if typ.size == 2*goarch.PtrSize {
   938  				print("runtime: heapBitsSetType size=", size, " but typ.size=", typ.size, "\n")
   939  				throw("heapBitsSetType: inconsistent object sizes")
   940  			}
   941  		}
   942  		if typ.size == goarch.PtrSize {
   943  			// The type contains a pointer otherwise heapBitsSetType wouldn't have been called.
   944  			// Since the type is only 1 pointer wide and contains a pointer, its gcdata must be exactly 1.
   945  			if doubleCheck && *typ.gcdata != 1 {
   946  				print("runtime: heapBitsSetType size=", size, " typ.size=", typ.size, "but *typ.gcdata", *typ.gcdata, "\n")
   947  				throw("heapBitsSetType: unexpected gcdata for 1 pointer wide type size in 3 pointer wide size class")
   948  			}
   949  			// 3 element array of pointers. Unrolling ptrmask 3 times into p yields 00000111.
   950  			b = 7
   951  		}
   952  
   953  		hb := b & 7
   954  		// Set bitScan bits for all pointers.
   955  		hb |= hb << wordsPerBitmapByte
   956  		// First bitScan bit is always set since the type contains pointers.
   957  		hb |= bitScan
   958  		// Second bitScan bit needs to also be set if the third bitScan bit is set.
   959  		hb |= hb & (bitScan << (2 * heapBitsShift)) >> 1
   960  
   961  		// For h.shift > 1 heap bits cross a byte boundary and need to be written part
   962  		// to h.bitp and part to the next h.bitp.
   963  		switch h.shift {
   964  		case 0:
   965  			*h.bitp &^= mask3 << 0
   966  			*h.bitp |= hb << 0
   967  		case 1:
   968  			*h.bitp &^= mask3 << 1
   969  			*h.bitp |= hb << 1
   970  		case 2:
   971  			*h.bitp &^= mask2 << 2
   972  			*h.bitp |= (hb & mask2) << 2
   973  			// Two words written to the first byte.
   974  			// Advance two words to get to the next byte.
   975  			h = h.next().next()
   976  			*h.bitp &^= mask1
   977  			*h.bitp |= (hb >> 2) & mask1
   978  		case 3:
   979  			*h.bitp &^= mask1 << 3
   980  			*h.bitp |= (hb & mask1) << 3
   981  			// One word written to the first byte.
   982  			// Advance one word to get to the next byte.
   983  			h = h.next()
   984  			*h.bitp &^= mask2
   985  			*h.bitp |= (hb >> 1) & mask2
   986  		}
   987  		return
   988  	}
   989  
   990  	// Copy from 1-bit ptrmask into 2-bit bitmap.
   991  	// The basic approach is to use a single uintptr as a bit buffer,
   992  	// alternating between reloading the buffer and writing bitmap bytes.
   993  	// In general, one load can supply two bitmap byte writes.
   994  	// This is a lot of lines of code, but it compiles into relatively few
   995  	// machine instructions.
   996  
   997  	outOfPlace := false
   998  	if arenaIndex(x+size-1) != arenaIdx(h.arena) || (doubleCheck && fastrandn(2) == 0) {
   999  		// This object spans heap arenas, so the bitmap may be
  1000  		// discontiguous. Unroll it into the object instead
  1001  		// and then copy it out.
  1002  		//
  1003  		// In doubleCheck mode, we randomly do this anyway to
  1004  		// stress test the bitmap copying path.
  1005  		outOfPlace = true
  1006  		h.bitp = (*uint8)(unsafe.Pointer(x))
  1007  		h.last = nil
  1008  	}
  1009  
  1010  	var (
  1011  		// Ptrmask input.
  1012  		p     *byte   // last ptrmask byte read
  1013  		b     uintptr // ptrmask bits already loaded
  1014  		nb    uintptr // number of bits in b at next read
  1015  		endp  *byte   // final ptrmask byte to read (then repeat)
  1016  		endnb uintptr // number of valid bits in *endp
  1017  		pbits uintptr // alternate source of bits
  1018  
  1019  		// Heap bitmap output.
  1020  		w     uintptr // words processed
  1021  		nw    uintptr // number of words to process
  1022  		hbitp *byte   // next heap bitmap byte to write
  1023  		hb    uintptr // bits being prepared for *hbitp
  1024  	)
  1025  
  1026  	hbitp = h.bitp
  1027  
  1028  	// Handle GC program. Delayed until this part of the code
  1029  	// so that we can use the same double-checking mechanism
  1030  	// as the 1-bit case. Nothing above could have encountered
  1031  	// GC programs: the cases were all too small.
  1032  	if typ.kind&kindGCProg != 0 {
  1033  		heapBitsSetTypeGCProg(h, typ.ptrdata, typ.size, dataSize, size, addb(typ.gcdata, 4))
  1034  		if doubleCheck {
  1035  			// Double-check the heap bits written by GC program
  1036  			// by running the GC program to create a 1-bit pointer mask
  1037  			// and then jumping to the double-check code below.
  1038  			// This doesn't catch bugs shared between the 1-bit and 4-bit
  1039  			// GC program execution, but it does catch mistakes specific
  1040  			// to just one of those and bugs in heapBitsSetTypeGCProg's
  1041  			// implementation of arrays.
  1042  			lock(&debugPtrmask.lock)
  1043  			if debugPtrmask.data == nil {
  1044  				debugPtrmask.data = (*byte)(persistentalloc(1<<20, 1, &memstats.other_sys))
  1045  			}
  1046  			ptrmask = debugPtrmask.data
  1047  			runGCProg(addb(typ.gcdata, 4), nil, ptrmask, 1)
  1048  		}
  1049  		goto Phase4
  1050  	}
  1051  
  1052  	// Note about sizes:
  1053  	//
  1054  	// typ.size is the number of words in the object,
  1055  	// and typ.ptrdata is the number of words in the prefix
  1056  	// of the object that contains pointers. That is, the final
  1057  	// typ.size - typ.ptrdata words contain no pointers.
  1058  	// This allows optimization of a common pattern where
  1059  	// an object has a small header followed by a large scalar
  1060  	// buffer. If we know the pointers are over, we don't have
  1061  	// to scan the buffer's heap bitmap at all.
  1062  	// The 1-bit ptrmasks are sized to contain only bits for
  1063  	// the typ.ptrdata prefix, zero padded out to a full byte
  1064  	// of bitmap. This code sets nw (below) so that heap bitmap
  1065  	// bits are only written for the typ.ptrdata prefix; if there is
  1066  	// more room in the allocated object, the next heap bitmap
  1067  	// entry is a 00, indicating that there are no more pointers
  1068  	// to scan. So only the ptrmask for the ptrdata bytes is needed.
  1069  	//
  1070  	// Replicated copies are not as nice: if there is an array of
  1071  	// objects with scalar tails, all but the last tail does have to
  1072  	// be initialized, because there is no way to say "skip forward".
  1073  	// However, because of the possibility of a repeated type with
  1074  	// size not a multiple of 4 pointers (one heap bitmap byte),
  1075  	// the code already must handle the last ptrmask byte specially
  1076  	// by treating it as containing only the bits for endnb pointers,
  1077  	// where endnb <= 4. We represent large scalar tails that must
  1078  	// be expanded in the replication by setting endnb larger than 4.
  1079  	// This will have the effect of reading many bits out of b,
  1080  	// but once the real bits are shifted out, b will supply as many
  1081  	// zero bits as we try to read, which is exactly what we need.
  1082  
  1083  	p = ptrmask
  1084  	if typ.size < dataSize {
  1085  		// Filling in bits for an array of typ.
  1086  		// Set up for repetition of ptrmask during main loop.
  1087  		// Note that ptrmask describes only a prefix of
  1088  		const maxBits = goarch.PtrSize*8 - 7
  1089  		if typ.ptrdata/goarch.PtrSize <= maxBits {
  1090  			// Entire ptrmask fits in uintptr with room for a byte fragment.
  1091  			// Load into pbits and never read from ptrmask again.
  1092  			// This is especially important when the ptrmask has
  1093  			// fewer than 8 bits in it; otherwise the reload in the middle
  1094  			// of the Phase 2 loop would itself need to loop to gather
  1095  			// at least 8 bits.
  1096  
  1097  			// Accumulate ptrmask into b.
  1098  			// ptrmask is sized to describe only typ.ptrdata, but we record
  1099  			// it as describing typ.size bytes, since all the high bits are zero.
  1100  			nb = typ.ptrdata / goarch.PtrSize
  1101  			for i := uintptr(0); i < nb; i += 8 {
  1102  				b |= uintptr(*p) << i
  1103  				p = add1(p)
  1104  			}
  1105  			nb = typ.size / goarch.PtrSize
  1106  
  1107  			// Replicate ptrmask to fill entire pbits uintptr.
  1108  			// Doubling and truncating is fewer steps than
  1109  			// iterating by nb each time. (nb could be 1.)
  1110  			// Since we loaded typ.ptrdata/goarch.PtrSize bits
  1111  			// but are pretending to have typ.size/goarch.PtrSize,
  1112  			// there might be no replication necessary/possible.
  1113  			pbits = b
  1114  			endnb = nb
  1115  			if nb+nb <= maxBits {
  1116  				for endnb <= goarch.PtrSize*8 {
  1117  					pbits |= pbits << endnb
  1118  					endnb += endnb
  1119  				}
  1120  				// Truncate to a multiple of original ptrmask.
  1121  				// Because nb+nb <= maxBits, nb fits in a byte.
  1122  				// Byte division is cheaper than uintptr division.
  1123  				endnb = uintptr(maxBits/byte(nb)) * nb
  1124  				pbits &= 1<<endnb - 1
  1125  				b = pbits
  1126  				nb = endnb
  1127  			}
  1128  
  1129  			// Clear p and endp as sentinel for using pbits.
  1130  			// Checked during Phase 2 loop.
  1131  			p = nil
  1132  			endp = nil
  1133  		} else {
  1134  			// Ptrmask is larger. Read it multiple times.
  1135  			n := (typ.ptrdata/goarch.PtrSize+7)/8 - 1
  1136  			endp = addb(ptrmask, n)
  1137  			endnb = typ.size/goarch.PtrSize - n*8
  1138  		}
  1139  	}
  1140  	if p != nil {
  1141  		b = uintptr(*p)
  1142  		p = add1(p)
  1143  		nb = 8
  1144  	}
  1145  
  1146  	if typ.size == dataSize {
  1147  		// Single entry: can stop once we reach the non-pointer data.
  1148  		nw = typ.ptrdata / goarch.PtrSize
  1149  	} else {
  1150  		// Repeated instances of typ in an array.
  1151  		// Have to process first N-1 entries in full, but can stop
  1152  		// once we reach the non-pointer data in the final entry.
  1153  		nw = ((dataSize/typ.size-1)*typ.size + typ.ptrdata) / goarch.PtrSize
  1154  	}
  1155  	if nw == 0 {
  1156  		// No pointers! Caller was supposed to check.
  1157  		println("runtime: invalid type ", typ.string())
  1158  		throw("heapBitsSetType: called with non-pointer type")
  1159  		return
  1160  	}
  1161  
  1162  	// Phase 1: Special case for leading byte (shift==0) or half-byte (shift==2).
  1163  	// The leading byte is special because it contains the bits for word 1,
  1164  	// which does not have the scan bit set.
  1165  	// The leading half-byte is special because it's a half a byte,
  1166  	// so we have to be careful with the bits already there.
  1167  	switch {
  1168  	default:
  1169  		throw("heapBitsSetType: unexpected shift")
  1170  
  1171  	case h.shift == 0:
  1172  		// Ptrmask and heap bitmap are aligned.
  1173  		//
  1174  		// This is a fast path for small objects.
  1175  		//
  1176  		// The first byte we write out covers the first four
  1177  		// words of the object. The scan/dead bit on the first
  1178  		// word must be set to scan since there are pointers
  1179  		// somewhere in the object.
  1180  		// In all following words, we set the scan/dead
  1181  		// appropriately to indicate that the object continues
  1182  		// to the next 2-bit entry in the bitmap.
  1183  		//
  1184  		// We set four bits at a time here, but if the object
  1185  		// is fewer than four words, phase 3 will clear
  1186  		// unnecessary bits.
  1187  		hb = b & bitPointerAll
  1188  		hb |= bitScanAll
  1189  		if w += 4; w >= nw {
  1190  			goto Phase3
  1191  		}
  1192  		*hbitp = uint8(hb)
  1193  		hbitp = add1(hbitp)
  1194  		b >>= 4
  1195  		nb -= 4
  1196  
  1197  	case h.shift == 2:
  1198  		// Ptrmask and heap bitmap are misaligned.
  1199  		//
  1200  		// On 32 bit architectures only the 6-word object that corresponds
  1201  		// to a 24 bytes size class can start with h.shift of 2 here since
  1202  		// all other non 16 byte aligned size classes have been handled by
  1203  		// special code paths at the beginning of heapBitsSetType on 32 bit.
  1204  		//
  1205  		// Many size classes are only 16 byte aligned. On 64 bit architectures
  1206  		// this results in a heap bitmap position starting with a h.shift of 2.
  1207  		//
  1208  		// The bits for the first two words are in a byte shared
  1209  		// with another object, so we must be careful with the bits
  1210  		// already there.
  1211  		//
  1212  		// We took care of 1-word, 2-word, and 3-word objects above,
  1213  		// so this is at least a 6-word object.
  1214  		hb = (b & (bitPointer | bitPointer<<heapBitsShift)) << (2 * heapBitsShift)
  1215  		hb |= bitScan << (2 * heapBitsShift)
  1216  		if nw > 1 {
  1217  			hb |= bitScan << (3 * heapBitsShift)
  1218  		}
  1219  		b >>= 2
  1220  		nb -= 2
  1221  		*hbitp &^= uint8((bitPointer | bitScan | ((bitPointer | bitScan) << heapBitsShift)) << (2 * heapBitsShift))
  1222  		*hbitp |= uint8(hb)
  1223  		hbitp = add1(hbitp)
  1224  		if w += 2; w >= nw {
  1225  			// We know that there is more data, because we handled 2-word and 3-word objects above.
  1226  			// This must be at least a 6-word object. If we're out of pointer words,
  1227  			// mark no scan in next bitmap byte and finish.
  1228  			hb = 0
  1229  			w += 4
  1230  			goto Phase3
  1231  		}
  1232  	}
  1233  
  1234  	// Phase 2: Full bytes in bitmap, up to but not including write to last byte (full or partial) in bitmap.
  1235  	// The loop computes the bits for that last write but does not execute the write;
  1236  	// it leaves the bits in hb for processing by phase 3.
  1237  	// To avoid repeated adjustment of nb, we subtract out the 4 bits we're going to
  1238  	// use in the first half of the loop right now, and then we only adjust nb explicitly
  1239  	// if the 8 bits used by each iteration isn't balanced by 8 bits loaded mid-loop.
  1240  	nb -= 4
  1241  	for {
  1242  		// Emit bitmap byte.
  1243  		// b has at least nb+4 bits, with one exception:
  1244  		// if w+4 >= nw, then b has only nw-w bits,
  1245  		// but we'll stop at the break and then truncate
  1246  		// appropriately in Phase 3.
  1247  		hb = b & bitPointerAll
  1248  		hb |= bitScanAll
  1249  		if w += 4; w >= nw {
  1250  			break
  1251  		}
  1252  		*hbitp = uint8(hb)
  1253  		hbitp = add1(hbitp)
  1254  		b >>= 4
  1255  
  1256  		// Load more bits. b has nb right now.
  1257  		if p != endp {
  1258  			// Fast path: keep reading from ptrmask.
  1259  			// nb unmodified: we just loaded 8 bits,
  1260  			// and the next iteration will consume 8 bits,
  1261  			// leaving us with the same nb the next time we're here.
  1262  			if nb < 8 {
  1263  				b |= uintptr(*p) << nb
  1264  				p = add1(p)
  1265  			} else {
  1266  				// Reduce the number of bits in b.
  1267  				// This is important if we skipped
  1268  				// over a scalar tail, since nb could
  1269  				// be larger than the bit width of b.
  1270  				nb -= 8
  1271  			}
  1272  		} else if p == nil {
  1273  			// Almost as fast path: track bit count and refill from pbits.
  1274  			// For short repetitions.
  1275  			if nb < 8 {
  1276  				b |= pbits << nb
  1277  				nb += endnb
  1278  			}
  1279  			nb -= 8 // for next iteration
  1280  		} else {
  1281  			// Slow path: reached end of ptrmask.
  1282  			// Process final partial byte and rewind to start.
  1283  			b |= uintptr(*p) << nb
  1284  			nb += endnb
  1285  			if nb < 8 {
  1286  				b |= uintptr(*ptrmask) << nb
  1287  				p = add1(ptrmask)
  1288  			} else {
  1289  				nb -= 8
  1290  				p = ptrmask
  1291  			}
  1292  		}
  1293  
  1294  		// Emit bitmap byte.
  1295  		hb = b & bitPointerAll
  1296  		hb |= bitScanAll
  1297  		if w += 4; w >= nw {
  1298  			break
  1299  		}
  1300  		*hbitp = uint8(hb)
  1301  		hbitp = add1(hbitp)
  1302  		b >>= 4
  1303  	}
  1304  
  1305  Phase3:
  1306  	// Phase 3: Write last byte or partial byte and zero the rest of the bitmap entries.
  1307  	if w > nw {
  1308  		// Counting the 4 entries in hb not yet written to memory,
  1309  		// there are more entries than possible pointer slots.
  1310  		// Discard the excess entries (can't be more than 3).
  1311  		mask := uintptr(1)<<(4-(w-nw)) - 1
  1312  		hb &= mask | mask<<4 // apply mask to both pointer bits and scan bits
  1313  	}
  1314  
  1315  	// Change nw from counting possibly-pointer words to total words in allocation.
  1316  	nw = size / goarch.PtrSize
  1317  
  1318  	// Write whole bitmap bytes.
  1319  	// The first is hb, the rest are zero.
  1320  	if w <= nw {
  1321  		*hbitp = uint8(hb)
  1322  		hbitp = add1(hbitp)
  1323  		hb = 0 // for possible final half-byte below
  1324  		for w += 4; w <= nw; w += 4 {
  1325  			*hbitp = 0
  1326  			hbitp = add1(hbitp)
  1327  		}
  1328  	}
  1329  
  1330  	// Write final partial bitmap byte if any.
  1331  	// We know w > nw, or else we'd still be in the loop above.
  1332  	// It can be bigger only due to the 4 entries in hb that it counts.
  1333  	// If w == nw+4 then there's nothing left to do: we wrote all nw entries
  1334  	// and can discard the 4 sitting in hb.
  1335  	// But if w == nw+2, we need to write first two in hb.
  1336  	// The byte is shared with the next object, so be careful with
  1337  	// existing bits.
  1338  	if w == nw+2 {
  1339  		*hbitp = *hbitp&^(bitPointer|bitScan|(bitPointer|bitScan)<<heapBitsShift) | uint8(hb)
  1340  	}
  1341  
  1342  Phase4:
  1343  	// Phase 4: Copy unrolled bitmap to per-arena bitmaps, if necessary.
  1344  	if outOfPlace {
  1345  		// TODO: We could probably make this faster by
  1346  		// handling [x+dataSize, x+size) specially.
  1347  		h := heapBitsForAddr(x)
  1348  		// cnw is the number of heap words, or bit pairs
  1349  		// remaining (like nw above).
  1350  		cnw := size / goarch.PtrSize
  1351  		src := (*uint8)(unsafe.Pointer(x))
  1352  		// We know the first and last byte of the bitmap are
  1353  		// not the same, but it's still possible for small
  1354  		// objects span arenas, so it may share bitmap bytes
  1355  		// with neighboring objects.
  1356  		//
  1357  		// Handle the first byte specially if it's shared. See
  1358  		// Phase 1 for why this is the only special case we need.
  1359  		if doubleCheck {
  1360  			if !(h.shift == 0 || h.shift == 2) {
  1361  				print("x=", x, " size=", size, " cnw=", h.shift, "\n")
  1362  				throw("bad start shift")
  1363  			}
  1364  		}
  1365  		if h.shift == 2 {
  1366  			*h.bitp = *h.bitp&^((bitPointer|bitScan|(bitPointer|bitScan)<<heapBitsShift)<<(2*heapBitsShift)) | *src
  1367  			h = h.next().next()
  1368  			cnw -= 2
  1369  			src = addb(src, 1)
  1370  		}
  1371  		// We're now byte aligned. Copy out to per-arena
  1372  		// bitmaps until the last byte (which may again be
  1373  		// partial).
  1374  		for cnw >= 4 {
  1375  			// This loop processes four words at a time,
  1376  			// so round cnw down accordingly.
  1377  			hNext, words := h.forwardOrBoundary(cnw / 4 * 4)
  1378  
  1379  			// n is the number of bitmap bytes to copy.
  1380  			n := words / 4
  1381  			memmove(unsafe.Pointer(h.bitp), unsafe.Pointer(src), n)
  1382  			cnw -= words
  1383  			h = hNext
  1384  			src = addb(src, n)
  1385  		}
  1386  		if doubleCheck && h.shift != 0 {
  1387  			print("cnw=", cnw, " h.shift=", h.shift, "\n")
  1388  			throw("bad shift after block copy")
  1389  		}
  1390  		// Handle the last byte if it's shared.
  1391  		if cnw == 2 {
  1392  			*h.bitp = *h.bitp&^(bitPointer|bitScan|(bitPointer|bitScan)<<heapBitsShift) | *src
  1393  			src = addb(src, 1)
  1394  			h = h.next().next()
  1395  		}
  1396  		if doubleCheck {
  1397  			if uintptr(unsafe.Pointer(src)) > x+size {
  1398  				throw("copy exceeded object size")
  1399  			}
  1400  			if !(cnw == 0 || cnw == 2) {
  1401  				print("x=", x, " size=", size, " cnw=", cnw, "\n")
  1402  				throw("bad number of remaining words")
  1403  			}
  1404  			// Set up hbitp so doubleCheck code below can check it.
  1405  			hbitp = h.bitp
  1406  		}
  1407  		// Zero the object where we wrote the bitmap.
  1408  		memclrNoHeapPointers(unsafe.Pointer(x), uintptr(unsafe.Pointer(src))-x)
  1409  	}
  1410  
  1411  	// Double check the whole bitmap.
  1412  	if doubleCheck {
  1413  		// x+size may not point to the heap, so back up one
  1414  		// word and then advance it the way we do above.
  1415  		end := heapBitsForAddr(x + size - goarch.PtrSize)
  1416  		if outOfPlace {
  1417  			// In out-of-place copying, we just advance
  1418  			// using next.
  1419  			end = end.next()
  1420  		} else {
  1421  			// Don't use next because that may advance to
  1422  			// the next arena and the in-place logic
  1423  			// doesn't do that.
  1424  			end.shift += heapBitsShift
  1425  			if end.shift == 4*heapBitsShift {
  1426  				end.bitp, end.shift = add1(end.bitp), 0
  1427  			}
  1428  		}
  1429  		if typ.kind&kindGCProg == 0 && (hbitp != end.bitp || (w == nw+2) != (end.shift == 2)) {
  1430  			println("ended at wrong bitmap byte for", typ.string(), "x", dataSize/typ.size)
  1431  			print("typ.size=", typ.size, " typ.ptrdata=", typ.ptrdata, " dataSize=", dataSize, " size=", size, "\n")
  1432  			print("w=", w, " nw=", nw, " b=", hex(b), " nb=", nb, " hb=", hex(hb), "\n")
  1433  			h0 := heapBitsForAddr(x)
  1434  			print("initial bits h0.bitp=", h0.bitp, " h0.shift=", h0.shift, "\n")
  1435  			print("ended at hbitp=", hbitp, " but next starts at bitp=", end.bitp, " shift=", end.shift, "\n")
  1436  			throw("bad heapBitsSetType")
  1437  		}
  1438  
  1439  		// Double-check that bits to be written were written correctly.
  1440  		// Does not check that other bits were not written, unfortunately.
  1441  		h := heapBitsForAddr(x)
  1442  		nptr := typ.ptrdata / goarch.PtrSize
  1443  		ndata := typ.size / goarch.PtrSize
  1444  		count := dataSize / typ.size
  1445  		totalptr := ((count-1)*typ.size + typ.ptrdata) / goarch.PtrSize
  1446  		for i := uintptr(0); i < size/goarch.PtrSize; i++ {
  1447  			j := i % ndata
  1448  			var have, want uint8
  1449  			have = (*h.bitp >> h.shift) & (bitPointer | bitScan)
  1450  			if i >= totalptr {
  1451  				if typ.kind&kindGCProg != 0 && i < (totalptr+3)/4*4 {
  1452  					// heapBitsSetTypeGCProg always fills
  1453  					// in full nibbles of bitScan.
  1454  					want = bitScan
  1455  				}
  1456  			} else {
  1457  				if j < nptr && (*addb(ptrmask, j/8)>>(j%8))&1 != 0 {
  1458  					want |= bitPointer
  1459  				}
  1460  				want |= bitScan
  1461  			}
  1462  			if have != want {
  1463  				println("mismatch writing bits for", typ.string(), "x", dataSize/typ.size)
  1464  				print("typ.size=", typ.size, " typ.ptrdata=", typ.ptrdata, " dataSize=", dataSize, " size=", size, "\n")
  1465  				print("kindGCProg=", typ.kind&kindGCProg != 0, " outOfPlace=", outOfPlace, "\n")
  1466  				print("w=", w, " nw=", nw, " b=", hex(b), " nb=", nb, " hb=", hex(hb), "\n")
  1467  				h0 := heapBitsForAddr(x)
  1468  				print("initial bits h0.bitp=", h0.bitp, " h0.shift=", h0.shift, "\n")
  1469  				print("current bits h.bitp=", h.bitp, " h.shift=", h.shift, " *h.bitp=", hex(*h.bitp), "\n")
  1470  				print("ptrmask=", ptrmask, " p=", p, " endp=", endp, " endnb=", endnb, " pbits=", hex(pbits), " b=", hex(b), " nb=", nb, "\n")
  1471  				println("at word", i, "offset", i*goarch.PtrSize, "have", hex(have), "want", hex(want))
  1472  				if typ.kind&kindGCProg != 0 {
  1473  					println("GC program:")
  1474  					dumpGCProg(addb(typ.gcdata, 4))
  1475  				}
  1476  				throw("bad heapBitsSetType")
  1477  			}
  1478  			h = h.next()
  1479  		}
  1480  		if ptrmask == debugPtrmask.data {
  1481  			unlock(&debugPtrmask.lock)
  1482  		}
  1483  	}
  1484  }
  1485  
  1486  var debugPtrmask struct {
  1487  	lock mutex
  1488  	data *byte
  1489  }
  1490  
  1491  // heapBitsSetTypeGCProg implements heapBitsSetType using a GC program.
  1492  // progSize is the size of the memory described by the program.
  1493  // elemSize is the size of the element that the GC program describes (a prefix of).
  1494  // dataSize is the total size of the intended data, a multiple of elemSize.
  1495  // allocSize is the total size of the allocated memory.
  1496  //
  1497  // GC programs are only used for large allocations.
  1498  // heapBitsSetType requires that allocSize is a multiple of 4 words,
  1499  // so that the relevant bitmap bytes are not shared with surrounding
  1500  // objects.
  1501  func heapBitsSetTypeGCProg(h heapBits, progSize, elemSize, dataSize, allocSize uintptr, prog *byte) {
  1502  	if goarch.PtrSize == 8 && allocSize%(4*goarch.PtrSize) != 0 {
  1503  		// Alignment will be wrong.
  1504  		throw("heapBitsSetTypeGCProg: small allocation")
  1505  	}
  1506  	var totalBits uintptr
  1507  	if elemSize == dataSize {
  1508  		totalBits = runGCProg(prog, nil, h.bitp, 2)
  1509  		if totalBits*goarch.PtrSize != progSize {
  1510  			println("runtime: heapBitsSetTypeGCProg: total bits", totalBits, "but progSize", progSize)
  1511  			throw("heapBitsSetTypeGCProg: unexpected bit count")
  1512  		}
  1513  	} else {
  1514  		count := dataSize / elemSize
  1515  
  1516  		// Piece together program trailer to run after prog that does:
  1517  		//	literal(0)
  1518  		//	repeat(1, elemSize-progSize-1) // zeros to fill element size
  1519  		//	repeat(elemSize, count-1) // repeat that element for count
  1520  		// This zero-pads the data remaining in the first element and then
  1521  		// repeats that first element to fill the array.
  1522  		var trailer [40]byte // 3 varints (max 10 each) + some bytes
  1523  		i := 0
  1524  		if n := elemSize/goarch.PtrSize - progSize/goarch.PtrSize; n > 0 {
  1525  			// literal(0)
  1526  			trailer[i] = 0x01
  1527  			i++
  1528  			trailer[i] = 0
  1529  			i++
  1530  			if n > 1 {
  1531  				// repeat(1, n-1)
  1532  				trailer[i] = 0x81
  1533  				i++
  1534  				n--
  1535  				for ; n >= 0x80; n >>= 7 {
  1536  					trailer[i] = byte(n | 0x80)
  1537  					i++
  1538  				}
  1539  				trailer[i] = byte(n)
  1540  				i++
  1541  			}
  1542  		}
  1543  		// repeat(elemSize/ptrSize, count-1)
  1544  		trailer[i] = 0x80
  1545  		i++
  1546  		n := elemSize / goarch.PtrSize
  1547  		for ; n >= 0x80; n >>= 7 {
  1548  			trailer[i] = byte(n | 0x80)
  1549  			i++
  1550  		}
  1551  		trailer[i] = byte(n)
  1552  		i++
  1553  		n = count - 1
  1554  		for ; n >= 0x80; n >>= 7 {
  1555  			trailer[i] = byte(n | 0x80)
  1556  			i++
  1557  		}
  1558  		trailer[i] = byte(n)
  1559  		i++
  1560  		trailer[i] = 0
  1561  		i++
  1562  
  1563  		runGCProg(prog, &trailer[0], h.bitp, 2)
  1564  
  1565  		// Even though we filled in the full array just now,
  1566  		// record that we only filled in up to the ptrdata of the
  1567  		// last element. This will cause the code below to
  1568  		// memclr the dead section of the final array element,
  1569  		// so that scanobject can stop early in the final element.
  1570  		totalBits = (elemSize*(count-1) + progSize) / goarch.PtrSize
  1571  	}
  1572  	endProg := unsafe.Pointer(addb(h.bitp, (totalBits+3)/4))
  1573  	endAlloc := unsafe.Pointer(addb(h.bitp, allocSize/goarch.PtrSize/wordsPerBitmapByte))
  1574  	memclrNoHeapPointers(endProg, uintptr(endAlloc)-uintptr(endProg))
  1575  }
  1576  
  1577  // progToPointerMask returns the 1-bit pointer mask output by the GC program prog.
  1578  // size the size of the region described by prog, in bytes.
  1579  // The resulting bitvector will have no more than size/goarch.PtrSize bits.
  1580  func progToPointerMask(prog *byte, size uintptr) bitvector {
  1581  	n := (size/goarch.PtrSize + 7) / 8
  1582  	x := (*[1 << 30]byte)(persistentalloc(n+1, 1, &memstats.buckhash_sys))[:n+1]
  1583  	x[len(x)-1] = 0xa1 // overflow check sentinel
  1584  	n = runGCProg(prog, nil, &x[0], 1)
  1585  	if x[len(x)-1] != 0xa1 {
  1586  		throw("progToPointerMask: overflow")
  1587  	}
  1588  	return bitvector{int32(n), &x[0]}
  1589  }
  1590  
  1591  // Packed GC pointer bitmaps, aka GC programs.
  1592  //
  1593  // For large types containing arrays, the type information has a
  1594  // natural repetition that can be encoded to save space in the
  1595  // binary and in the memory representation of the type information.
  1596  //
  1597  // The encoding is a simple Lempel-Ziv style bytecode machine
  1598  // with the following instructions:
  1599  //
  1600  //	00000000: stop
  1601  //	0nnnnnnn: emit n bits copied from the next (n+7)/8 bytes
  1602  //	10000000 n c: repeat the previous n bits c times; n, c are varints
  1603  //	1nnnnnnn c: repeat the previous n bits c times; c is a varint
  1604  
  1605  // runGCProg executes the GC program prog, and then trailer if non-nil,
  1606  // writing to dst with entries of the given size.
  1607  // If size == 1, dst is a 1-bit pointer mask laid out moving forward from dst.
  1608  // If size == 2, dst is the 2-bit heap bitmap, and writes move backward
  1609  // starting at dst (because the heap bitmap does). In this case, the caller guarantees
  1610  // that only whole bytes in dst need to be written.
  1611  //
  1612  // runGCProg returns the number of 1- or 2-bit entries written to memory.
  1613  func runGCProg(prog, trailer, dst *byte, size int) uintptr {
  1614  	dstStart := dst
  1615  
  1616  	// Bits waiting to be written to memory.
  1617  	var bits uintptr
  1618  	var nbits uintptr
  1619  
  1620  	p := prog
  1621  Run:
  1622  	for {
  1623  		// Flush accumulated full bytes.
  1624  		// The rest of the loop assumes that nbits <= 7.
  1625  		for ; nbits >= 8; nbits -= 8 {
  1626  			if size == 1 {
  1627  				*dst = uint8(bits)
  1628  				dst = add1(dst)
  1629  				bits >>= 8
  1630  			} else {
  1631  				v := bits&bitPointerAll | bitScanAll
  1632  				*dst = uint8(v)
  1633  				dst = add1(dst)
  1634  				bits >>= 4
  1635  				v = bits&bitPointerAll | bitScanAll
  1636  				*dst = uint8(v)
  1637  				dst = add1(dst)
  1638  				bits >>= 4
  1639  			}
  1640  		}
  1641  
  1642  		// Process one instruction.
  1643  		inst := uintptr(*p)
  1644  		p = add1(p)
  1645  		n := inst & 0x7F
  1646  		if inst&0x80 == 0 {
  1647  			// Literal bits; n == 0 means end of program.
  1648  			if n == 0 {
  1649  				// Program is over; continue in trailer if present.
  1650  				if trailer != nil {
  1651  					p = trailer
  1652  					trailer = nil
  1653  					continue
  1654  				}
  1655  				break Run
  1656  			}
  1657  			nbyte := n / 8
  1658  			for i := uintptr(0); i < nbyte; i++ {
  1659  				bits |= uintptr(*p) << nbits
  1660  				p = add1(p)
  1661  				if size == 1 {
  1662  					*dst = uint8(bits)
  1663  					dst = add1(dst)
  1664  					bits >>= 8
  1665  				} else {
  1666  					v := bits&0xf | bitScanAll
  1667  					*dst = uint8(v)
  1668  					dst = add1(dst)
  1669  					bits >>= 4
  1670  					v = bits&0xf | bitScanAll
  1671  					*dst = uint8(v)
  1672  					dst = add1(dst)
  1673  					bits >>= 4
  1674  				}
  1675  			}
  1676  			if n %= 8; n > 0 {
  1677  				bits |= uintptr(*p) << nbits
  1678  				p = add1(p)
  1679  				nbits += n
  1680  			}
  1681  			continue Run
  1682  		}
  1683  
  1684  		// Repeat. If n == 0, it is encoded in a varint in the next bytes.
  1685  		if n == 0 {
  1686  			for off := uint(0); ; off += 7 {
  1687  				x := uintptr(*p)
  1688  				p = add1(p)
  1689  				n |= (x & 0x7F) << off
  1690  				if x&0x80 == 0 {
  1691  					break
  1692  				}
  1693  			}
  1694  		}
  1695  
  1696  		// Count is encoded in a varint in the next bytes.
  1697  		c := uintptr(0)
  1698  		for off := uint(0); ; off += 7 {
  1699  			x := uintptr(*p)
  1700  			p = add1(p)
  1701  			c |= (x & 0x7F) << off
  1702  			if x&0x80 == 0 {
  1703  				break
  1704  			}
  1705  		}
  1706  		c *= n // now total number of bits to copy
  1707  
  1708  		// If the number of bits being repeated is small, load them
  1709  		// into a register and use that register for the entire loop
  1710  		// instead of repeatedly reading from memory.
  1711  		// Handling fewer than 8 bits here makes the general loop simpler.
  1712  		// The cutoff is goarch.PtrSize*8 - 7 to guarantee that when we add
  1713  		// the pattern to a bit buffer holding at most 7 bits (a partial byte)
  1714  		// it will not overflow.
  1715  		src := dst
  1716  		const maxBits = goarch.PtrSize*8 - 7
  1717  		if n <= maxBits {
  1718  			// Start with bits in output buffer.
  1719  			pattern := bits
  1720  			npattern := nbits
  1721  
  1722  			// If we need more bits, fetch them from memory.
  1723  			if size == 1 {
  1724  				src = subtract1(src)
  1725  				for npattern < n {
  1726  					pattern <<= 8
  1727  					pattern |= uintptr(*src)
  1728  					src = subtract1(src)
  1729  					npattern += 8
  1730  				}
  1731  			} else {
  1732  				src = subtract1(src)
  1733  				for npattern < n {
  1734  					pattern <<= 4
  1735  					pattern |= uintptr(*src) & 0xf
  1736  					src = subtract1(src)
  1737  					npattern += 4
  1738  				}
  1739  			}
  1740  
  1741  			// We started with the whole bit output buffer,
  1742  			// and then we loaded bits from whole bytes.
  1743  			// Either way, we might now have too many instead of too few.
  1744  			// Discard the extra.
  1745  			if npattern > n {
  1746  				pattern >>= npattern - n
  1747  				npattern = n
  1748  			}
  1749  
  1750  			// Replicate pattern to at most maxBits.
  1751  			if npattern == 1 {
  1752  				// One bit being repeated.
  1753  				// If the bit is 1, make the pattern all 1s.
  1754  				// If the bit is 0, the pattern is already all 0s,
  1755  				// but we can claim that the number of bits
  1756  				// in the word is equal to the number we need (c),
  1757  				// because right shift of bits will zero fill.
  1758  				if pattern == 1 {
  1759  					pattern = 1<<maxBits - 1
  1760  					npattern = maxBits
  1761  				} else {
  1762  					npattern = c
  1763  				}
  1764  			} else {
  1765  				b := pattern
  1766  				nb := npattern
  1767  				if nb+nb <= maxBits {
  1768  					// Double pattern until the whole uintptr is filled.
  1769  					for nb <= goarch.PtrSize*8 {
  1770  						b |= b << nb
  1771  						nb += nb
  1772  					}
  1773  					// Trim away incomplete copy of original pattern in high bits.
  1774  					// TODO(rsc): Replace with table lookup or loop on systems without divide?
  1775  					nb = maxBits / npattern * npattern
  1776  					b &= 1<<nb - 1
  1777  					pattern = b
  1778  					npattern = nb
  1779  				}
  1780  			}
  1781  
  1782  			// Add pattern to bit buffer and flush bit buffer, c/npattern times.
  1783  			// Since pattern contains >8 bits, there will be full bytes to flush
  1784  			// on each iteration.
  1785  			for ; c >= npattern; c -= npattern {
  1786  				bits |= pattern << nbits
  1787  				nbits += npattern
  1788  				if size == 1 {
  1789  					for nbits >= 8 {
  1790  						*dst = uint8(bits)
  1791  						dst = add1(dst)
  1792  						bits >>= 8
  1793  						nbits -= 8
  1794  					}
  1795  				} else {
  1796  					for nbits >= 4 {
  1797  						*dst = uint8(bits&0xf | bitScanAll)
  1798  						dst = add1(dst)
  1799  						bits >>= 4
  1800  						nbits -= 4
  1801  					}
  1802  				}
  1803  			}
  1804  
  1805  			// Add final fragment to bit buffer.
  1806  			if c > 0 {
  1807  				pattern &= 1<<c - 1
  1808  				bits |= pattern << nbits
  1809  				nbits += c
  1810  			}
  1811  			continue Run
  1812  		}
  1813  
  1814  		// Repeat; n too large to fit in a register.
  1815  		// Since nbits <= 7, we know the first few bytes of repeated data
  1816  		// are already written to memory.
  1817  		off := n - nbits // n > nbits because n > maxBits and nbits <= 7
  1818  		if size == 1 {
  1819  			// Leading src fragment.
  1820  			src = subtractb(src, (off+7)/8)
  1821  			if frag := off & 7; frag != 0 {
  1822  				bits |= uintptr(*src) >> (8 - frag) << nbits
  1823  				src = add1(src)
  1824  				nbits += frag
  1825  				c -= frag
  1826  			}
  1827  			// Main loop: load one byte, write another.
  1828  			// The bits are rotating through the bit buffer.
  1829  			for i := c / 8; i > 0; i-- {
  1830  				bits |= uintptr(*src) << nbits
  1831  				src = add1(src)
  1832  				*dst = uint8(bits)
  1833  				dst = add1(dst)
  1834  				bits >>= 8
  1835  			}
  1836  			// Final src fragment.
  1837  			if c %= 8; c > 0 {
  1838  				bits |= (uintptr(*src) & (1<<c - 1)) << nbits
  1839  				nbits += c
  1840  			}
  1841  		} else {
  1842  			// Leading src fragment.
  1843  			src = subtractb(src, (off+3)/4)
  1844  			if frag := off & 3; frag != 0 {
  1845  				bits |= (uintptr(*src) & 0xf) >> (4 - frag) << nbits
  1846  				src = add1(src)
  1847  				nbits += frag
  1848  				c -= frag
  1849  			}
  1850  			// Main loop: load one byte, write another.
  1851  			// The bits are rotating through the bit buffer.
  1852  			for i := c / 4; i > 0; i-- {
  1853  				bits |= (uintptr(*src) & 0xf) << nbits
  1854  				src = add1(src)
  1855  				*dst = uint8(bits&0xf | bitScanAll)
  1856  				dst = add1(dst)
  1857  				bits >>= 4
  1858  			}
  1859  			// Final src fragment.
  1860  			if c %= 4; c > 0 {
  1861  				bits |= (uintptr(*src) & (1<<c - 1)) << nbits
  1862  				nbits += c
  1863  			}
  1864  		}
  1865  	}
  1866  
  1867  	// Write any final bits out, using full-byte writes, even for the final byte.
  1868  	var totalBits uintptr
  1869  	if size == 1 {
  1870  		totalBits = (uintptr(unsafe.Pointer(dst))-uintptr(unsafe.Pointer(dstStart)))*8 + nbits
  1871  		nbits += -nbits & 7
  1872  		for ; nbits > 0; nbits -= 8 {
  1873  			*dst = uint8(bits)
  1874  			dst = add1(dst)
  1875  			bits >>= 8
  1876  		}
  1877  	} else {
  1878  		totalBits = (uintptr(unsafe.Pointer(dst))-uintptr(unsafe.Pointer(dstStart)))*4 + nbits
  1879  		nbits += -nbits & 3
  1880  		for ; nbits > 0; nbits -= 4 {
  1881  			v := bits&0xf | bitScanAll
  1882  			*dst = uint8(v)
  1883  			dst = add1(dst)
  1884  			bits >>= 4
  1885  		}
  1886  	}
  1887  	return totalBits
  1888  }
  1889  
  1890  // materializeGCProg allocates space for the (1-bit) pointer bitmask
  1891  // for an object of size ptrdata.  Then it fills that space with the
  1892  // pointer bitmask specified by the program prog.
  1893  // The bitmask starts at s.startAddr.
  1894  // The result must be deallocated with dematerializeGCProg.
  1895  func materializeGCProg(ptrdata uintptr, prog *byte) *mspan {
  1896  	// Each word of ptrdata needs one bit in the bitmap.
  1897  	bitmapBytes := divRoundUp(ptrdata, 8*goarch.PtrSize)
  1898  	// Compute the number of pages needed for bitmapBytes.
  1899  	pages := divRoundUp(bitmapBytes, pageSize)
  1900  	s := mheap_.allocManual(pages, spanAllocPtrScalarBits)
  1901  	runGCProg(addb(prog, 4), nil, (*byte)(unsafe.Pointer(s.startAddr)), 1)
  1902  	return s
  1903  }
  1904  func dematerializeGCProg(s *mspan) {
  1905  	mheap_.freeManual(s, spanAllocPtrScalarBits)
  1906  }
  1907  
  1908  func dumpGCProg(p *byte) {
  1909  	nptr := 0
  1910  	for {
  1911  		x := *p
  1912  		p = add1(p)
  1913  		if x == 0 {
  1914  			print("\t", nptr, " end\n")
  1915  			break
  1916  		}
  1917  		if x&0x80 == 0 {
  1918  			print("\t", nptr, " lit ", x, ":")
  1919  			n := int(x+7) / 8
  1920  			for i := 0; i < n; i++ {
  1921  				print(" ", hex(*p))
  1922  				p = add1(p)
  1923  			}
  1924  			print("\n")
  1925  			nptr += int(x)
  1926  		} else {
  1927  			nbit := int(x &^ 0x80)
  1928  			if nbit == 0 {
  1929  				for nb := uint(0); ; nb += 7 {
  1930  					x := *p
  1931  					p = add1(p)
  1932  					nbit |= int(x&0x7f) << nb
  1933  					if x&0x80 == 0 {
  1934  						break
  1935  					}
  1936  				}
  1937  			}
  1938  			count := 0
  1939  			for nb := uint(0); ; nb += 7 {
  1940  				x := *p
  1941  				p = add1(p)
  1942  				count |= int(x&0x7f) << nb
  1943  				if x&0x80 == 0 {
  1944  					break
  1945  				}
  1946  			}
  1947  			print("\t", nptr, " repeat ", nbit, " × ", count, "\n")
  1948  			nptr += nbit * count
  1949  		}
  1950  	}
  1951  }
  1952  
  1953  // Testing.
  1954  
  1955  func getgcmaskcb(frame *stkframe, ctxt unsafe.Pointer) bool {
  1956  	target := (*stkframe)(ctxt)
  1957  	if frame.sp <= target.sp && target.sp < frame.varp {
  1958  		*target = *frame
  1959  		return false
  1960  	}
  1961  	return true
  1962  }
  1963  
  1964  // gcbits returns the GC type info for x, for testing.
  1965  // The result is the bitmap entries (0 or 1), one entry per byte.
  1966  //
  1967  //go:linkname reflect_gcbits reflect.gcbits
  1968  func reflect_gcbits(x any) []byte {
  1969  	ret := getgcmask(x)
  1970  	typ := (*ptrtype)(unsafe.Pointer(efaceOf(&x)._type)).elem
  1971  	nptr := typ.ptrdata / goarch.PtrSize
  1972  	for uintptr(len(ret)) > nptr && ret[len(ret)-1] == 0 {
  1973  		ret = ret[:len(ret)-1]
  1974  	}
  1975  	return ret
  1976  }
  1977  
  1978  // Returns GC type info for the pointer stored in ep for testing.
  1979  // If ep points to the stack, only static live information will be returned
  1980  // (i.e. not for objects which are only dynamically live stack objects).
  1981  func getgcmask(ep any) (mask []byte) {
  1982  	e := *efaceOf(&ep)
  1983  	p := e.data
  1984  	t := e._type
  1985  	// data or bss
  1986  	for _, datap := range activeModules() {
  1987  		// data
  1988  		if datap.data <= uintptr(p) && uintptr(p) < datap.edata {
  1989  			bitmap := datap.gcdatamask.bytedata
  1990  			n := (*ptrtype)(unsafe.Pointer(t)).elem.size
  1991  			mask = make([]byte, n/goarch.PtrSize)
  1992  			for i := uintptr(0); i < n; i += goarch.PtrSize {
  1993  				off := (uintptr(p) + i - datap.data) / goarch.PtrSize
  1994  				mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
  1995  			}
  1996  			return
  1997  		}
  1998  
  1999  		// bss
  2000  		if datap.bss <= uintptr(p) && uintptr(p) < datap.ebss {
  2001  			bitmap := datap.gcbssmask.bytedata
  2002  			n := (*ptrtype)(unsafe.Pointer(t)).elem.size
  2003  			mask = make([]byte, n/goarch.PtrSize)
  2004  			for i := uintptr(0); i < n; i += goarch.PtrSize {
  2005  				off := (uintptr(p) + i - datap.bss) / goarch.PtrSize
  2006  				mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
  2007  			}
  2008  			return
  2009  		}
  2010  	}
  2011  
  2012  	// heap
  2013  	if base, s, _ := findObject(uintptr(p), 0, 0); base != 0 {
  2014  		hbits := heapBitsForAddr(base)
  2015  		n := s.elemsize
  2016  		mask = make([]byte, n/goarch.PtrSize)
  2017  		for i := uintptr(0); i < n; i += goarch.PtrSize {
  2018  			if hbits.isPointer() {
  2019  				mask[i/goarch.PtrSize] = 1
  2020  			}
  2021  			if !hbits.morePointers() {
  2022  				mask = mask[:i/goarch.PtrSize]
  2023  				break
  2024  			}
  2025  			hbits = hbits.next()
  2026  		}
  2027  		return
  2028  	}
  2029  
  2030  	// stack
  2031  	if _g_ := getg(); _g_.m.curg.stack.lo <= uintptr(p) && uintptr(p) < _g_.m.curg.stack.hi {
  2032  		var frame stkframe
  2033  		frame.sp = uintptr(p)
  2034  		_g_ := getg()
  2035  		gentraceback(_g_.m.curg.sched.pc, _g_.m.curg.sched.sp, 0, _g_.m.curg, 0, nil, 1000, getgcmaskcb, noescape(unsafe.Pointer(&frame)), 0)
  2036  		if frame.fn.valid() {
  2037  			locals, _, _ := getStackMap(&frame, nil, false)
  2038  			if locals.n == 0 {
  2039  				return
  2040  			}
  2041  			size := uintptr(locals.n) * goarch.PtrSize
  2042  			n := (*ptrtype)(unsafe.Pointer(t)).elem.size
  2043  			mask = make([]byte, n/goarch.PtrSize)
  2044  			for i := uintptr(0); i < n; i += goarch.PtrSize {
  2045  				off := (uintptr(p) + i - frame.varp + size) / goarch.PtrSize
  2046  				mask[i/goarch.PtrSize] = locals.ptrbit(off)
  2047  			}
  2048  		}
  2049  		return
  2050  	}
  2051  
  2052  	// otherwise, not something the GC knows about.
  2053  	// possibly read-only data, like malloc(0).
  2054  	// must not have pointers
  2055  	return
  2056  }
  2057  

View as plain text