]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mbitmap.go
runtime: redo heap bitmap
[gostls13.git] / src / runtime / mbitmap.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // 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 1 bit for each pointer-sized word in the heap,
18 // recording whether a pointer is stored in that word or not. This bitmap
19 // is stored in the heapArena metadata backing each heap arena.
20 // That is, if ha is the heapArena for the arena starting at "start",
21 // then ha.bitmap[0] holds the 64 bits for the 64 words "start"
22 // through start+63*ptrSize, ha.bitmap[1] holds the entries for
23 // start+64*ptrSize through start+127*ptrSize, and so on.
24 // Bits correspond to words in little-endian order. ha.bitmap[0]&1 represents
25 // the word at "start", ha.bitmap[0]>>1&1 represents the word at start+8, etc.
26 // (For 32-bit platforms, s/64/32/.)
27 //
28 // We also keep a noMorePtrs bitmap which allows us to stop scanning
29 // the heap bitmap early in certain situations. If ha.noMorePtrs[i]>>j&1
30 // is 1, then the object containing the last word described by ha.bitmap[8*i+j]
31 // has no more pointers beyond those described by ha.bitmap[8*i+j].
32 // If ha.noMorePtrs[i]>>j&1 is set, the entries in ha.bitmap[8*i+j+1] and
33 // beyond must all be zero until the start of the next object.
34 //
35 // The bitmap for noscan spans is not maintained (can be junk). Code must
36 // ensure that an object is scannable before consulting its bitmap by
37 // checking either the noscan bit in the span or by consulting its
38 // type's information.
39 //
40 // The bitmap for unallocated objects is also not maintained.
41
42 package runtime
43
44 import (
45         "internal/goarch"
46         "runtime/internal/atomic"
47         "runtime/internal/sys"
48         "unsafe"
49 )
50
51 // addb returns the byte pointer p+n.
52 //
53 //go:nowritebarrier
54 //go:nosplit
55 func addb(p *byte, n uintptr) *byte {
56         // Note: wrote out full expression instead of calling add(p, n)
57         // to reduce the number of temporaries generated by the
58         // compiler for this trivial expression during inlining.
59         return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n))
60 }
61
62 // subtractb returns the byte pointer p-n.
63 //
64 //go:nowritebarrier
65 //go:nosplit
66 func subtractb(p *byte, n uintptr) *byte {
67         // Note: wrote out full expression instead of calling add(p, -n)
68         // to reduce the number of temporaries generated by the
69         // compiler for this trivial expression during inlining.
70         return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - n))
71 }
72
73 // add1 returns the byte pointer p+1.
74 //
75 //go:nowritebarrier
76 //go:nosplit
77 func add1(p *byte) *byte {
78         // Note: wrote out full expression instead of calling addb(p, 1)
79         // to reduce the number of temporaries generated by the
80         // compiler for this trivial expression during inlining.
81         return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1))
82 }
83
84 // subtract1 returns the byte pointer p-1.
85 //
86 // nosplit because it is used during write barriers and must not be preempted.
87 //
88 //go:nowritebarrier
89 //go:nosplit
90 func subtract1(p *byte) *byte {
91         // Note: wrote out full expression instead of calling subtractb(p, 1)
92         // to reduce the number of temporaries generated by the
93         // compiler for this trivial expression during inlining.
94         return (*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) - 1))
95 }
96
97 // markBits provides access to the mark bit for an object in the heap.
98 // bytep points to the byte holding the mark bit.
99 // mask is a byte with a single bit set that can be &ed with *bytep
100 // to see if the bit has been set.
101 // *m.byte&m.mask != 0 indicates the mark bit is set.
102 // index can be used along with span information to generate
103 // the address of the object in the heap.
104 // We maintain one set of mark bits for allocation and one for
105 // marking purposes.
106 type markBits struct {
107         bytep *uint8
108         mask  uint8
109         index uintptr
110 }
111
112 //go:nosplit
113 func (s *mspan) allocBitsForIndex(allocBitIndex uintptr) markBits {
114         bytep, mask := s.allocBits.bitp(allocBitIndex)
115         return markBits{bytep, mask, allocBitIndex}
116 }
117
118 // refillAllocCache takes 8 bytes s.allocBits starting at whichByte
119 // and negates them so that ctz (count trailing zeros) instructions
120 // can be used. It then places these 8 bytes into the cached 64 bit
121 // s.allocCache.
122 func (s *mspan) refillAllocCache(whichByte uintptr) {
123         bytes := (*[8]uint8)(unsafe.Pointer(s.allocBits.bytep(whichByte)))
124         aCache := uint64(0)
125         aCache |= uint64(bytes[0])
126         aCache |= uint64(bytes[1]) << (1 * 8)
127         aCache |= uint64(bytes[2]) << (2 * 8)
128         aCache |= uint64(bytes[3]) << (3 * 8)
129         aCache |= uint64(bytes[4]) << (4 * 8)
130         aCache |= uint64(bytes[5]) << (5 * 8)
131         aCache |= uint64(bytes[6]) << (6 * 8)
132         aCache |= uint64(bytes[7]) << (7 * 8)
133         s.allocCache = ^aCache
134 }
135
136 // nextFreeIndex returns the index of the next free object in s at
137 // or after s.freeindex.
138 // There are hardware instructions that can be used to make this
139 // faster if profiling warrants it.
140 func (s *mspan) nextFreeIndex() uintptr {
141         sfreeindex := s.freeindex
142         snelems := s.nelems
143         if sfreeindex == snelems {
144                 return sfreeindex
145         }
146         if sfreeindex > snelems {
147                 throw("s.freeindex > s.nelems")
148         }
149
150         aCache := s.allocCache
151
152         bitIndex := sys.Ctz64(aCache)
153         for bitIndex == 64 {
154                 // Move index to start of next cached bits.
155                 sfreeindex = (sfreeindex + 64) &^ (64 - 1)
156                 if sfreeindex >= snelems {
157                         s.freeindex = snelems
158                         return snelems
159                 }
160                 whichByte := sfreeindex / 8
161                 // Refill s.allocCache with the next 64 alloc bits.
162                 s.refillAllocCache(whichByte)
163                 aCache = s.allocCache
164                 bitIndex = sys.Ctz64(aCache)
165                 // nothing available in cached bits
166                 // grab the next 8 bytes and try again.
167         }
168         result := sfreeindex + uintptr(bitIndex)
169         if result >= snelems {
170                 s.freeindex = snelems
171                 return snelems
172         }
173
174         s.allocCache >>= uint(bitIndex + 1)
175         sfreeindex = result + 1
176
177         if sfreeindex%64 == 0 && sfreeindex != snelems {
178                 // We just incremented s.freeindex so it isn't 0.
179                 // As each 1 in s.allocCache was encountered and used for allocation
180                 // it was shifted away. At this point s.allocCache contains all 0s.
181                 // Refill s.allocCache so that it corresponds
182                 // to the bits at s.allocBits starting at s.freeindex.
183                 whichByte := sfreeindex / 8
184                 s.refillAllocCache(whichByte)
185         }
186         s.freeindex = sfreeindex
187         return result
188 }
189
190 // isFree reports whether the index'th object in s is unallocated.
191 //
192 // The caller must ensure s.state is mSpanInUse, and there must have
193 // been no preemption points since ensuring this (which could allow a
194 // GC transition, which would allow the state to change).
195 func (s *mspan) isFree(index uintptr) bool {
196         if index < s.freeindex {
197                 return false
198         }
199         bytep, mask := s.allocBits.bitp(index)
200         return *bytep&mask == 0
201 }
202
203 // divideByElemSize returns n/s.elemsize.
204 // n must be within [0, s.npages*_PageSize),
205 // or may be exactly s.npages*_PageSize
206 // if s.elemsize is from sizeclasses.go.
207 func (s *mspan) divideByElemSize(n uintptr) uintptr {
208         const doubleCheck = false
209
210         // See explanation in mksizeclasses.go's computeDivMagic.
211         q := uintptr((uint64(n) * uint64(s.divMul)) >> 32)
212
213         if doubleCheck && q != n/s.elemsize {
214                 println(n, "/", s.elemsize, "should be", n/s.elemsize, "but got", q)
215                 throw("bad magic division")
216         }
217         return q
218 }
219
220 func (s *mspan) objIndex(p uintptr) uintptr {
221         return s.divideByElemSize(p - s.base())
222 }
223
224 func markBitsForAddr(p uintptr) markBits {
225         s := spanOf(p)
226         objIndex := s.objIndex(p)
227         return s.markBitsForIndex(objIndex)
228 }
229
230 func (s *mspan) markBitsForIndex(objIndex uintptr) markBits {
231         bytep, mask := s.gcmarkBits.bitp(objIndex)
232         return markBits{bytep, mask, objIndex}
233 }
234
235 func (s *mspan) markBitsForBase() markBits {
236         return markBits{(*uint8)(s.gcmarkBits), uint8(1), 0}
237 }
238
239 // isMarked reports whether mark bit m is set.
240 func (m markBits) isMarked() bool {
241         return *m.bytep&m.mask != 0
242 }
243
244 // setMarked sets the marked bit in the markbits, atomically.
245 func (m markBits) setMarked() {
246         // Might be racing with other updates, so use atomic update always.
247         // We used to be clever here and use a non-atomic update in certain
248         // cases, but it's not worth the risk.
249         atomic.Or8(m.bytep, m.mask)
250 }
251
252 // setMarkedNonAtomic sets the marked bit in the markbits, non-atomically.
253 func (m markBits) setMarkedNonAtomic() {
254         *m.bytep |= m.mask
255 }
256
257 // clearMarked clears the marked bit in the markbits, atomically.
258 func (m markBits) clearMarked() {
259         // Might be racing with other updates, so use atomic update always.
260         // We used to be clever here and use a non-atomic update in certain
261         // cases, but it's not worth the risk.
262         atomic.And8(m.bytep, ^m.mask)
263 }
264
265 // markBitsForSpan returns the markBits for the span base address base.
266 func markBitsForSpan(base uintptr) (mbits markBits) {
267         mbits = markBitsForAddr(base)
268         if mbits.mask != 1 {
269                 throw("markBitsForSpan: unaligned start")
270         }
271         return mbits
272 }
273
274 // advance advances the markBits to the next object in the span.
275 func (m *markBits) advance() {
276         if m.mask == 1<<7 {
277                 m.bytep = (*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(m.bytep)) + 1))
278                 m.mask = 1
279         } else {
280                 m.mask = m.mask << 1
281         }
282         m.index++
283 }
284
285 // clobberdeadPtr is a special value that is used by the compiler to
286 // clobber dead stack slots, when -clobberdead flag is set.
287 const clobberdeadPtr = uintptr(0xdeaddead | 0xdeaddead<<((^uintptr(0)>>63)*32))
288
289 // badPointer throws bad pointer in heap panic.
290 func badPointer(s *mspan, p, refBase, refOff uintptr) {
291         // Typically this indicates an incorrect use
292         // of unsafe or cgo to store a bad pointer in
293         // the Go heap. It may also indicate a runtime
294         // bug.
295         //
296         // TODO(austin): We could be more aggressive
297         // and detect pointers to unallocated objects
298         // in allocated spans.
299         printlock()
300         print("runtime: pointer ", hex(p))
301         if s != nil {
302                 state := s.state.get()
303                 if state != mSpanInUse {
304                         print(" to unallocated span")
305                 } else {
306                         print(" to unused region of span")
307                 }
308                 print(" span.base()=", hex(s.base()), " span.limit=", hex(s.limit), " span.state=", state)
309         }
310         print("\n")
311         if refBase != 0 {
312                 print("runtime: found in object at *(", hex(refBase), "+", hex(refOff), ")\n")
313                 gcDumpObject("object", refBase, refOff)
314         }
315         getg().m.traceback = 2
316         throw("found bad pointer in Go heap (incorrect use of unsafe or cgo?)")
317 }
318
319 // findObject returns the base address for the heap object containing
320 // the address p, the object's span, and the index of the object in s.
321 // If p does not point into a heap object, it returns base == 0.
322 //
323 // If p points is an invalid heap pointer and debug.invalidptr != 0,
324 // findObject panics.
325 //
326 // refBase and refOff optionally give the base address of the object
327 // in which the pointer p was found and the byte offset at which it
328 // was found. These are used for error reporting.
329 //
330 // It is nosplit so it is safe for p to be a pointer to the current goroutine's stack.
331 // Since p is a uintptr, it would not be adjusted if the stack were to move.
332 //
333 //go:nosplit
334 func findObject(p, refBase, refOff uintptr) (base uintptr, s *mspan, objIndex uintptr) {
335         s = spanOf(p)
336         // If s is nil, the virtual address has never been part of the heap.
337         // This pointer may be to some mmap'd region, so we allow it.
338         if s == nil {
339                 if (GOARCH == "amd64" || GOARCH == "arm64") && p == clobberdeadPtr && debug.invalidptr != 0 {
340                         // Crash if clobberdeadPtr is seen. Only on AMD64 and ARM64 for now,
341                         // as they are the only platform where compiler's clobberdead mode is
342                         // implemented. On these platforms clobberdeadPtr cannot be a valid address.
343                         badPointer(s, p, refBase, refOff)
344                 }
345                 return
346         }
347         // If p is a bad pointer, it may not be in s's bounds.
348         //
349         // Check s.state to synchronize with span initialization
350         // before checking other fields. See also spanOfHeap.
351         if state := s.state.get(); state != mSpanInUse || p < s.base() || p >= s.limit {
352                 // Pointers into stacks are also ok, the runtime manages these explicitly.
353                 if state == mSpanManual {
354                         return
355                 }
356                 // The following ensures that we are rigorous about what data
357                 // structures hold valid pointers.
358                 if debug.invalidptr != 0 {
359                         badPointer(s, p, refBase, refOff)
360                 }
361                 return
362         }
363
364         objIndex = s.objIndex(p)
365         base = s.base() + objIndex*s.elemsize
366         return
367 }
368
369 // verifyNotInHeapPtr reports whether converting the not-in-heap pointer into a unsafe.Pointer is ok.
370 //
371 //go:linkname reflect_verifyNotInHeapPtr reflect.verifyNotInHeapPtr
372 func reflect_verifyNotInHeapPtr(p uintptr) bool {
373         // Conversion to a pointer is ok as long as findObject above does not call badPointer.
374         // Since we're already promised that p doesn't point into the heap, just disallow heap
375         // pointers and the special clobbered pointer.
376         return spanOf(p) == nil && p != clobberdeadPtr
377 }
378
379 const ptrBits = 8 * goarch.PtrSize
380
381 // heapBits provides access to the bitmap bits for a single heap word.
382 // The methods on heapBits take value receivers so that the compiler
383 // can more easily inline calls to those methods and registerize the
384 // struct fields independently.
385 type heapBits struct {
386         // heapBits will report on pointers in the range [addr,addr+size).
387         // The low bit of mask contains the pointerness of the word at addr
388         // (assuming valid>0).
389         addr, size uintptr
390
391         // The next few pointer bits representing words starting at addr.
392         // Those bits already returned by next() are zeroed.
393         mask uintptr
394         // Number of bits in mask that are valid. mask is always less than 1<<valid.
395         valid uintptr
396 }
397
398 // heapBitsForAddr returns the heapBits for the address addr.
399 // The caller must ensure [addr,addr+size) is in an allocated span.
400 // In particular, be careful not to point past the end of an object.
401 //
402 // nosplit because it is used during write barriers and must not be preempted.
403 //
404 //go:nosplit
405 func heapBitsForAddr(addr, size uintptr) heapBits {
406         // Find arena
407         ai := arenaIndex(addr)
408         ha := mheap_.arenas[ai.l1()][ai.l2()]
409
410         // Word index in arena.
411         word := addr / goarch.PtrSize % heapArenaWords
412
413         // Word index and bit offset in bitmap array.
414         idx := word / ptrBits
415         off := word % ptrBits
416
417         // Grab relevant bits of bitmap.
418         mask := ha.bitmap[idx] >> off
419         valid := ptrBits - off
420
421         // Process depending on where the object ends.
422         nptr := size / goarch.PtrSize
423         if nptr < valid {
424                 // Bits for this object end before the end of this bitmap word.
425                 // Squash bits for the following objects.
426                 mask &= 1<<(nptr&(ptrBits-1)) - 1
427                 valid = nptr
428         } else if nptr == valid {
429                 // Bits for this object end at exactly the end of this bitmap word.
430                 // All good.
431         } else {
432                 // Bits for this object extend into the next bitmap word. See if there
433                 // may be any pointers recorded there.
434                 if uintptr(ha.noMorePtrs[idx/8])>>(idx%8)&1 != 0 {
435                         // No more pointers in this object after this bitmap word.
436                         // Update size so we know not to look there.
437                         size = valid * goarch.PtrSize
438                 }
439         }
440
441         return heapBits{addr: addr, size: size, mask: mask, valid: valid}
442 }
443
444 // Returns the (absolute) address of the next known pointer and
445 // a heapBits iterator representing any remaining pointers.
446 // If there are no more pointers, returns address 0.
447 // Note that next does not modify h. The caller must record the result.
448 //
449 // nosplit because it is used during write barriers and must not be preempted.
450 //
451 //go:nosplit
452 func (h heapBits) next() (heapBits, uintptr) {
453         for {
454                 if h.mask != 0 {
455                         var i int
456                         if goarch.PtrSize == 8 {
457                                 i = sys.Ctz64(uint64(h.mask))
458                         } else {
459                                 i = sys.Ctz32(uint32(h.mask))
460                         }
461                         h.mask ^= uintptr(1) << (i & (ptrBits - 1))
462                         return h, h.addr + uintptr(i)*goarch.PtrSize
463                 }
464
465                 // Skip words that we've already processed.
466                 h.addr += h.valid * goarch.PtrSize
467                 h.size -= h.valid * goarch.PtrSize
468                 if h.size == 0 {
469                         return h, 0 // no more pointers
470                 }
471
472                 // Grab more bits and try again.
473                 h = heapBitsForAddr(h.addr, h.size)
474         }
475 }
476
477 // nextFast is like next, but can return 0 even when there are more pointers
478 // to be found. Callers should call next if nextFast returns 0 as its second
479 // return value.
480 //     if addr, h = h.nextFast(); addr == 0 {
481 //         if addr, h = h.next(); addr == 0 {
482 //             ... no more pointers ...
483 //         }
484 //     }
485 //     ... process pointer at addr ...
486 // nextFast is designed to be inlineable.
487 //
488 //go:nosplit
489 func (h heapBits) nextFast() (heapBits, uintptr) {
490         // TESTQ/JEQ
491         if h.mask == 0 {
492                 return h, 0
493         }
494         // BSFQ
495         var i int
496         if goarch.PtrSize == 8 {
497                 i = sys.Ctz64(uint64(h.mask))
498         } else {
499                 i = sys.Ctz32(uint32(h.mask))
500         }
501         // BTCQ
502         h.mask ^= uintptr(1) << (i & (ptrBits - 1))
503         // LEAQ (XX)(XX*8)
504         return h, h.addr + uintptr(i)*goarch.PtrSize
505 }
506
507 // bulkBarrierPreWrite executes a write barrier
508 // for every pointer slot in the memory range [src, src+size),
509 // using pointer/scalar information from [dst, dst+size).
510 // This executes the write barriers necessary before a memmove.
511 // src, dst, and size must be pointer-aligned.
512 // The range [dst, dst+size) must lie within a single object.
513 // It does not perform the actual writes.
514 //
515 // As a special case, src == 0 indicates that this is being used for a
516 // memclr. bulkBarrierPreWrite will pass 0 for the src of each write
517 // barrier.
518 //
519 // Callers should call bulkBarrierPreWrite immediately before
520 // calling memmove(dst, src, size). This function is marked nosplit
521 // to avoid being preempted; the GC must not stop the goroutine
522 // between the memmove and the execution of the barriers.
523 // The caller is also responsible for cgo pointer checks if this
524 // may be writing Go pointers into non-Go memory.
525 //
526 // The pointer bitmap is not maintained for allocations containing
527 // no pointers at all; any caller of bulkBarrierPreWrite must first
528 // make sure the underlying allocation contains pointers, usually
529 // by checking typ.ptrdata.
530 //
531 // Callers must perform cgo checks if writeBarrier.cgo.
532 //
533 //go:nosplit
534 func bulkBarrierPreWrite(dst, src, size uintptr) {
535         if (dst|src|size)&(goarch.PtrSize-1) != 0 {
536                 throw("bulkBarrierPreWrite: unaligned arguments")
537         }
538         if !writeBarrier.needed {
539                 return
540         }
541         if s := spanOf(dst); s == nil {
542                 // If dst is a global, use the data or BSS bitmaps to
543                 // execute write barriers.
544                 for _, datap := range activeModules() {
545                         if datap.data <= dst && dst < datap.edata {
546                                 bulkBarrierBitmap(dst, src, size, dst-datap.data, datap.gcdatamask.bytedata)
547                                 return
548                         }
549                 }
550                 for _, datap := range activeModules() {
551                         if datap.bss <= dst && dst < datap.ebss {
552                                 bulkBarrierBitmap(dst, src, size, dst-datap.bss, datap.gcbssmask.bytedata)
553                                 return
554                         }
555                 }
556                 return
557         } else if s.state.get() != mSpanInUse || dst < s.base() || s.limit <= dst {
558                 // dst was heap memory at some point, but isn't now.
559                 // It can't be a global. It must be either our stack,
560                 // or in the case of direct channel sends, it could be
561                 // another stack. Either way, no need for barriers.
562                 // This will also catch if dst is in a freed span,
563                 // though that should never have.
564                 return
565         }
566
567         buf := &getg().m.p.ptr().wbBuf
568         h := heapBitsForAddr(dst, size)
569         if src == 0 {
570                 for {
571                         var addr uintptr
572                         if h, addr = h.next(); addr == 0 {
573                                 break
574                         }
575                         dstx := (*uintptr)(unsafe.Pointer(addr))
576                         if !buf.putFast(*dstx, 0) {
577                                 wbBufFlush(nil, 0)
578                         }
579                 }
580         } else {
581                 for {
582                         var addr uintptr
583                         if h, addr = h.next(); addr == 0 {
584                                 break
585                         }
586                         dstx := (*uintptr)(unsafe.Pointer(addr))
587                         srcx := (*uintptr)(unsafe.Pointer(src + (addr - dst)))
588                         if !buf.putFast(*dstx, *srcx) {
589                                 wbBufFlush(nil, 0)
590                         }
591                 }
592         }
593 }
594
595 // bulkBarrierPreWriteSrcOnly is like bulkBarrierPreWrite but
596 // does not execute write barriers for [dst, dst+size).
597 //
598 // In addition to the requirements of bulkBarrierPreWrite
599 // callers need to ensure [dst, dst+size) is zeroed.
600 //
601 // This is used for special cases where e.g. dst was just
602 // created and zeroed with malloc.
603 //
604 //go:nosplit
605 func bulkBarrierPreWriteSrcOnly(dst, src, size uintptr) {
606         if (dst|src|size)&(goarch.PtrSize-1) != 0 {
607                 throw("bulkBarrierPreWrite: unaligned arguments")
608         }
609         if !writeBarrier.needed {
610                 return
611         }
612         buf := &getg().m.p.ptr().wbBuf
613         h := heapBitsForAddr(dst, size)
614         for {
615                 var addr uintptr
616                 if h, addr = h.next(); addr == 0 {
617                         break
618                 }
619                 srcx := (*uintptr)(unsafe.Pointer(addr - dst + src))
620                 if !buf.putFast(0, *srcx) {
621                         wbBufFlush(nil, 0)
622                 }
623         }
624 }
625
626 // bulkBarrierBitmap executes write barriers for copying from [src,
627 // src+size) to [dst, dst+size) using a 1-bit pointer bitmap. src is
628 // assumed to start maskOffset bytes into the data covered by the
629 // bitmap in bits (which may not be a multiple of 8).
630 //
631 // This is used by bulkBarrierPreWrite for writes to data and BSS.
632 //
633 //go:nosplit
634 func bulkBarrierBitmap(dst, src, size, maskOffset uintptr, bits *uint8) {
635         word := maskOffset / goarch.PtrSize
636         bits = addb(bits, word/8)
637         mask := uint8(1) << (word % 8)
638
639         buf := &getg().m.p.ptr().wbBuf
640         for i := uintptr(0); i < size; i += goarch.PtrSize {
641                 if mask == 0 {
642                         bits = addb(bits, 1)
643                         if *bits == 0 {
644                                 // Skip 8 words.
645                                 i += 7 * goarch.PtrSize
646                                 continue
647                         }
648                         mask = 1
649                 }
650                 if *bits&mask != 0 {
651                         dstx := (*uintptr)(unsafe.Pointer(dst + i))
652                         if src == 0 {
653                                 if !buf.putFast(*dstx, 0) {
654                                         wbBufFlush(nil, 0)
655                                 }
656                         } else {
657                                 srcx := (*uintptr)(unsafe.Pointer(src + i))
658                                 if !buf.putFast(*dstx, *srcx) {
659                                         wbBufFlush(nil, 0)
660                                 }
661                         }
662                 }
663                 mask <<= 1
664         }
665 }
666
667 // typeBitsBulkBarrier executes a write barrier for every
668 // pointer that would be copied from [src, src+size) to [dst,
669 // dst+size) by a memmove using the type bitmap to locate those
670 // pointer slots.
671 //
672 // The type typ must correspond exactly to [src, src+size) and [dst, dst+size).
673 // dst, src, and size must be pointer-aligned.
674 // The type typ must have a plain bitmap, not a GC program.
675 // The only use of this function is in channel sends, and the
676 // 64 kB channel element limit takes care of this for us.
677 //
678 // Must not be preempted because it typically runs right before memmove,
679 // and the GC must observe them as an atomic action.
680 //
681 // Callers must perform cgo checks if writeBarrier.cgo.
682 //
683 //go:nosplit
684 func typeBitsBulkBarrier(typ *_type, dst, src, size uintptr) {
685         if typ == nil {
686                 throw("runtime: typeBitsBulkBarrier without type")
687         }
688         if typ.size != size {
689                 println("runtime: typeBitsBulkBarrier with type ", typ.string(), " of size ", typ.size, " but memory size", size)
690                 throw("runtime: invalid typeBitsBulkBarrier")
691         }
692         if typ.kind&kindGCProg != 0 {
693                 println("runtime: typeBitsBulkBarrier with type ", typ.string(), " with GC prog")
694                 throw("runtime: invalid typeBitsBulkBarrier")
695         }
696         if !writeBarrier.needed {
697                 return
698         }
699         ptrmask := typ.gcdata
700         buf := &getg().m.p.ptr().wbBuf
701         var bits uint32
702         for i := uintptr(0); i < typ.ptrdata; i += goarch.PtrSize {
703                 if i&(goarch.PtrSize*8-1) == 0 {
704                         bits = uint32(*ptrmask)
705                         ptrmask = addb(ptrmask, 1)
706                 } else {
707                         bits = bits >> 1
708                 }
709                 if bits&1 != 0 {
710                         dstx := (*uintptr)(unsafe.Pointer(dst + i))
711                         srcx := (*uintptr)(unsafe.Pointer(src + i))
712                         if !buf.putFast(*dstx, *srcx) {
713                                 wbBufFlush(nil, 0)
714                         }
715                 }
716         }
717 }
718
719 // initHeapBits initializes the heap bitmap for a span.
720 // If this is a span of single pointer allocations, it initializes all
721 // words to pointer.
722 func (s *mspan) initHeapBits() {
723         isPtrs := goarch.PtrSize == 8 && s.elemsize == goarch.PtrSize
724         if !isPtrs {
725                 return // nothing to do
726         }
727         h := writeHeapBitsForAddr(s.base())
728         size := s.npages * pageSize
729         nptrs := size / goarch.PtrSize
730         for i := uintptr(0); i < nptrs; i += ptrBits {
731                 h = h.write(^uintptr(0), ptrBits)
732         }
733         h.flush(s.base(), size)
734 }
735
736 // countAlloc returns the number of objects allocated in span s by
737 // scanning the allocation bitmap.
738 func (s *mspan) countAlloc() int {
739         count := 0
740         bytes := divRoundUp(s.nelems, 8)
741         // Iterate over each 8-byte chunk and count allocations
742         // with an intrinsic. Note that newMarkBits guarantees that
743         // gcmarkBits will be 8-byte aligned, so we don't have to
744         // worry about edge cases, irrelevant bits will simply be zero.
745         for i := uintptr(0); i < bytes; i += 8 {
746                 // Extract 64 bits from the byte pointer and get a OnesCount.
747                 // Note that the unsafe cast here doesn't preserve endianness,
748                 // but that's OK. We only care about how many bits are 1, not
749                 // about the order we discover them in.
750                 mrkBits := *(*uint64)(unsafe.Pointer(s.gcmarkBits.bytep(i)))
751                 count += sys.OnesCount64(mrkBits)
752         }
753         return count
754 }
755
756 type writeHeapBits struct {
757         addr  uintptr // address that the low bit of mask represents the pointer state of.
758         mask  uintptr // some pointer bits starting at the address addr.
759         valid uintptr // number of bits in buf that are valid (including low)
760         low   uintptr // number of low-order bits to not overwrite
761 }
762
763 func writeHeapBitsForAddr(addr uintptr) (h writeHeapBits) {
764         // We start writing bits maybe in the middle of a heap bitmap word.
765         // Remember how many bits into the word we started, so we can be sure
766         // not to overwrite the previous bits.
767         h.low = addr / goarch.PtrSize % ptrBits
768
769         // round down to heap word that starts the bitmap word.
770         h.addr = addr - h.low*goarch.PtrSize
771
772         // We don't have any bits yet.
773         h.mask = 0
774         h.valid = h.low
775
776         return
777 }
778
779 // write appends the pointerness of the next valid pointer slots
780 // using the low valid bits of bits. 1=pointer, 0=scalar.
781 func (h writeHeapBits) write(bits, valid uintptr) writeHeapBits {
782         if h.valid+valid <= ptrBits {
783                 // Fast path - just accumulate the bits.
784                 h.mask |= bits << h.valid
785                 h.valid += valid
786                 return h
787         }
788         // Too many bits to fit in this word. Write the current word
789         // out and move on to the next word.
790
791         data := h.mask | bits<<h.valid       // mask for this word
792         h.mask = bits >> (ptrBits - h.valid) // leftover for next word
793         h.valid += valid - ptrBits           // have h.valid+valid bits, writing ptrBits of them
794
795         // Flush mask to the memory bitmap.
796         // TODO: figure out how to cache arena lookup.
797         ai := arenaIndex(h.addr)
798         ha := mheap_.arenas[ai.l1()][ai.l2()]
799         idx := h.addr / (ptrBits * goarch.PtrSize) % heapArenaBitmapWords
800         m := uintptr(1)<<h.low - 1
801         ha.bitmap[idx] = ha.bitmap[idx]&m | data
802         // Note: no synchronization required for this write because
803         // the allocator has exclusive access to the page, and the bitmap
804         // entries are all for a single page. Also, visibility of these
805         // writes is guaranteed by the publication barrier in mallocgc.
806
807         // Clear noMorePtrs bit, since we're going to be writing bits
808         // into the following word.
809         ha.noMorePtrs[idx/8] &^= uint8(1) << (idx % 8)
810         // Note: same as above
811
812         // Move to next word of bitmap.
813         h.addr += ptrBits * goarch.PtrSize
814         h.low = 0
815         return h
816 }
817
818 // Add padding of size bytes.
819 func (h writeHeapBits) pad(size uintptr) writeHeapBits {
820         if size == 0 {
821                 return h
822         }
823         words := size / goarch.PtrSize
824         for words > ptrBits {
825                 h = h.write(0, ptrBits)
826                 words -= ptrBits
827         }
828         return h.write(0, words)
829 }
830
831 // Flush the bits that have been written, and add zeros as needed
832 // to cover the full object [addr, addr+size).
833 func (h writeHeapBits) flush(addr, size uintptr) {
834         // zeros counts the number of bits needed to represent the object minus the
835         // number of bits we've already written. This is the number of 0 bits
836         // that need to be added.
837         zeros := (addr+size-h.addr)/goarch.PtrSize - h.valid
838
839         // Add zero bits up to the bitmap word boundary
840         if zeros > 0 {
841                 z := ptrBits - h.valid
842                 if z > zeros {
843                         z = zeros
844                 }
845                 h.valid += z
846                 zeros -= z
847         }
848
849         // Find word in bitmap that we're going to write.
850         ai := arenaIndex(h.addr)
851         ha := mheap_.arenas[ai.l1()][ai.l2()]
852         idx := h.addr / (ptrBits * goarch.PtrSize) % heapArenaBitmapWords
853
854         // Write remaining bits.
855         if h.valid != h.low {
856                 m := uintptr(1)<<h.low - 1      // don't clear existing bits below "low"
857                 m |= ^(uintptr(1)<<h.valid - 1) // don't clear existing bits above "valid"
858                 ha.bitmap[idx] = ha.bitmap[idx]&m | h.mask
859         }
860         if zeros == 0 {
861                 return
862         }
863
864         // Record in the noMorePtrs map that there won't be any more 1 bits,
865         // so readers can stop early.
866         ha.noMorePtrs[idx/8] |= uint8(1) << (idx % 8)
867
868         // Advance to next bitmap word.
869         h.addr += ptrBits * goarch.PtrSize
870
871         // Continue on writing zeros for the rest of the object.
872         // For standard use of the ptr bits this is not required, as
873         // the bits are read from the beginning of the object. Some uses,
874         // like oblets, bulk write barriers, and cgocheck, might
875         // start mid-object, so these writes are still required.
876         for {
877                 // Write zero bits.
878                 ai := arenaIndex(h.addr)
879                 ha := mheap_.arenas[ai.l1()][ai.l2()]
880                 idx := h.addr / (ptrBits * goarch.PtrSize) % heapArenaBitmapWords
881                 if zeros < ptrBits {
882                         ha.bitmap[idx] &^= uintptr(1)<<zeros - 1
883                         break
884                 } else if zeros == ptrBits {
885                         ha.bitmap[idx] = 0
886                         break
887                 } else {
888                         ha.bitmap[idx] = 0
889                         zeros -= ptrBits
890                 }
891                 ha.noMorePtrs[idx/8] |= uint8(1) << (idx % 8)
892                 h.addr += ptrBits * goarch.PtrSize
893         }
894 }
895
896 // heapBitsSetType records that the new allocation [x, x+size)
897 // holds in [x, x+dataSize) one or more values of type typ.
898 // (The number of values is given by dataSize / typ.size.)
899 // If dataSize < size, the fragment [x+dataSize, x+size) is
900 // recorded as non-pointer data.
901 // It is known that the type has pointers somewhere;
902 // malloc does not call heapBitsSetType when there are no pointers,
903 // because all free objects are marked as noscan during
904 // heapBitsSweepSpan.
905 //
906 // There can only be one allocation from a given span active at a time,
907 // and the bitmap for a span always falls on word boundaries,
908 // so there are no write-write races for access to the heap bitmap.
909 // Hence, heapBitsSetType can access the bitmap without atomics.
910 //
911 // There can be read-write races between heapBitsSetType and things
912 // that read the heap bitmap like scanobject. However, since
913 // heapBitsSetType is only used for objects that have not yet been
914 // made reachable, readers will ignore bits being modified by this
915 // function. This does mean this function cannot transiently modify
916 // bits that belong to neighboring objects. Also, on weakly-ordered
917 // machines, callers must execute a store/store (publication) barrier
918 // between calling this function and making the object reachable.
919 func heapBitsSetType(x, size, dataSize uintptr, typ *_type) {
920         const doubleCheck = true // slow but helpful; enable to test modifications to this code
921
922         if doubleCheck && dataSize%typ.size != 0 {
923                 throw("heapBitsSetType: dataSize not a multiple of typ.size")
924         }
925
926         if goarch.PtrSize == 8 && size == goarch.PtrSize {
927                 // It's one word and it has pointers, it must be a pointer.
928                 // Since all allocated one-word objects are pointers
929                 // (non-pointers are aggregated into tinySize allocations),
930                 // initSpan sets the pointer bits for us. Nothing to do here.
931                 if doubleCheck {
932                         h, addr := heapBitsForAddr(x, size).next()
933                         if addr != x {
934                                 throw("heapBitsSetType: pointer bit missing")
935                         }
936                         _, addr = h.next()
937                         if addr != 0 {
938                                 throw("heapBitsSetType: second pointer bit found")
939                         }
940                 }
941                 return
942         }
943
944         h := writeHeapBitsForAddr(x)
945
946         // Handle GC program.
947         if typ.kind&kindGCProg != 0 {
948                 // Expand the gc program into the storage we're going to use for the actual object.
949                 obj := (*uint8)(unsafe.Pointer(x))
950                 n := runGCProg(addb(typ.gcdata, 4), obj)
951                 // Use the expanded program to set the heap bits.
952                 for i := uintptr(0); true; i += typ.size {
953                         // Copy expanded program to heap bitmap.
954                         p := obj
955                         j := n
956                         for j > 8 {
957                                 h = h.write(uintptr(*p), 8)
958                                 p = add1(p)
959                                 j -= 8
960                         }
961                         h = h.write(uintptr(*p), j)
962
963                         if i+typ.size == dataSize {
964                                 break // no padding after last element
965                         }
966
967                         // Pad with zeros to the start of the next element.
968                         h = h.pad(typ.size - n*goarch.PtrSize)
969                 }
970
971                 h.flush(x, size)
972
973                 // Erase the expanded GC program.
974                 memclrNoHeapPointers(unsafe.Pointer(obj), (n+7)/8)
975                 return
976         }
977
978         // Note about sizes:
979         //
980         // typ.size is the number of words in the object,
981         // and typ.ptrdata is the number of words in the prefix
982         // of the object that contains pointers. That is, the final
983         // typ.size - typ.ptrdata words contain no pointers.
984         // This allows optimization of a common pattern where
985         // an object has a small header followed by a large scalar
986         // buffer. If we know the pointers are over, we don't have
987         // to scan the buffer's heap bitmap at all.
988         // The 1-bit ptrmasks are sized to contain only bits for
989         // the typ.ptrdata prefix, zero padded out to a full byte
990         // of bitmap. If there is more room in the allocated object,
991         // that space is pointerless. The noMorePtrs bitmap will prevent
992         // scanning large pointerless tails of an object.
993         //
994         // Replicated copies are not as nice: if there is an array of
995         // objects with scalar tails, all but the last tail does have to
996         // be initialized, because there is no way to say "skip forward".
997
998         for i := uintptr(0); true; i += typ.size {
999                 p := typ.gcdata
1000                 var j uintptr
1001                 for j = 0; j+8*goarch.PtrSize < typ.ptrdata; j += 8 * goarch.PtrSize {
1002                         h = h.write(uintptr(*p), 8)
1003                         p = add1(p)
1004                 }
1005                 h = h.write(uintptr(*p), (typ.ptrdata-j)/goarch.PtrSize)
1006                 if i+typ.size == dataSize {
1007                         break // don't need the trailing nonptr bits on the last element.
1008                 }
1009                 // Pad with zeros to the start of the next element.
1010                 h = h.pad(typ.size - typ.ptrdata)
1011         }
1012         h.flush(x, size)
1013
1014         if doubleCheck {
1015                 h := heapBitsForAddr(x, size)
1016                 for i := uintptr(0); i < size; i += goarch.PtrSize {
1017                         // Compute the pointer bit we want at offset i.
1018                         want := false
1019                         if i < dataSize {
1020                                 off := i % typ.size
1021                                 if off < typ.ptrdata {
1022                                         j := off / goarch.PtrSize
1023                                         want = *addb(typ.gcdata, j/8)>>(j%8)&1 != 0
1024                                 }
1025                         }
1026                         if want {
1027                                 var addr uintptr
1028                                 h, addr = h.next()
1029                                 if addr != x+i {
1030                                         throw("heapBitsSetType: pointer entry not correct")
1031                                 }
1032                         }
1033                 }
1034                 if _, addr := h.next(); addr != 0 {
1035                         throw("heapBitsSetType: extra pointer")
1036                 }
1037         }
1038 }
1039
1040 var debugPtrmask struct {
1041         lock mutex
1042         data *byte
1043 }
1044
1045 // progToPointerMask returns the 1-bit pointer mask output by the GC program prog.
1046 // size the size of the region described by prog, in bytes.
1047 // The resulting bitvector will have no more than size/goarch.PtrSize bits.
1048 func progToPointerMask(prog *byte, size uintptr) bitvector {
1049         n := (size/goarch.PtrSize + 7) / 8
1050         x := (*[1 << 30]byte)(persistentalloc(n+1, 1, &memstats.buckhash_sys))[:n+1]
1051         x[len(x)-1] = 0xa1 // overflow check sentinel
1052         n = runGCProg(prog, &x[0])
1053         if x[len(x)-1] != 0xa1 {
1054                 throw("progToPointerMask: overflow")
1055         }
1056         return bitvector{int32(n), &x[0]}
1057 }
1058
1059 // Packed GC pointer bitmaps, aka GC programs.
1060 //
1061 // For large types containing arrays, the type information has a
1062 // natural repetition that can be encoded to save space in the
1063 // binary and in the memory representation of the type information.
1064 //
1065 // The encoding is a simple Lempel-Ziv style bytecode machine
1066 // with the following instructions:
1067 //
1068 //      00000000: stop
1069 //      0nnnnnnn: emit n bits copied from the next (n+7)/8 bytes
1070 //      10000000 n c: repeat the previous n bits c times; n, c are varints
1071 //      1nnnnnnn c: repeat the previous n bits c times; c is a varint
1072
1073 // runGCProg returns the number of 1-bit entries written to memory.
1074 func runGCProg(prog, dst *byte) uintptr {
1075         dstStart := dst
1076
1077         // Bits waiting to be written to memory.
1078         var bits uintptr
1079         var nbits uintptr
1080
1081         p := prog
1082 Run:
1083         for {
1084                 // Flush accumulated full bytes.
1085                 // The rest of the loop assumes that nbits <= 7.
1086                 for ; nbits >= 8; nbits -= 8 {
1087                         *dst = uint8(bits)
1088                         dst = add1(dst)
1089                         bits >>= 8
1090                 }
1091
1092                 // Process one instruction.
1093                 inst := uintptr(*p)
1094                 p = add1(p)
1095                 n := inst & 0x7F
1096                 if inst&0x80 == 0 {
1097                         // Literal bits; n == 0 means end of program.
1098                         if n == 0 {
1099                                 // Program is over.
1100                                 break Run
1101                         }
1102                         nbyte := n / 8
1103                         for i := uintptr(0); i < nbyte; i++ {
1104                                 bits |= uintptr(*p) << nbits
1105                                 p = add1(p)
1106                                 *dst = uint8(bits)
1107                                 dst = add1(dst)
1108                                 bits >>= 8
1109                         }
1110                         if n %= 8; n > 0 {
1111                                 bits |= uintptr(*p) << nbits
1112                                 p = add1(p)
1113                                 nbits += n
1114                         }
1115                         continue Run
1116                 }
1117
1118                 // Repeat. If n == 0, it is encoded in a varint in the next bytes.
1119                 if n == 0 {
1120                         for off := uint(0); ; off += 7 {
1121                                 x := uintptr(*p)
1122                                 p = add1(p)
1123                                 n |= (x & 0x7F) << off
1124                                 if x&0x80 == 0 {
1125                                         break
1126                                 }
1127                         }
1128                 }
1129
1130                 // Count is encoded in a varint in the next bytes.
1131                 c := uintptr(0)
1132                 for off := uint(0); ; off += 7 {
1133                         x := uintptr(*p)
1134                         p = add1(p)
1135                         c |= (x & 0x7F) << off
1136                         if x&0x80 == 0 {
1137                                 break
1138                         }
1139                 }
1140                 c *= n // now total number of bits to copy
1141
1142                 // If the number of bits being repeated is small, load them
1143                 // into a register and use that register for the entire loop
1144                 // instead of repeatedly reading from memory.
1145                 // Handling fewer than 8 bits here makes the general loop simpler.
1146                 // The cutoff is goarch.PtrSize*8 - 7 to guarantee that when we add
1147                 // the pattern to a bit buffer holding at most 7 bits (a partial byte)
1148                 // it will not overflow.
1149                 src := dst
1150                 const maxBits = goarch.PtrSize*8 - 7
1151                 if n <= maxBits {
1152                         // Start with bits in output buffer.
1153                         pattern := bits
1154                         npattern := nbits
1155
1156                         // If we need more bits, fetch them from memory.
1157                         src = subtract1(src)
1158                         for npattern < n {
1159                                 pattern <<= 8
1160                                 pattern |= uintptr(*src)
1161                                 src = subtract1(src)
1162                                 npattern += 8
1163                         }
1164
1165                         // We started with the whole bit output buffer,
1166                         // and then we loaded bits from whole bytes.
1167                         // Either way, we might now have too many instead of too few.
1168                         // Discard the extra.
1169                         if npattern > n {
1170                                 pattern >>= npattern - n
1171                                 npattern = n
1172                         }
1173
1174                         // Replicate pattern to at most maxBits.
1175                         if npattern == 1 {
1176                                 // One bit being repeated.
1177                                 // If the bit is 1, make the pattern all 1s.
1178                                 // If the bit is 0, the pattern is already all 0s,
1179                                 // but we can claim that the number of bits
1180                                 // in the word is equal to the number we need (c),
1181                                 // because right shift of bits will zero fill.
1182                                 if pattern == 1 {
1183                                         pattern = 1<<maxBits - 1
1184                                         npattern = maxBits
1185                                 } else {
1186                                         npattern = c
1187                                 }
1188                         } else {
1189                                 b := pattern
1190                                 nb := npattern
1191                                 if nb+nb <= maxBits {
1192                                         // Double pattern until the whole uintptr is filled.
1193                                         for nb <= goarch.PtrSize*8 {
1194                                                 b |= b << nb
1195                                                 nb += nb
1196                                         }
1197                                         // Trim away incomplete copy of original pattern in high bits.
1198                                         // TODO(rsc): Replace with table lookup or loop on systems without divide?
1199                                         nb = maxBits / npattern * npattern
1200                                         b &= 1<<nb - 1
1201                                         pattern = b
1202                                         npattern = nb
1203                                 }
1204                         }
1205
1206                         // Add pattern to bit buffer and flush bit buffer, c/npattern times.
1207                         // Since pattern contains >8 bits, there will be full bytes to flush
1208                         // on each iteration.
1209                         for ; c >= npattern; c -= npattern {
1210                                 bits |= pattern << nbits
1211                                 nbits += npattern
1212                                 for nbits >= 8 {
1213                                         *dst = uint8(bits)
1214                                         dst = add1(dst)
1215                                         bits >>= 8
1216                                         nbits -= 8
1217                                 }
1218                         }
1219
1220                         // Add final fragment to bit buffer.
1221                         if c > 0 {
1222                                 pattern &= 1<<c - 1
1223                                 bits |= pattern << nbits
1224                                 nbits += c
1225                         }
1226                         continue Run
1227                 }
1228
1229                 // Repeat; n too large to fit in a register.
1230                 // Since nbits <= 7, we know the first few bytes of repeated data
1231                 // are already written to memory.
1232                 off := n - nbits // n > nbits because n > maxBits and nbits <= 7
1233                 // Leading src fragment.
1234                 src = subtractb(src, (off+7)/8)
1235                 if frag := off & 7; frag != 0 {
1236                         bits |= uintptr(*src) >> (8 - frag) << nbits
1237                         src = add1(src)
1238                         nbits += frag
1239                         c -= frag
1240                 }
1241                 // Main loop: load one byte, write another.
1242                 // The bits are rotating through the bit buffer.
1243                 for i := c / 8; i > 0; i-- {
1244                         bits |= uintptr(*src) << nbits
1245                         src = add1(src)
1246                         *dst = uint8(bits)
1247                         dst = add1(dst)
1248                         bits >>= 8
1249                 }
1250                 // Final src fragment.
1251                 if c %= 8; c > 0 {
1252                         bits |= (uintptr(*src) & (1<<c - 1)) << nbits
1253                         nbits += c
1254                 }
1255         }
1256
1257         // Write any final bits out, using full-byte writes, even for the final byte.
1258         totalBits := (uintptr(unsafe.Pointer(dst))-uintptr(unsafe.Pointer(dstStart)))*8 + nbits
1259         nbits += -nbits & 7
1260         for ; nbits > 0; nbits -= 8 {
1261                 *dst = uint8(bits)
1262                 dst = add1(dst)
1263                 bits >>= 8
1264         }
1265         return totalBits
1266 }
1267
1268 // materializeGCProg allocates space for the (1-bit) pointer bitmask
1269 // for an object of size ptrdata.  Then it fills that space with the
1270 // pointer bitmask specified by the program prog.
1271 // The bitmask starts at s.startAddr.
1272 // The result must be deallocated with dematerializeGCProg.
1273 func materializeGCProg(ptrdata uintptr, prog *byte) *mspan {
1274         // Each word of ptrdata needs one bit in the bitmap.
1275         bitmapBytes := divRoundUp(ptrdata, 8*goarch.PtrSize)
1276         // Compute the number of pages needed for bitmapBytes.
1277         pages := divRoundUp(bitmapBytes, pageSize)
1278         s := mheap_.allocManual(pages, spanAllocPtrScalarBits)
1279         runGCProg(addb(prog, 4), (*byte)(unsafe.Pointer(s.startAddr)))
1280         return s
1281 }
1282 func dematerializeGCProg(s *mspan) {
1283         mheap_.freeManual(s, spanAllocPtrScalarBits)
1284 }
1285
1286 func dumpGCProg(p *byte) {
1287         nptr := 0
1288         for {
1289                 x := *p
1290                 p = add1(p)
1291                 if x == 0 {
1292                         print("\t", nptr, " end\n")
1293                         break
1294                 }
1295                 if x&0x80 == 0 {
1296                         print("\t", nptr, " lit ", x, ":")
1297                         n := int(x+7) / 8
1298                         for i := 0; i < n; i++ {
1299                                 print(" ", hex(*p))
1300                                 p = add1(p)
1301                         }
1302                         print("\n")
1303                         nptr += int(x)
1304                 } else {
1305                         nbit := int(x &^ 0x80)
1306                         if nbit == 0 {
1307                                 for nb := uint(0); ; nb += 7 {
1308                                         x := *p
1309                                         p = add1(p)
1310                                         nbit |= int(x&0x7f) << nb
1311                                         if x&0x80 == 0 {
1312                                                 break
1313                                         }
1314                                 }
1315                         }
1316                         count := 0
1317                         for nb := uint(0); ; nb += 7 {
1318                                 x := *p
1319                                 p = add1(p)
1320                                 count |= int(x&0x7f) << nb
1321                                 if x&0x80 == 0 {
1322                                         break
1323                                 }
1324                         }
1325                         print("\t", nptr, " repeat ", nbit, " × ", count, "\n")
1326                         nptr += nbit * count
1327                 }
1328         }
1329 }
1330
1331 // Testing.
1332
1333 func getgcmaskcb(frame *stkframe, ctxt unsafe.Pointer) bool {
1334         target := (*stkframe)(ctxt)
1335         if frame.sp <= target.sp && target.sp < frame.varp {
1336                 *target = *frame
1337                 return false
1338         }
1339         return true
1340 }
1341
1342 // gcbits returns the GC type info for x, for testing.
1343 // The result is the bitmap entries (0 or 1), one entry per byte.
1344 //
1345 //go:linkname reflect_gcbits reflect.gcbits
1346 func reflect_gcbits(x any) []byte {
1347         return getgcmask(x)
1348 }
1349
1350 // Returns GC type info for the pointer stored in ep for testing.
1351 // If ep points to the stack, only static live information will be returned
1352 // (i.e. not for objects which are only dynamically live stack objects).
1353 func getgcmask(ep any) (mask []byte) {
1354         e := *efaceOf(&ep)
1355         p := e.data
1356         t := e._type
1357         // data or bss
1358         for _, datap := range activeModules() {
1359                 // data
1360                 if datap.data <= uintptr(p) && uintptr(p) < datap.edata {
1361                         bitmap := datap.gcdatamask.bytedata
1362                         n := (*ptrtype)(unsafe.Pointer(t)).elem.size
1363                         mask = make([]byte, n/goarch.PtrSize)
1364                         for i := uintptr(0); i < n; i += goarch.PtrSize {
1365                                 off := (uintptr(p) + i - datap.data) / goarch.PtrSize
1366                                 mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
1367                         }
1368                         return
1369                 }
1370
1371                 // bss
1372                 if datap.bss <= uintptr(p) && uintptr(p) < datap.ebss {
1373                         bitmap := datap.gcbssmask.bytedata
1374                         n := (*ptrtype)(unsafe.Pointer(t)).elem.size
1375                         mask = make([]byte, n/goarch.PtrSize)
1376                         for i := uintptr(0); i < n; i += goarch.PtrSize {
1377                                 off := (uintptr(p) + i - datap.bss) / goarch.PtrSize
1378                                 mask[i/goarch.PtrSize] = (*addb(bitmap, off/8) >> (off % 8)) & 1
1379                         }
1380                         return
1381                 }
1382         }
1383
1384         // heap
1385         if base, s, _ := findObject(uintptr(p), 0, 0); base != 0 {
1386                 if s.spanclass.noscan() {
1387                         return nil
1388                 }
1389                 n := s.elemsize
1390                 hbits := heapBitsForAddr(base, n)
1391                 mask = make([]byte, n/goarch.PtrSize)
1392                 for {
1393                         var addr uintptr
1394                         if hbits, addr = hbits.next(); addr == 0 {
1395                                 break
1396                         }
1397                         mask[(addr-base)/goarch.PtrSize] = 1
1398                 }
1399                 // Callers expect this mask to end at the last pointer.
1400                 for len(mask) > 0 && mask[len(mask)-1] == 0 {
1401                         mask = mask[:len(mask)-1]
1402                 }
1403                 return
1404         }
1405
1406         // stack
1407         if gp := getg(); gp.m.curg.stack.lo <= uintptr(p) && uintptr(p) < gp.m.curg.stack.hi {
1408                 var frame stkframe
1409                 frame.sp = uintptr(p)
1410                 gentraceback(gp.m.curg.sched.pc, gp.m.curg.sched.sp, 0, gp.m.curg, 0, nil, 1000, getgcmaskcb, noescape(unsafe.Pointer(&frame)), 0)
1411                 if frame.fn.valid() {
1412                         locals, _, _ := getStackMap(&frame, nil, false)
1413                         if locals.n == 0 {
1414                                 return
1415                         }
1416                         size := uintptr(locals.n) * goarch.PtrSize
1417                         n := (*ptrtype)(unsafe.Pointer(t)).elem.size
1418                         mask = make([]byte, n/goarch.PtrSize)
1419                         for i := uintptr(0); i < n; i += goarch.PtrSize {
1420                                 off := (uintptr(p) + i - frame.varp + size) / goarch.PtrSize
1421                                 mask[i/goarch.PtrSize] = locals.ptrbit(off)
1422                         }
1423                 }
1424                 return
1425         }
1426
1427         // otherwise, not something the GC knows about.
1428         // possibly read-only data, like malloc(0).
1429         // must not have pointers
1430         return
1431 }