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