Debian Codegraph @

libgo/go/runtime/malloc.go

raw
1 // Copyright 2014 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 // Memory allocator.
6 //
7 // This was originally based on tcmalloc, but has diverged quite a bit.
8 // http://goog-perftools.sourceforge.net/doc/tcmalloc.html
9
10 // The main allocator works in runs of pages.
11 // Small allocation sizes (up to and including 32 kB) are
12 // rounded to one of about 70 size classes, each of which
13 // has its own free set of objects of exactly that size.
14 // Any free page of memory can be split into a set of objects
15 // of one size class, which are then managed using a free bitmap.
16 //
17 // The allocator's data structures are:
18 //
19 // fixalloc: a free-list allocator for fixed-size off-heap objects,
20 // used to manage storage used by the allocator.
21 // mheap: the malloc heap, managed at page (8192-byte) granularity.
22 // mspan: a run of in-use pages managed by the mheap.
23 // mcentral: collects all spans of a given size class.
24 // mcache: a per-P cache of mspans with free space.
25 // mstats: allocation statistics.
26 //
27 // Allocating a small object proceeds up a hierarchy of caches:
28 //
29 // 1. Round the size up to one of the small size classes
30 // and look in the corresponding mspan in this P's mcache.
31 // Scan the mspan's free bitmap to find a free slot.
32 // If there is a free slot, allocate it.
33 // This can all be done without acquiring a lock.
34 //
35 // 2. If the mspan has no free slots, obtain a new mspan
36 // from the mcentral's list of mspans of the required size
37 // class that have free space.
38 // Obtaining a whole span amortizes the cost of locking
39 // the mcentral.
40 //
41 // 3. If the mcentral's mspan list is empty, obtain a run
42 // of pages from the mheap to use for the mspan.
43 //
44 // 4. If the mheap is empty or has no page runs large enough,
45 // allocate a new group of pages (at least 1MB) from the
46 // operating system. Allocating a large run of pages
47 // amortizes the cost of talking to the operating system.
48 //
49 // Sweeping an mspan and freeing objects on it proceeds up a similar
50 // hierarchy:
51 //
52 // 1. If the mspan is being swept in response to allocation, it
53 // is returned to the mcache to satisfy the allocation.
54 //
55 // 2. Otherwise, if the mspan still has allocated objects in it,
56 // it is placed on the mcentral free list for the mspan's size
57 // class.
58 //
59 // 3. Otherwise, if all objects in the mspan are free, the mspan's
60 // pages are returned to the mheap and the mspan is now dead.
61 //
62 // Allocating and freeing a large object uses the mheap
63 // directly, bypassing the mcache and mcentral.
64 //
65 // If mspan.needzero is false, then free object slots in the mspan are
66 // already zeroed. Otherwise if needzero is true, objects are zeroed as
67 // they are allocated. There are various benefits to delaying zeroing
68 // this way:
69 //
70 // 1. Stack frame allocation can avoid zeroing altogether.
71 //
72 // 2. It exhibits better temporal locality, since the program is
73 // probably about to write to the memory.
74 //
75 // 3. We don't zero pages that never get reused.
76
77 // Virtual memory layout
78 //
79 // The heap consists of a set of arenas, which are 64MB on 64-bit and
80 // 4MB on 32-bit (heapArenaBytes). Each arena's start address is also
81 // aligned to the arena size.
82 //
83 // Each arena has an associated heapArena object that stores the
84 // metadata for that arena: the heap bitmap for all words in the arena
85 // and the span map for all pages in the arena. heapArena objects are
86 // themselves allocated off-heap.
87 //
88 // Since arenas are aligned, the address space can be viewed as a
89 // series of arena frames. The arena map (mheap_.arenas) maps from
90 // arena frame number to *heapArena, or nil for parts of the address
91 // space not backed by the Go heap. The arena map is structured as a
92 // two-level array consisting of a "L1" arena map and many "L2" arena
93 // maps; however, since arenas are large, on many architectures, the
94 // arena map consists of a single, large L2 map.
95 //
96 // The arena map covers the entire possible address space, allowing
97 // the Go heap to use any part of the address space. The allocator
98 // attempts to keep arenas contiguous so that large spans (and hence
99 // large objects) can cross arenas.
100
101 package runtime
102
103 import (
104 "internal/goarch"
105 "internal/goos"
106 "runtime/internal/atomic"
107 "runtime/internal/math"
108 "runtime/internal/sys"
109 "unsafe"
110 )
111
112 // C function to get the end of the program's memory.
113 func getEnd() uintptr
114
115 // For gccgo, use go:linkname to export compiler-called functions.
116 //
117 //go:linkname newobject
118
119 // Functions called by C code.
120 //go:linkname mallocgc
121
122 const (
123 debugMalloc = false
124
125 maxTinySize = _TinySize
126 tinySizeClass = _TinySizeClass
127 maxSmallSize = _MaxSmallSize
128
129 pageShift = _PageShift
130 pageSize = _PageSize
131 pageMask = _PageMask
132 // By construction, single page spans of the smallest object class
133 // have the most objects per span.
134 maxObjsPerSpan = pageSize / 8
135
136 concurrentSweep = _ConcurrentSweep
137
138 _PageSize = 1 << _PageShift
139 _PageMask = _PageSize - 1
140
141 // _64bit = 1 on 64-bit systems, 0 on 32-bit systems
142 _64bit = 1 << (^uintptr(0) >> 63) / 2
143
144 // Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
145 _TinySize = 16
146 _TinySizeClass = int8(2)
147
148 _FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
149
150 // Per-P, per order stack segment cache size.
151 _StackCacheSize = 32 * 1024
152
153 // Number of orders that get caching. Order 0 is FixedStack
154 // and each successive order is twice as large.
155 // We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
156 // will be allocated directly.
157 // Since FixedStack is different on different systems, we
158 // must vary NumStackOrders to keep the same maximum cached size.
159 // OS | FixedStack | NumStackOrders
160 // -----------------+------------+---------------
161 // linux/darwin/bsd | 2KB | 4
162 // windows/32 | 4KB | 3
163 // windows/64 | 8KB | 2
164 // plan9 | 4KB | 3
165 _NumStackOrders = 4 - goarch.PtrSize/4*goos.IsWindows - 1*goos.IsPlan9
166
167 // heapAddrBits is the number of bits in a heap address. On
168 // amd64, addresses are sign-extended beyond heapAddrBits. On
169 // other arches, they are zero-extended.
170 //
171 // On most 64-bit platforms, we limit this to 48 bits based on a
172 // combination of hardware and OS limitations.
173 //
174 // amd64 hardware limits addresses to 48 bits, sign-extended
175 // to 64 bits. Addresses where the top 16 bits are not either
176 // all 0 or all 1 are "non-canonical" and invalid. Because of
177 // these "negative" addresses, we offset addresses by 1<<47
178 // (arenaBaseOffset) on amd64 before computing indexes into
179 // the heap arenas index. In 2017, amd64 hardware added
180 // support for 57 bit addresses; however, currently only Linux
181 // supports this extension and the kernel will never choose an
182 // address above 1<<47 unless mmap is called with a hint
183 // address above 1<<47 (which we never do).
184 //
185 // arm64 hardware (as of ARMv8) limits user addresses to 48
186 // bits, in the range [0, 1<<48).
187 //
188 // ppc64, mips64, and s390x support arbitrary 64 bit addresses
189 // in hardware. On Linux, Go leans on stricter OS limits. Based
190 // on Linux's processor.h, the user address space is limited as
191 // follows on 64-bit architectures:
192 //
193 // Architecture Name Maximum Value (exclusive)
194 // ---------------------------------------------------------------------
195 // amd64 TASK_SIZE_MAX 0x007ffffffff000 (47 bit addresses)
196 // arm64 TASK_SIZE_64 0x01000000000000 (48 bit addresses)
197 // ppc64{,le} TASK_SIZE_USER64 0x00400000000000 (46 bit addresses)
198 // mips64{,le} TASK_SIZE64 0x00010000000000 (40 bit addresses)
199 // s390x TASK_SIZE 1<<64 (64 bit addresses)
200 //
201 // These limits may increase over time, but are currently at
202 // most 48 bits except on s390x. On all architectures, Linux
203 // starts placing mmap'd regions at addresses that are
204 // significantly below 48 bits, so even if it's possible to
205 // exceed Go's 48 bit limit, it's extremely unlikely in
206 // practice.
207 //
208 // On 32-bit platforms, we accept the full 32-bit address
209 // space because doing so is cheap.
210 // mips32 only has access to the low 2GB of virtual memory, so
211 // we further limit it to 31 bits.
212 //
213 // On ios/arm64, although 64-bit pointers are presumably
214 // available, pointers are truncated to 33 bits in iOS <14.
215 // Furthermore, only the top 4 GiB of the address space are
216 // actually available to the application. In iOS >=14, more
217 // of the address space is available, and the OS can now
218 // provide addresses outside of those 33 bits. Pick 40 bits
219 // as a reasonable balance between address space usage by the
220 // page allocator, and flexibility for what mmap'd regions
221 // we'll accept for the heap. We can't just move to the full
222 // 48 bits because this uses too much address space for older
223 // iOS versions.
224 // TODO(mknyszek): Once iOS <14 is deprecated, promote ios/arm64
225 // to a 48-bit address space like every other arm64 platform.
226 //
227 // WebAssembly currently has a limit of 4GB linear memory.
228 heapAddrBits = (_64bit*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64))*48 + (1-_64bit+goarch.IsWasm)*(32-(goarch.IsMips+goarch.IsMipsle)) + 40*goos.IsIos*goarch.IsArm64
229
230 // maxAlloc is the maximum size of an allocation. On 64-bit,
231 // it's theoretically possible to allocate 1<<heapAddrBits bytes. On
232 // 32-bit, however, this is one less than 1<<32 because the
233 // number of bytes in the address space doesn't actually fit
234 // in a uintptr.
235 maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1
236
237 // The number of bits in a heap address, the size of heap
238 // arenas, and the L1 and L2 arena map sizes are related by
239 //
240 // (1 << addr bits) = arena size * L1 entries * L2 entries
241 //
242 // Currently, we balance these as follows:
243 //
244 // Platform Addr bits Arena size L1 entries L2 entries
245 // -------------- --------- ---------- ---------- -----------
246 // */64-bit 48 64MB 1 4M (32MB)
247 // windows/64-bit 48 4MB 64 1M (8MB)
248 // ios/arm64 33 4MB 1 2048 (8KB)
249 // */32-bit 32 4MB 1 1024 (4KB)
250 // */mips(le) 31 4MB 1 512 (2KB)
251
252 // heapArenaBytes is the size of a heap arena. The heap
253 // consists of mappings of size heapArenaBytes, aligned to
254 // heapArenaBytes. The initial heap mapping is one arena.
255 //
256 // This is currently 64MB on 64-bit non-Windows and 4MB on
257 // 32-bit and on Windows. We use smaller arenas on Windows
258 // because all committed memory is charged to the process,
259 // even if it's not touched. Hence, for processes with small
260 // heaps, the mapped arena space needs to be commensurate.
261 // This is particularly important with the race detector,
262 // since it significantly amplifies the cost of committed
263 // memory.
264 heapArenaBytes = 1 << logHeapArenaBytes
265
266 // logHeapArenaBytes is log_2 of heapArenaBytes. For clarity,
267 // prefer using heapArenaBytes where possible (we need the
268 // constant to compute some other constants).
269 logHeapArenaBytes = (6+20)*(_64bit*(1-goos.IsWindows)*(1-goarch.IsWasm)*(1-goos.IsIos*goarch.IsArm64)) + (2+20)*(_64bit*goos.IsWindows) + (2+20)*(1-_64bit) + (2+20)*goarch.IsWasm + (2+20)*goos.IsIos*goarch.IsArm64
270
271 // heapArenaBitmapBytes is the size of each heap arena's bitmap.
272 heapArenaBitmapBytes = heapArenaBytes / (goarch.PtrSize * 8 / 2)
273
274 pagesPerArena = heapArenaBytes / pageSize
275
276 // arenaL1Bits is the number of bits of the arena number
277 // covered by the first level arena map.
278 //
279 // This number should be small, since the first level arena
280 // map requires PtrSize*(1<<arenaL1Bits) of space in the
281 // binary's BSS. It can be zero, in which case the first level
282 // index is effectively unused. There is a performance benefit
283 // to this, since the generated code can be more efficient,
284 // but comes at the cost of having a large L2 mapping.
285 //
286 // We use the L1 map on 64-bit Windows because the arena size
287 // is small, but the address space is still 48 bits, and
288 // there's a high cost to having a large L2.
289 arenaL1Bits = 6 * (_64bit * goos.IsWindows)
290
291 // arenaL2Bits is the number of bits of the arena number
292 // covered by the second level arena index.
293 //
294 // The size of each arena map allocation is proportional to
295 // 1<<arenaL2Bits, so it's important that this not be too
296 // large. 48 bits leads to 32MB arena index allocations, which
297 // is about the practical threshold.
298 arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits
299
300 // arenaL1Shift is the number of bits to shift an arena frame
301 // number by to compute an index into the first level arena map.
302 arenaL1Shift = arenaL2Bits
303
304 // arenaBits is the total bits in a combined arena map index.
305 // This is split between the index into the L1 arena map and
306 // the L2 arena map.
307 arenaBits = arenaL1Bits + arenaL2Bits
308
309 // arenaBaseOffset is the pointer value that corresponds to
310 // index 0 in the heap arena map.
311 //
312 // On amd64, the address space is 48 bits, sign extended to 64
313 // bits. This offset lets us handle "negative" addresses (or
314 // high addresses if viewed as unsigned).
315 //
316 // On aix/ppc64, this offset allows to keep the heapAddrBits to
317 // 48. Otherwise, it would be 60 in order to handle mmap addresses
318 // (in range 0x0a00000000000000 - 0x0afffffffffffff). But in this
319 // case, the memory reserved in (s *pageAlloc).init for chunks
320 // is causing important slowdowns.
321 //
322 // On other platforms, the user address space is contiguous
323 // and starts at 0, so no offset is necessary.
324 arenaBaseOffset = 0xffff800000000000*goarch.IsAmd64 + 0x0a00000000000000*goos.IsAix*goarch.IsPpc64
325 // A typed version of this constant that will make it into DWARF (for viewcore).
326 arenaBaseOffsetUintptr = uintptr(arenaBaseOffset)
327
328 // Max number of threads to run garbage collection.
329 // 2, 3, and 4 are all plausible maximums depending
330 // on the hardware details of the machine. The garbage
331 // collector scales well to 32 cpus.
332 _MaxGcproc = 32
333
334 // minLegalPointer is the smallest possible legal pointer.
335 // This is the smallest possible architectural page size,
336 // since we assume that the first page is never mapped.
337 //
338 // This should agree with minZeroPage in the compiler.
339 minLegalPointer uintptr = 4096
340 )
341
342 // physPageSize is the size in bytes of the OS's physical pages.
343 // Mapping and unmapping operations must be done at multiples of
344 // physPageSize.
345 //
346 // This must be set by the OS init code (typically in osinit) before
347 // mallocinit.
348 var physPageSize uintptr
349
350 // physHugePageSize is the size in bytes of the OS's default physical huge
351 // page size whose allocation is opaque to the application. It is assumed
352 // and verified to be a power of two.
353 //
354 // If set, this must be set by the OS init code (typically in osinit) before
355 // mallocinit. However, setting it at all is optional, and leaving the default
356 // value is always safe (though potentially less efficient).
357 //
358 // Since physHugePageSize is always assumed to be a power of two,
359 // physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
360 // The purpose of physHugePageShift is to avoid doing divisions in
361 // performance critical functions.
362 var (
363 physHugePageSize uintptr
364 physHugePageShift uint
365 )
366
367 // OS memory management abstraction layer
368 //
369 // Regions of the address space managed by the runtime may be in one of four
370 // states at any given time:
371 // 1) None - Unreserved and unmapped, the default state of any region.
372 // 2) Reserved - Owned by the runtime, but accessing it would cause a fault.
373 // Does not count against the process' memory footprint.
374 // 3) Prepared - Reserved, intended not to be backed by physical memory (though
375 // an OS may implement this lazily). Can transition efficiently to
376 // Ready. Accessing memory in such a region is undefined (may
377 // fault, may give back unexpected zeroes, etc.).
378 // 4) Ready - may be accessed safely.
379 //
380 // This set of states is more than is strictly necessary to support all the
381 // currently supported platforms. One could get by with just None, Reserved, and
382 // Ready. However, the Prepared state gives us flexibility for performance
383 // purposes. For example, on POSIX-y operating systems, Reserved is usually a
384 // private anonymous mmap'd region with PROT_NONE set, and to transition
385 // to Ready would require setting PROT_READ|PROT_WRITE. However the
386 // underspecification of Prepared lets us use just MADV_FREE to transition from
387 // Ready to Prepared. Thus with the Prepared state we can set the permission
388 // bits just once early on, we can efficiently tell the OS that it's free to
389 // take pages away from us when we don't strictly need them.
390 //
391 // For each OS there is a common set of helpers defined that transition
392 // memory regions between these states. The helpers are as follows:
393 //
394 // sysAlloc transitions an OS-chosen region of memory from None to Ready.
395 // More specifically, it obtains a large chunk of zeroed memory from the
396 // operating system, typically on the order of a hundred kilobytes
397 // or a megabyte. This memory is always immediately available for use.
398 //
399 // sysFree transitions a memory region from any state to None. Therefore, it
400 // returns memory unconditionally. It is used if an out-of-memory error has been
401 // detected midway through an allocation or to carve out an aligned section of
402 // the address space. It is okay if sysFree is a no-op only if sysReserve always
403 // returns a memory region aligned to the heap allocator's alignment
404 // restrictions.
405 //
406 // sysReserve transitions a memory region from None to Reserved. It reserves
407 // address space in such a way that it would cause a fatal fault upon access
408 // (either via permissions or not committing the memory). Such a reservation is
409 // thus never backed by physical memory.
410 // If the pointer passed to it is non-nil, the caller wants the
411 // reservation there, but sysReserve can still choose another
412 // location if that one is unavailable.
413 // NOTE: sysReserve returns OS-aligned memory, but the heap allocator
414 // may use larger alignment, so the caller must be careful to realign the
415 // memory obtained by sysReserve.
416 //
417 // sysMap transitions a memory region from Reserved to Prepared. It ensures the
418 // memory region can be efficiently transitioned to Ready.
419 //
420 // sysUsed transitions a memory region from Prepared to Ready. It notifies the
421 // operating system that the memory region is needed and ensures that the region
422 // may be safely accessed. This is typically a no-op on systems that don't have
423 // an explicit commit step and hard over-commit limits, but is critical on
424 // Windows, for example.
425 //
426 // sysUnused transitions a memory region from Ready to Prepared. It notifies the
427 // operating system that the physical pages backing this memory region are no
428 // longer needed and can be reused for other purposes. The contents of a
429 // sysUnused memory region are considered forfeit and the region must not be
430 // accessed again until sysUsed is called.
431 //
432 // sysFault transitions a memory region from Ready or Prepared to Reserved. It
433 // marks a region such that it will always fault if accessed. Used only for
434 // debugging the runtime.
435
436 func mallocinit() {
437 if class_to_size[_TinySizeClass] != _TinySize {
438 throw("bad TinySizeClass")
439 }
440
441 if heapArenaBitmapBytes&(heapArenaBitmapBytes-1) != 0 {
442 // heapBits expects modular arithmetic on bitmap
443 // addresses to work.
444 throw("heapArenaBitmapBytes not a power of 2")
445 }
446
447 // Copy class sizes out for statistics table.
448 for i := range class_to_size {
449 memstats.by_size[i].size = uint32(class_to_size[i])
450 }
451
452 // Check physPageSize.
453 if physPageSize == 0 {
454 // The OS init code failed to fetch the physical page size.
455 throw("failed to get system page size")
456 }
457 if physPageSize > maxPhysPageSize {
458 print("system page size (", physPageSize, ") is larger than maximum page size (", maxPhysPageSize, ")\n")
459 throw("bad system page size")
460 }
461 if physPageSize < minPhysPageSize {
462 print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
463 throw("bad system page size")
464 }
465 if physPageSize&(physPageSize-1) != 0 {
466 print("system page size (", physPageSize, ") must be a power of 2\n")
467 throw("bad system page size")
468 }
469 if physHugePageSize&(physHugePageSize-1) != 0 {
470 print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
471 throw("bad system huge page size")
472 }
473 if physHugePageSize > maxPhysHugePageSize {
474 // physHugePageSize is greater than the maximum supported huge page size.
475 // Don't throw here, like in the other cases, since a system configured
476 // in this way isn't wrong, we just don't have the code to support them.
477 // Instead, silently set the huge page size to zero.
478 physHugePageSize = 0
479 }
480 if physHugePageSize != 0 {
481 // Since physHugePageSize is a power of 2, it suffices to increase
482 // physHugePageShift until 1<<physHugePageShift == physHugePageSize.
483 for 1<<physHugePageShift != physHugePageSize {
484 physHugePageShift++
485 }
486 }
487 if pagesPerArena%pagesPerSpanRoot != 0 {
488 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerSpanRoot (", pagesPerSpanRoot, ")\n")
489 throw("bad pagesPerSpanRoot")
490 }
491 if pagesPerArena%pagesPerReclaimerChunk != 0 {
492 print("pagesPerArena (", pagesPerArena, ") is not divisible by pagesPerReclaimerChunk (", pagesPerReclaimerChunk, ")\n")
493 throw("bad pagesPerReclaimerChunk")
494 }
495
496 // Initialize the heap.
497 mheap_.init()
498 mcache0 = allocmcache()
499 lockInit(&gcBitsArenas.lock, lockRankGcBitsArenas)
500 lockInit(&proflock, lockRankProf)
501 lockInit(&globalAlloc.mutex, lockRankGlobalAlloc)
502
503 // Create initial arena growth hints.
504 if goarch.PtrSize == 8 {
505 // On a 64-bit machine, we pick the following hints
506 // because:
507 //
508 // 1. Starting from the middle of the address space
509 // makes it easier to grow out a contiguous range
510 // without running in to some other mapping.
511 //
512 // 2. This makes Go heap addresses more easily
513 // recognizable when debugging.
514 //
515 // 3. Stack scanning in gccgo is still conservative,
516 // so it's important that addresses be distinguishable
517 // from other data.
518 //
519 // Starting at 0x00c0 means that the valid memory addresses
520 // will begin 0x00c0, 0x00c1, ...
521 // In little-endian, that's c0 00, c1 00, ... None of those are valid
522 // UTF-8 sequences, and they are otherwise as far away from
523 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
524 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
525 // on OS X during thread allocations. 0x00c0 causes conflicts with
526 // AddressSanitizer which reserves all memory up to 0x0100.
527 // These choices reduce the odds of a conservative garbage collector
528 // not collecting memory because some non-pointer block of memory
529 // had a bit pattern that matched a memory address.
530 //
531 // However, on arm64, we ignore all this advice above and slam the
532 // allocation at 0x40 << 32 because when using 4k pages with 3-level
533 // translation buffers, the user address space is limited to 39 bits
534 // On ios/arm64, the address space is even smaller.
535 //
536 // On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
537 // processes.
538 for i := 0x7f; i >= 0; i-- {
539 var p uintptr
540 switch {
541 case raceenabled:
542 // The TSAN runtime requires the heap
543 // to be in the range [0x00c000000000,
544 // 0x00e000000000).
545 p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
546 if p >= uintptrMask&0x00e000000000 {
547 continue
548 }
549 case GOARCH == "arm64" && GOOS == "ios":
550 p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
551 case GOARCH == "arm64":
552 p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
553 case GOOS == "aix":
554 if i == 0 {
555 // We don't use addresses directly after 0x0A00000000000000
556 // to avoid collisions with others mmaps done by non-go programs.
557 continue
558 }
559 p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
560 default:
561 p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
562 }
563 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
564 hint.addr = p
565 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
566 }
567 } else {
568 // On a 32-bit machine, we're much more concerned
569 // about keeping the usable heap contiguous.
570 // Hence:
571 //
572 // 1. We reserve space for all heapArenas up front so
573 // they don't get interleaved with the heap. They're
574 // ~258MB, so this isn't too bad. (We could reserve a
575 // smaller amount of space up front if this is a
576 // problem.)
577 //
578 // 2. We hint the heap to start right above the end of
579 // the binary so we have the best chance of keeping it
580 // contiguous.
581 //
582 // 3. We try to stake out a reasonably large initial
583 // heap reservation.
584
585 const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
586 meta := uintptr(sysReserve(nil, arenaMetaSize))
587 if meta != 0 {
588 mheap_.heapArenaAlloc.init(meta, arenaMetaSize, true)
589 }
590
591 // We want to start the arena low, but if we're linked
592 // against C code, it's possible global constructors
593 // have called malloc and adjusted the process' brk.
594 // Query the brk so we can avoid trying to map the
595 // region over it (which will cause the kernel to put
596 // the region somewhere else, likely at a high
597 // address).
598 procBrk := sbrk0()
599
600 // If we ask for the end of the data segment but the
601 // operating system requires a little more space
602 // before we can start allocating, it will give out a
603 // slightly higher pointer. Except QEMU, which is
604 // buggy, as usual: it won't adjust the pointer
605 // upward. So adjust it upward a little bit ourselves:
606 // 1/4 MB to get away from the running binary image.
607 p := getEnd()
608 if p < procBrk {
609 p = procBrk
610 }
611 if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
612 p = mheap_.heapArenaAlloc.end
613 }
614 p = alignUp(p+(256<<10), heapArenaBytes)
615 // Because we're worried about fragmentation on
616 // 32-bit, we try to make a large initial reservation.
617 arenaSizes := [...]uintptr{
618 512 << 20,
619 256 << 20,
620 128 << 20,
621 }
622 for _, arenaSize := range &arenaSizes {
623 a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes)
624 if a != nil {
625 mheap_.arena.init(uintptr(a), size, false)
626 p = mheap_.arena.end // For hint below
627 break
628 }
629 }
630 hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
631 hint.addr = p
632 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
633 }
634 }
635
636 // sysAlloc allocates heap arena space for at least n bytes. The
637 // returned pointer is always heapArenaBytes-aligned and backed by
638 // h.arenas metadata. The returned size is always a multiple of
639 // heapArenaBytes. sysAlloc returns nil on failure.
640 // There is no corresponding free function.
641 //
642 // sysAlloc returns a memory region in the Reserved state. This region must
643 // be transitioned to Prepared and then Ready before use.
644 //
645 // h must be locked.
646 func (h *mheap) sysAlloc(n uintptr) (v unsafe.Pointer, size uintptr) {
647 assertLockHeld(&h.lock)
648
649 n = alignUp(n, heapArenaBytes)
650
651 // First, try the arena pre-reservation.
652 v = h.arena.alloc(n, heapArenaBytes, &memstats.heap_sys)
653 if v != nil {
654 size = n
655 goto mapped
656 }
657
658 // Try to grow the heap at a hint address.
659 for h.arenaHints != nil {
660 hint := h.arenaHints
661 p := hint.addr
662 if hint.down {
663 p -= n
664 }
665 if p+n < p {
666 // We can't use this, so don't ask.
667 v = nil
668 } else if arenaIndex(p+n-1) >= 1<<arenaBits {
669 // Outside addressable heap. Can't use.
670 v = nil
671 } else {
672 v = sysReserve(unsafe.Pointer(p), n)
673 }
674 if p == uintptr(v) {
675 // Success. Update the hint.
676 if !hint.down {
677 p += n
678 }
679 hint.addr = p
680 size = n
681 break
682 }
683 // Failed. Discard this hint and try the next.
684 //
685 // TODO: This would be cleaner if sysReserve could be
686 // told to only return the requested address. In
687 // particular, this is already how Windows behaves, so
688 // it would simplify things there.
689 if v != nil {
690 sysFree(v, n, nil)
691 }
692 h.arenaHints = hint.next
693 h.arenaHintAlloc.free(unsafe.Pointer(hint))
694 }
695
696 if size == 0 {
697 if raceenabled {
698 // The race detector assumes the heap lives in
699 // [0x00c000000000, 0x00e000000000), but we
700 // just ran out of hints in this region. Give
701 // a nice failure.
702 throw("too many address space collisions for -race mode")
703 }
704
705 // All of the hints failed, so we'll take any
706 // (sufficiently aligned) address the kernel will give
707 // us.
708 v, size = sysReserveAligned(nil, n, heapArenaBytes)
709 if v == nil {
710 return nil, 0
711 }
712
713 // Create new hints for extending this region.
714 hint := (*arenaHint)(h.arenaHintAlloc.alloc())
715 hint.addr, hint.down = uintptr(v), true
716 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
717 hint = (*arenaHint)(h.arenaHintAlloc.alloc())
718 hint.addr = uintptr(v) + size
719 hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
720 }
721
722 // Check for bad pointers or pointers we can't use.
723 {
724 var bad string
725 p := uintptr(v)
726 if p+size < p {
727 bad = "region exceeds uintptr range"
728 } else if arenaIndex(p) >= 1<<arenaBits {
729 bad = "base outside usable address space"
730 } else if arenaIndex(p+size-1) >= 1<<arenaBits {
731 bad = "end outside usable address space"
732 }
733 if bad != "" {
734 // This should be impossible on most architectures,
735 // but it would be really confusing to debug.
736 print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
737 throw("memory reservation exceeds address space limit")
738 }
739 }
740
741 if uintptr(v)&(heapArenaBytes-1) != 0 {
742 throw("misrounded allocation in sysAlloc")
743 }
744
745 mapped:
746 // Create arena metadata.
747 for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
748 l2 := h.arenas[ri.l1()]
749 if l2 == nil {
750 // Allocate an L2 arena map.
751 l2 = (*[1 << arenaL2Bits]*heapArena)(persistentalloc(unsafe.Sizeof(*l2), goarch.PtrSize, nil))
752 if l2 == nil {
753 throw("out of memory allocating heap arena map")
754 }
755 atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
756 }
757
758 if l2[ri.l2()] != nil {
759 throw("arena already initialized")
760 }
761 var r *heapArena
762 r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
763 if r == nil {
764 r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), goarch.PtrSize, &memstats.gcMiscSys))
765 if r == nil {
766 throw("out of memory allocating heap arena metadata")
767 }
768 }
769
770 // Add the arena to the arenas list.
771 if len(h.allArenas) == cap(h.allArenas) {
772 size := 2 * uintptr(cap(h.allArenas)) * goarch.PtrSize
773 if size == 0 {
774 size = physPageSize
775 }
776 newArray := (*notInHeap)(persistentalloc(size, goarch.PtrSize, &memstats.gcMiscSys))
777 if newArray == nil {
778 throw("out of memory allocating allArenas")
779 }
780 oldSlice := h.allArenas
781 *(*notInHeapSlice)(unsafe.Pointer(&h.allArenas)) = notInHeapSlice{newArray, len(h.allArenas), int(size / goarch.PtrSize)}
782 copy(h.allArenas, oldSlice)
783 // Do not free the old backing array because
784 // there may be concurrent readers. Since we
785 // double the array each time, this can lead
786 // to at most 2x waste.
787 }
788 h.allArenas = h.allArenas[:len(h.allArenas)+1]
789 h.allArenas[len(h.allArenas)-1] = ri
790
791 // Store atomically just in case an object from the
792 // new heap arena becomes visible before the heap lock
793 // is released (which shouldn't happen, but there's
794 // little downside to this).
795 atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
796 }
797
798 // Tell the race detector about the new heap memory.
799 if raceenabled {
800 racemapshadow(v, size)
801 }
802
803 return
804 }
805
806 // sysReserveAligned is like sysReserve, but the returned pointer is
807 // aligned to align bytes. It may reserve either n or n+align bytes,
808 // so it returns the size that was reserved.
809 func sysReserveAligned(v unsafe.Pointer, size, align uintptr) (unsafe.Pointer, uintptr) {
810 // Since the alignment is rather large in uses of this
811 // function, we're not likely to get it by chance, so we ask
812 // for a larger region and remove the parts we don't need.
813 retries := 0
814 retry:
815 p := uintptr(sysReserve(v, size+align))
816 switch {
817 case p == 0:
818 return nil, 0
819 case p&(align-1) == 0:
820 // We got lucky and got an aligned region, so we can
821 // use the whole thing.
822 return unsafe.Pointer(p), size + align
823 case GOOS == "windows":
824 // On Windows we can't release pieces of a
825 // reservation, so we release the whole thing and
826 // re-reserve the aligned sub-region. This may race,
827 // so we may have to try again.
828 sysFree(unsafe.Pointer(p), size+align, nil)
829 p = alignUp(p, align)
830 p2 := sysReserve(unsafe.Pointer(p), size)
831 if p != uintptr(p2) {
832 // Must have raced. Try again.
833 sysFree(p2, size, nil)
834 if retries++; retries == 100 {
835 throw("failed to allocate aligned heap memory; too many retries")
836 }
837 goto retry
838 }
839 // Success.
840 return p2, size
841 default:
842 // Trim off the unaligned parts.
843 pAligned := alignUp(p, align)
844 sysFree(unsafe.Pointer(p), pAligned-p, nil)
845 end := pAligned + size
846 endLen := (p + size + align) - end
847 if endLen > 0 {
848 sysFree(unsafe.Pointer(end), endLen, nil)
849 }
850 return unsafe.Pointer(pAligned), size
851 }
852 }
853
854 // base address for all 0-byte allocations
855 var zerobase uintptr
856
857 // nextFreeFast returns the next free object if one is quickly available.
858 // Otherwise it returns 0.
859 func nextFreeFast(s *mspan) gclinkptr {
860 theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
861 if theBit < 64 {
862 result := s.freeindex + uintptr(theBit)
863 if result < s.nelems {
864 freeidx := result + 1
865 if freeidx%64 == 0 && freeidx != s.nelems {
866 return 0
867 }
868 s.allocCache >>= uint(theBit + 1)
869 s.freeindex = freeidx
870 s.allocCount++
871 return gclinkptr(result*s.elemsize + s.base())
872 }
873 }
874 return 0
875 }
876
877 // nextFree returns the next free object from the cached span if one is available.
878 // Otherwise it refills the cache with a span with an available object and
879 // returns that object along with a flag indicating that this was a heavy
880 // weight allocation. If it is a heavy weight allocation the caller must
881 // determine whether a new GC cycle needs to be started or if the GC is active
882 // whether this goroutine needs to assist the GC.
883 //
884 // Must run in a non-preemptible context since otherwise the owner of
885 // c could change.
886 func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
887 s = c.alloc[spc]
888 shouldhelpgc = false
889 freeIndex := s.nextFreeIndex()
890 if freeIndex == s.nelems {
891 // The span is full.
892 if uintptr(s.allocCount) != s.nelems {
893 println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
894 throw("s.allocCount != s.nelems && freeIndex == s.nelems")
895 }
896 c.refill(spc)
897 shouldhelpgc = true
898 s = c.alloc[spc]
899
900 freeIndex = s.nextFreeIndex()
901 }
902
903 if freeIndex >= s.nelems {
904 throw("freeIndex is not valid")
905 }
906
907 v = gclinkptr(freeIndex*s.elemsize + s.base())
908 s.allocCount++
909 if uintptr(s.allocCount) > s.nelems {
910 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
911 throw("s.allocCount > s.nelems")
912 }
913 return
914 }
915
916 // Allocate an object of size bytes.
917 // Small objects are allocated from the per-P cache's free lists.
918 // Large objects (> 32 kB) are allocated straight from the heap.
919 func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
920 if gcphase == _GCmarktermination {
921 throw("mallocgc called with gcphase == _GCmarktermination")
922 }
923
924 if size == 0 {
925 return unsafe.Pointer(&zerobase)
926 }
927 userSize := size
928 if asanenabled {
929 // Refer to ASAN runtime library, the malloc() function allocates extra memory,
930 // the redzone, around the user requested memory region. And the redzones are marked
931 // as unaddressable. We perform the same operations in Go to detect the overflows or
932 // underflows.
933 size += computeRZlog(size)
934 }
935
936 if debug.malloc {
937 if debug.sbrk != 0 {
938 align := uintptr(16)
939 if typ != nil {
940 // TODO(austin): This should be just
941 // align = uintptr(typ.align)
942 // but that's only 4 on 32-bit platforms,
943 // even if there's a uint64 field in typ (see #599).
944 // This causes 64-bit atomic accesses to panic.
945 // Hence, we use stricter alignment that matches
946 // the normal allocator better.
947 if size&7 == 0 {
948 align = 8
949 } else if size&3 == 0 {
950 align = 4
951 } else if size&1 == 0 {
952 align = 2
953 } else {
954 align = 1
955 }
956 }
957 return persistentalloc(size, align, &memstats.other_sys)
958 }
959
960 if inittrace.active && inittrace.id == getg().goid {
961 // Init functions are executed sequentially in a single goroutine.
962 inittrace.allocs += 1
963 }
964 }
965
966 // When using gccgo, when a cgo or SWIG function has an
967 // interface return type and the function returns a
968 // non-pointer, memory allocation occurs after syscall.Cgocall
969 // but before syscall.CgocallDone. Treat this allocation as a
970 // callback.
971 incallback := false
972 if gp := getg(); gp.m.p == 0 && gp.m.ncgo > 0 {
973 exitsyscall()
974 incallback = true
975 }
976
977 // assistG is the G to charge for this allocation, or nil if
978 // GC is not currently active.
979 var assistG *g
980 if gcBlackenEnabled != 0 {
981 // Charge the current user G for this allocation.
982 assistG = getg()
983 if assistG.m.curg != nil {
984 assistG = assistG.m.curg
985 }
986 // Charge the allocation against the G. We'll account
987 // for internal fragmentation at the end of mallocgc.
988 assistG.gcAssistBytes -= int64(size)
989
990 if assistG.gcAssistBytes < 0 {
991 // This G is in debt. Assist the GC to correct
992 // this before allocating. This must happen
993 // before disabling preemption.
994 gcAssistAlloc(assistG)
995 }
996 }
997
998 // Set mp.mallocing to keep from being preempted by GC.
999 mp := acquirem()
1000 if mp.mallocing != 0 {
1001 throw("malloc deadlock")
1002 }
1003 if mp.gsignal == getg() {
1004 throw("malloc during signal")
1005 }
1006 mp.mallocing = 1
1007
1008 shouldhelpgc := false
1009 dataSize := userSize
1010 c := getMCache(mp)
1011 if c == nil {
1012 throw("mallocgc called without a P or outside bootstrapping")
1013 }
1014 var span *mspan
1015 var x unsafe.Pointer
1016 noscan := typ == nil || typ.ptrdata == 0
1017 // In some cases block zeroing can profitably (for latency reduction purposes)
1018 // be delayed till preemption is possible; delayedZeroing tracks that state.
1019 delayedZeroing := false
1020 if size <= maxSmallSize {
1021 if noscan && size < maxTinySize {
1022 // Tiny allocator.
1023 //
1024 // Tiny allocator combines several tiny allocation requests
1025 // into a single memory block. The resulting memory block
1026 // is freed when all subobjects are unreachable. The subobjects
1027 // must be noscan (don't have pointers), this ensures that
1028 // the amount of potentially wasted memory is bounded.
1029 //
1030 // Size of the memory block used for combining (maxTinySize) is tunable.
1031 // Current setting is 16 bytes, which relates to 2x worst case memory
1032 // wastage (when all but one subobjects are unreachable).
1033 // 8 bytes would result in no wastage at all, but provides less
1034 // opportunities for combining.
1035 // 32 bytes provides more opportunities for combining,
1036 // but can lead to 4x worst case wastage.
1037 // The best case winning is 8x regardless of block size.
1038 //
1039 // Objects obtained from tiny allocator must not be freed explicitly.
1040 // So when an object will be freed explicitly, we ensure that
1041 // its size >= maxTinySize.
1042 //
1043 // SetFinalizer has a special case for objects potentially coming
1044 // from tiny allocator, it such case it allows to set finalizers
1045 // for an inner byte of a memory block.
1046 //
1047 // The main targets of tiny allocator are small strings and
1048 // standalone escaping variables. On a json benchmark
1049 // the allocator reduces number of allocations by ~12% and
1050 // reduces heap size by ~20%.
1051 off := c.tinyoffset
1052 // Align tiny pointer for required (conservative) alignment.
1053 if size&7 == 0 {
1054 off = alignUp(off, 8)
1055 } else if goarch.PtrSize == 4 && size == 12 {
1056 // Conservatively align 12-byte objects to 8 bytes on 32-bit
1057 // systems so that objects whose first field is a 64-bit
1058 // value is aligned to 8 bytes and does not cause a fault on
1059 // atomic access. See issue 37262.
1060 // TODO(mknyszek): Remove this workaround if/when issue 36606
1061 // is resolved.
1062 off = alignUp(off, 8)
1063 } else if size&3 == 0 {
1064 off = alignUp(off, 4)
1065 } else if size&1 == 0 {
1066 off = alignUp(off, 2)
1067 }
1068 if off+size <= maxTinySize && c.tiny != 0 {
1069 // The object fits into existing tiny block.
1070 x = unsafe.Pointer(c.tiny + off)
1071 c.tinyoffset = off + size
1072 c.tinyAllocs++
1073 mp.mallocing = 0
1074 releasem(mp)
1075 if incallback {
1076 entersyscall()
1077 }
1078 return x
1079 }
1080 // Allocate a new maxTinySize block.
1081 span = c.alloc[tinySpanClass]
1082 v := nextFreeFast(span)
1083 if v == 0 {
1084 v, span, shouldhelpgc = c.nextFree(tinySpanClass)
1085 }
1086 x = unsafe.Pointer(v)
1087 (*[2]uint64)(x)[0] = 0
1088 (*[2]uint64)(x)[1] = 0
1089 // See if we need to replace the existing tiny block with the new one
1090 // based on amount of remaining free space.
1091 if !raceenabled && (size < c.tinyoffset || c.tiny == 0) {
1092 // Note: disabled when race detector is on, see comment near end of this function.
1093 c.tiny = uintptr(x)
1094 c.tinyoffset = size
1095 }
1096 size = maxTinySize
1097 } else {
1098 var sizeclass uint8
1099 if size <= smallSizeMax-8 {
1100 sizeclass = size_to_class8[divRoundUp(size, smallSizeDiv)]
1101 } else {
1102 sizeclass = size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)]
1103 }
1104 size = uintptr(class_to_size[sizeclass])
1105 spc := makeSpanClass(sizeclass, noscan)
1106 span = c.alloc[spc]
1107 v := nextFreeFast(span)
1108 if v == 0 {
1109 v, span, shouldhelpgc = c.nextFree(spc)
1110 }
1111 x = unsafe.Pointer(v)
1112 if needzero && span.needzero != 0 {
1113 memclrNoHeapPointers(unsafe.Pointer(v), size)
1114 }
1115 }
1116 } else {
1117 shouldhelpgc = true
1118 // For large allocations, keep track of zeroed state so that
1119 // bulk zeroing can be happen later in a preemptible context.
1120 span = c.allocLarge(size, noscan)
1121 span.freeindex = 1
1122 span.allocCount = 1
1123 size = span.elemsize
1124 x = unsafe.Pointer(span.base())
1125 if needzero && span.needzero != 0 {
1126 if noscan {
1127 delayedZeroing = true
1128 } else {
1129 memclrNoHeapPointers(x, size)
1130 // We've in theory cleared almost the whole span here,
1131 // and could take the extra step of actually clearing
1132 // the whole thing. However, don't. Any GC bits for the
1133 // uncleared parts will be zero, and it's just going to
1134 // be needzero = 1 once freed anyway.
1135 }
1136 }
1137 }
1138
1139 var scanSize uintptr
1140 if !noscan {
1141 heapBitsSetType(uintptr(x), size, dataSize, typ)
1142 if dataSize > typ.size {
1143 // Array allocation. If there are any
1144 // pointers, GC has to scan to the last
1145 // element.
1146 if typ.ptrdata != 0 {
1147 scanSize = dataSize - typ.size + typ.ptrdata
1148 }
1149 } else {
1150 scanSize = typ.ptrdata
1151 }
1152 c.scanAlloc += scanSize
1153 }
1154
1155 // Ensure that the stores above that initialize x to
1156 // type-safe memory and set the heap bits occur before
1157 // the caller can make x observable to the garbage
1158 // collector. Otherwise, on weakly ordered machines,
1159 // the garbage collector could follow a pointer to x,
1160 // but see uninitialized memory or stale heap bits.
1161 publicationBarrier()
1162
1163 // Allocate black during GC.
1164 // All slots hold nil so no scanning is needed.
1165 // This may be racing with GC so do it atomically if there can be
1166 // a race marking the bit.
1167 if gcphase != _GCoff {
1168 gcmarknewobject(span, uintptr(x), size, scanSize)
1169 }
1170
1171 if raceenabled {
1172 racemalloc(x, size)
1173 }
1174
1175 if msanenabled {
1176 msanmalloc(x, size)
1177 }
1178
1179 if asanenabled {
1180 // We should only read/write the memory with the size asked by the user.
1181 // The rest of the allocated memory should be poisoned, so that we can report
1182 // errors when accessing poisoned memory.
1183 // The allocated memory is larger than required userSize, it will also include
1184 // redzone and some other padding bytes.
1185 rzBeg := unsafe.Add(x, userSize)
1186 asanpoison(rzBeg, size-userSize)
1187 asanunpoison(x, userSize)
1188 }
1189
1190 if rate := MemProfileRate; rate > 0 {
1191 // Note cache c only valid while m acquired; see #47302
1192 if rate != 1 && size < c.nextSample {
1193 c.nextSample -= size
1194 } else {
1195 profilealloc(mp, x, size)
1196 }
1197 }
1198 mp.mallocing = 0
1199 releasem(mp)
1200
1201 // Pointerfree data can be zeroed late in a context where preemption can occur.
1202 // x will keep the memory alive.
1203 if delayedZeroing {
1204 if !noscan {
1205 throw("delayed zeroing on data that may contain pointers")
1206 }
1207 memclrNoHeapPointersChunked(size, x) // This is a possible preemption point: see #47302
1208 }
1209
1210 if debug.malloc {
1211 if debug.allocfreetrace != 0 {
1212 tracealloc(x, size, typ)
1213 }
1214
1215 if inittrace.active && inittrace.id == getg().goid {
1216 // Init functions are executed sequentially in a single goroutine.
1217 inittrace.bytes += uint64(size)
1218 }
1219 }
1220
1221 if assistG != nil {
1222 // Account for internal fragmentation in the assist
1223 // debt now that we know it.
1224 assistG.gcAssistBytes -= int64(size - dataSize)
1225 }
1226
1227 if shouldhelpgc {
1228 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
1229 gcStart(t)
1230 }
1231 }
1232
1233 if raceenabled && noscan && dataSize < maxTinySize {
1234 // Pad tinysize allocations so they are aligned with the end
1235 // of the tinyalloc region. This ensures that any arithmetic
1236 // that goes off the top end of the object will be detectable
1237 // by checkptr (issue 38872).
1238 // Note that we disable tinyalloc when raceenabled for this to work.
1239 // TODO: This padding is only performed when the race detector
1240 // is enabled. It would be nice to enable it if any package
1241 // was compiled with checkptr, but there's no easy way to
1242 // detect that (especially at compile time).
1243 // TODO: enable this padding for all allocations, not just
1244 // tinyalloc ones. It's tricky because of pointer maps.
1245 // Maybe just all noscan objects?
1246 x = add(x, size-dataSize)
1247 }
1248
1249 // Check preemption, since unlike gc we don't check on every call.
1250 if getg().preempt {
1251 checkPreempt()
1252 }
1253
1254 if incallback {
1255 entersyscall()
1256 }
1257
1258 return x
1259 }
1260
1261 // memclrNoHeapPointersChunked repeatedly calls memclrNoHeapPointers
1262 // on chunks of the buffer to be zeroed, with opportunities for preemption
1263 // along the way. memclrNoHeapPointers contains no safepoints and also
1264 // cannot be preemptively scheduled, so this provides a still-efficient
1265 // block copy that can also be preempted on a reasonable granularity.
1266 //
1267 // Use this with care; if the data being cleared is tagged to contain
1268 // pointers, this allows the GC to run before it is all cleared.
1269 func memclrNoHeapPointersChunked(size uintptr, x unsafe.Pointer) {
1270 v := uintptr(x)
1271 // got this from benchmarking. 128k is too small, 512k is too large.
1272 const chunkBytes = 256 * 1024
1273 vsize := v + size
1274 for voff := v; voff < vsize; voff = voff + chunkBytes {
1275 if getg().preempt {
1276 // may hold locks, e.g., profiling
1277 goschedguarded()
1278 }
1279 // clear min(avail, lump) bytes
1280 n := vsize - voff
1281 if n > chunkBytes {
1282 n = chunkBytes
1283 }
1284 memclrNoHeapPointers(unsafe.Pointer(voff), n)
1285 }
1286 }
1287
1288 // implementation of new builtin
1289 // compiler (both frontend and SSA backend) knows the signature
1290 // of this function
1291 func newobject(typ *_type) unsafe.Pointer {
1292 return mallocgc(typ.size, typ, true)
1293 }
1294
1295 //go:linkname reflect_unsafe_New reflect.unsafe__New
1296 func reflect_unsafe_New(typ *_type) unsafe.Pointer {
1297 return mallocgc(typ.size, typ, true)
1298 }
1299
1300 //go:linkname reflectlite_unsafe_New internal_1reflectlite.unsafe__New
1301 func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
1302 return mallocgc(typ.size, typ, true)
1303 }
1304
1305 // newarray allocates an array of n elements of type typ.
1306 func newarray(typ *_type, n int) unsafe.Pointer {
1307 if n == 1 {
1308 return mallocgc(typ.size, typ, true)
1309 }
1310 mem, overflow := math.MulUintptr(typ.size, uintptr(n))
1311 if overflow || mem > maxAlloc || n < 0 {
1312 panic(plainError("runtime: allocation size out of range"))
1313 }
1314 return mallocgc(mem, typ, true)
1315 }
1316
1317 //go:linkname reflect_unsafe_NewArray reflect.unsafe__NewArray
1318 func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
1319 return newarray(typ, n)
1320 }
1321
1322 func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
1323 c := getMCache(mp)
1324 if c == nil {
1325 throw("profilealloc called without a P or outside bootstrapping")
1326 }
1327 c.nextSample = nextSample()
1328 mProf_Malloc(x, size)
1329 }
1330
1331 // nextSample returns the next sampling point for heap profiling. The goal is
1332 // to sample allocations on average every MemProfileRate bytes, but with a
1333 // completely random distribution over the allocation timeline; this
1334 // corresponds to a Poisson process with parameter MemProfileRate. In Poisson
1335 // processes, the distance between two samples follows the exponential
1336 // distribution (exp(MemProfileRate)), so the best return value is a random
1337 // number taken from an exponential distribution whose mean is MemProfileRate.
1338 func nextSample() uintptr {
1339 if MemProfileRate == 1 {
1340 // Callers assign our return value to
1341 // mcache.next_sample, but next_sample is not used
1342 // when the rate is 1. So avoid the math below and
1343 // just return something.
1344 return 0
1345 }
1346 if GOOS == "plan9" {
1347 // Plan 9 doesn't support floating point in note handler.
1348 if g := getg(); g == g.m.gsignal {
1349 return nextSampleNoFP()
1350 }
1351 }
1352
1353 return uintptr(fastexprand(MemProfileRate))
1354 }
1355
1356 // fastexprand returns a random number from an exponential distribution with
1357 // the specified mean.
1358 func fastexprand(mean int) int32 {
1359 // Avoid overflow. Maximum possible step is
1360 // -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
1361 switch {
1362 case mean > 0x7000000:
1363 mean = 0x7000000
1364 case mean == 0:
1365 return 0
1366 }
1367
1368 // Take a random sample of the exponential distribution exp(-mean*x).
1369 // The probability distribution function is mean*exp(-mean*x), so the CDF is
1370 // p = 1 - exp(-mean*x), so
1371 // q = 1 - p == exp(-mean*x)
1372 // log_e(q) = -mean*x
1373 // -log_e(q)/mean = x
1374 // x = -log_e(q) * mean
1375 // x = log_2(q) * (-log_e(2)) * mean ; Using log_2 for efficiency
1376 const randomBitCount = 26
1377 q := fastrandn(1<<randomBitCount) + 1
1378 qlog := fastlog2(float64(q)) - randomBitCount
1379 if qlog > 0 {
1380 qlog = 0
1381 }
1382 const minusLog2 = -0.6931471805599453 // -ln(2)
1383 return int32(qlog*(minusLog2*float64(mean))) + 1
1384 }
1385
1386 // nextSampleNoFP is similar to nextSample, but uses older,
1387 // simpler code to avoid floating point.
1388 func nextSampleNoFP() uintptr {
1389 // Set first allocation sample size.
1390 rate := MemProfileRate
1391 if rate > 0x3fffffff { // make 2*rate not overflow
1392 rate = 0x3fffffff
1393 }
1394 if rate != 0 {
1395 return uintptr(fastrandn(uint32(2 * rate)))
1396 }
1397 return 0
1398 }
1399
1400 type persistentAlloc struct {
1401 base *notInHeap
1402 off uintptr
1403 }
1404
1405 var globalAlloc struct {
1406 mutex
1407 persistentAlloc
1408 }
1409
1410 // persistentChunkSize is the number of bytes we allocate when we grow
1411 // a persistentAlloc.
1412 const persistentChunkSize = 256 << 10
1413
1414 // persistentChunks is a list of all the persistent chunks we have
1415 // allocated. The list is maintained through the first word in the
1416 // persistent chunk. This is updated atomically.
1417 var persistentChunks *notInHeap
1418
1419 // Wrapper around sysAlloc that can allocate small chunks.
1420 // There is no associated free operation.
1421 // Intended for things like function/type/debug-related persistent data.
1422 // If align is 0, uses default align (currently 8).
1423 // The returned memory will be zeroed.
1424 //
1425 // Consider marking persistentalloc'd types go:notinheap.
1426 func persistentalloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1427 var p *notInHeap
1428 systemstack(func() {
1429 p = persistentalloc1(size, align, sysStat)
1430 })
1431 return unsafe.Pointer(p)
1432 }
1433
1434 // Must run on system stack because stack growth can (re)invoke it.
1435 // See issue 9174.
1436 //go:systemstack
1437 func persistentalloc1(size, align uintptr, sysStat *sysMemStat) *notInHeap {
1438 const (
1439 maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
1440 )
1441
1442 if size == 0 {
1443 throw("persistentalloc: size == 0")
1444 }
1445 if align != 0 {
1446 if align&(align-1) != 0 {
1447 throw("persistentalloc: align is not a power of 2")
1448 }
1449 if align > _PageSize {
1450 throw("persistentalloc: align is too large")
1451 }
1452 } else {
1453 align = 8
1454 }
1455
1456 if size >= maxBlock {
1457 return (*notInHeap)(sysAlloc(size, sysStat))
1458 }
1459
1460 mp := acquirem()
1461 var persistent *persistentAlloc
1462 if mp != nil && mp.p != 0 {
1463 persistent = &mp.p.ptr().palloc
1464 } else {
1465 lock(&globalAlloc.mutex)
1466 persistent = &globalAlloc.persistentAlloc
1467 }
1468 persistent.off = alignUp(persistent.off, align)
1469 if persistent.off+size > persistentChunkSize || persistent.base == nil {
1470 persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys))
1471 if persistent.base == nil {
1472 if persistent == &globalAlloc.persistentAlloc {
1473 unlock(&globalAlloc.mutex)
1474 }
1475 throw("runtime: cannot allocate memory")
1476 }
1477
1478 // Add the new chunk to the persistentChunks list.
1479 for {
1480 chunks := uintptr(unsafe.Pointer(persistentChunks))
1481 *(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
1482 if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
1483 break
1484 }
1485 }
1486 persistent.off = alignUp(goarch.PtrSize, align)
1487 }
1488 p := persistent.base.add(persistent.off)
1489 persistent.off += size
1490 releasem(mp)
1491 if persistent == &globalAlloc.persistentAlloc {
1492 unlock(&globalAlloc.mutex)
1493 }
1494
1495 if sysStat != &memstats.other_sys {
1496 sysStat.add(int64(size))
1497 memstats.other_sys.add(-int64(size))
1498 }
1499 return p
1500 }
1501
1502 // inPersistentAlloc reports whether p points to memory allocated by
1503 // persistentalloc. This must be nosplit because it is called by the
1504 // cgo checker code, which is called by the write barrier code.
1505 //go:nosplit
1506 func inPersistentAlloc(p uintptr) bool {
1507 chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
1508 for chunk != 0 {
1509 if p >= chunk && p < chunk+persistentChunkSize {
1510 return true
1511 }
1512 chunk = *(*uintptr)(unsafe.Pointer(chunk))
1513 }
1514 return false
1515 }
1516
1517 // linearAlloc is a simple linear allocator that pre-reserves a region
1518 // of memory and then optionally maps that region into the Ready state
1519 // as needed.
1520 //
1521 // The caller is responsible for locking.
1522 type linearAlloc struct {
1523 next uintptr // next free byte
1524 mapped uintptr // one byte past end of mapped space
1525 end uintptr // end of reserved space
1526
1527 mapMemory bool // transition memory from Reserved to Ready if true
1528 }
1529
1530 func (l *linearAlloc) init(base, size uintptr, mapMemory bool) {
1531 if base+size < base {
1532 // Chop off the last byte. The runtime isn't prepared
1533 // to deal with situations where the bounds could overflow.
1534 // Leave that memory reserved, though, so we don't map it
1535 // later.
1536 size -= 1
1537 }
1538 l.next, l.mapped = base, base
1539 l.end = base + size
1540 l.mapMemory = mapMemory
1541 }
1542
1543 func (l *linearAlloc) alloc(size, align uintptr, sysStat *sysMemStat) unsafe.Pointer {
1544 p := alignUp(l.next, align)
1545 if p+size > l.end {
1546 return nil
1547 }
1548 l.next = p + size
1549 if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
1550 if l.mapMemory {
1551 // Transition from Reserved to Prepared to Ready.
1552 sysMap(unsafe.Pointer(l.mapped), pEnd-l.mapped, sysStat)
1553 sysUsed(unsafe.Pointer(l.mapped), pEnd-l.mapped)
1554 }
1555 l.mapped = pEnd
1556 }
1557 return unsafe.Pointer(p)
1558 }
1559
1560 // notInHeap is off-heap memory allocated by a lower-level allocator
1561 // like sysAlloc or persistentAlloc.
1562 //
1563 // In general, it's better to use real types marked as go:notinheap,
1564 // but this serves as a generic type for situations where that isn't
1565 // possible (like in the allocators).
1566 //
1567 // TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
1568 //
1569 //go:notinheap
1570 type notInHeap struct{}
1571
1572 func (p *notInHeap) add(bytes uintptr) *notInHeap {
1573 return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))
1574 }
1575
1576 // computeRZlog computes the size of the redzone.
1577 // Refer to the implementation of the compiler-rt.
1578 func computeRZlog(userSize uintptr) uintptr {
1579 switch {
1580 case userSize <= (64 - 16):
1581 return 16 << 0
1582 case userSize <= (128 - 32):
1583 return 16 << 1
1584 case userSize <= (512 - 64):
1585 return 16 << 2
1586 case userSize <= (4096 - 128):
1587 return 16 << 3
1588 case userSize <= (1<<14)-256:
1589 return 16 << 4
1590 case userSize <= (1<<15)-512:
1591 return 16 << 5
1592 case userSize <= (1<<16)-1024:
1593 return 16 << 6
1594 default:
1595 return 16 << 7
1596 }
1597 }