malloc.go 47.6 KB
Newer Older
1 2 3 4
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7
// Memory allocator.
//
// This was originally based on tcmalloc, but has diverged quite a bit.
Russ Cox's avatar
Russ Cox committed
8 9 10 11
// http://goog-perftools.sourceforge.net/doc/tcmalloc.html

// The main allocator works in runs of pages.
// Small allocation sizes (up to and including 32 kB) are
12 13
// rounded to one of about 70 size classes, each of which
// has its own free set of objects of exactly that size.
Russ Cox's avatar
Russ Cox committed
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.
Russ Cox's avatar
Russ Cox committed
16 17 18
//
// The allocator's data structures are:
//
19
//	fixalloc: a free-list allocator for fixed-size off-heap objects,
Russ Cox's avatar
Russ Cox committed
20
//		used to manage storage used by the allocator.
21 22 23 24 25
//	mheap: the malloc heap, managed at page (8192-byte) granularity.
//	mspan: a run of pages managed by the mheap.
//	mcentral: collects all spans of a given size class.
//	mcache: a per-P cache of mspans with free space.
//	mstats: allocation statistics.
Russ Cox's avatar
Russ Cox committed
26 27 28 29
//
// Allocating a small object proceeds up a hierarchy of caches:
//
//	1. Round the size up to one of the small size classes
30 31 32
//	   and look in the corresponding mspan in this P's mcache.
//	   Scan the mspan's free bitmap to find a free slot.
//	   If there is a free slot, allocate it.
Russ Cox's avatar
Russ Cox committed
33 34
//	   This can all be done without acquiring a lock.
//
35 36 37 38 39
//	2. If the mspan has no free slots, obtain a new mspan
//	   from the mcentral's list of mspans of the required size
//	   class that have free space.
//	   Obtaining a whole span amortizes the cost of locking
//	   the mcentral.
Russ Cox's avatar
Russ Cox committed
40
//
41 42
//	3. If the mcentral's mspan list is empty, obtain a run
//	   of pages from the mheap to use for the mspan.
Russ Cox's avatar
Russ Cox committed
43
//
44
//	4. If the mheap is empty or has no page runs large enough,
Russ Cox's avatar
Russ Cox committed
45
//	   allocate a new group of pages (at least 1MB) from the
46
//	   operating system. Allocating a large run of pages
Russ Cox's avatar
Russ Cox committed
47 48
//	   amortizes the cost of talking to the operating system.
//
49 50 51 52 53
// Sweeping an mspan and freeing objects on it proceeds up a similar
// hierarchy:
//
//	1. If the mspan is being swept in response to allocation, it
//	   is returned to the mcache to satisfy the allocation.
Russ Cox's avatar
Russ Cox committed
54
//
55 56 57
//	2. Otherwise, if the mspan still has allocated objects in it,
//	   it is placed on the mcentral free list for the mspan's size
//	   class.
Russ Cox's avatar
Russ Cox committed
58
//
59 60 61 62
//	3. Otherwise, if all objects in the mspan are free, the mspan
//	   is now "idle", so it is returned to the mheap and no longer
//	   has a size class.
//	   This may coalesce it with adjacent idle mspans.
Russ Cox's avatar
Russ Cox committed
63
//
64 65
//	4. If an mspan remains idle for long enough, return its pages
//	   to the operating system.
Russ Cox's avatar
Russ Cox committed
66
//
67 68
// Allocating and freeing a large object uses the mheap
// directly, bypassing the mcache and mcentral.
Russ Cox's avatar
Russ Cox committed
69
//
70 71 72
// Free object slots in an mspan are zeroed only if mspan.needzero is
// false. If needzero is true, objects are zeroed as they are
// allocated. There are various benefits to delaying zeroing this way:
Russ Cox's avatar
Russ Cox committed
73
//
74
//	1. Stack frame allocation can avoid zeroing altogether.
Russ Cox's avatar
Russ Cox committed
75
//
76 77
//	2. It exhibits better temporal locality, since the program is
//	   probably about to write to the memory.
Russ Cox's avatar
Russ Cox committed
78
//
79
//	3. We don't zero pages that never get reused.
Russ Cox's avatar
Russ Cox committed
80

81 82 83 84 85 86 87 88 89 90 91 92
// Virtual memory layout
//
// The heap consists of a set of arenas, which are 64MB on 64-bit and
// 4MB on 32-bit (heapArenaBytes). Each arena's start address is also
// aligned to the arena size.
//
// Each arena has an associated heapArena object that stores the
// metadata for that arena: the heap bitmap for all words in the arena
// and the span map for all pages in the arena. heapArena objects are
// themselves allocated off-heap.
//
// Since arenas are aligned, the address space can be viewed as a
93
// series of arena frames. The arena map (mheap_.arenas) maps from
94
// arena frame number to *heapArena, or nil for parts of the address
95 96 97 98
// space not backed by the Go heap. The arena map is structured as a
// two-level array consisting of a "L1" arena map and many "L2" arena
// maps; however, since arenas are large, on many architectures, the
// arena map consists of a single, large L2 map.
99
//
100
// The arena map covers the entire possible address space, allowing
101 102 103 104
// the Go heap to use any part of the address space. The allocator
// attempts to keep arenas contiguous so that large spans (and hence
// large objects) can cross arenas.

105 106
package runtime

107
import (
108
	"runtime/internal/atomic"
109
	"runtime/internal/math"
110 111 112
	"runtime/internal/sys"
	"unsafe"
)
113 114

const (
115 116
	debugMalloc = false

117 118 119
	maxTinySize   = _TinySize
	tinySizeClass = _TinySizeClass
	maxSmallSize  = _MaxSmallSize
120

121 122 123
	pageShift = _PageShift
	pageSize  = _PageSize
	pageMask  = _PageMask
124 125 126
	// By construction, single page spans of the smallest object class
	// have the most objects per span.
	maxObjsPerSpan = pageSize / 8
127

128
	concurrentSweep = _ConcurrentSweep
129

130 131
	_PageSize = 1 << _PageShift
	_PageMask = _PageSize - 1
Russ Cox's avatar
Russ Cox committed
132 133 134 135 136 137

	// _64bit = 1 on 64-bit systems, 0 on 32-bit systems
	_64bit = 1 << (^uintptr(0) >> 63) / 2

	// Tiny allocator parameters, see "Tiny allocator" comment in malloc.go.
	_TinySize      = 16
138
	_TinySizeClass = int8(2)
Russ Cox's avatar
Russ Cox committed
139

140
	_FixAllocChunk = 16 << 10 // Chunk size for FixAlloc
Russ Cox's avatar
Russ Cox committed
141 142 143 144

	// Per-P, per order stack segment cache size.
	_StackCacheSize = 32 * 1024

145
	// Number of orders that get caching. Order 0 is FixedStack
Russ Cox's avatar
Russ Cox committed
146
	// and each successive order is twice as large.
147
	// We want to cache 2KB, 4KB, 8KB, and 16KB stacks. Larger stacks
Russ Cox's avatar
Russ Cox committed
148 149 150 151 152 153 154 155 156
	// will be allocated directly.
	// Since FixedStack is different on different systems, we
	// must vary NumStackOrders to keep the same maximum cached size.
	//   OS               | FixedStack | NumStackOrders
	//   -----------------+------------+---------------
	//   linux/darwin/bsd | 2KB        | 4
	//   windows/32       | 4KB        | 3
	//   windows/64       | 8KB        | 2
	//   plan9            | 4KB        | 3
157
	_NumStackOrders = 4 - sys.PtrSize/4*sys.GoosWindows - 1*sys.GoosPlan9
Russ Cox's avatar
Russ Cox committed
158

159 160 161
	// heapAddrBits is the number of bits in a heap address. On
	// amd64, addresses are sign-extended beyond heapAddrBits. On
	// other arches, they are zero-extended.
162
	//
163
	// On most 64-bit platforms, we limit this to 48 bits based on a
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	// combination of hardware and OS limitations.
	//
	// amd64 hardware limits addresses to 48 bits, sign-extended
	// to 64 bits. Addresses where the top 16 bits are not either
	// all 0 or all 1 are "non-canonical" and invalid. Because of
	// these "negative" addresses, we offset addresses by 1<<47
	// (arenaBaseOffset) on amd64 before computing indexes into
	// the heap arenas index. In 2017, amd64 hardware added
	// support for 57 bit addresses; however, currently only Linux
	// supports this extension and the kernel will never choose an
	// address above 1<<47 unless mmap is called with a hint
	// address above 1<<47 (which we never do).
	//
	// arm64 hardware (as of ARMv8) limits user addresses to 48
	// bits, in the range [0, 1<<48).
	//
	// ppc64, mips64, and s390x support arbitrary 64 bit addresses
181 182 183
	// in hardware. On Linux, Go leans on stricter OS limits. Based
	// on Linux's processor.h, the user address space is limited as
	// follows on 64-bit architectures:
184 185 186 187 188 189 190 191 192
	//
	// Architecture  Name              Maximum Value (exclusive)
	// ---------------------------------------------------------------------
	// amd64         TASK_SIZE_MAX     0x007ffffffff000 (47 bit addresses)
	// arm64         TASK_SIZE_64      0x01000000000000 (48 bit addresses)
	// ppc64{,le}    TASK_SIZE_USER64  0x00400000000000 (46 bit addresses)
	// mips64{,le}   TASK_SIZE64       0x00010000000000 (40 bit addresses)
	// s390x         TASK_SIZE         1<<64 (64 bit addresses)
	//
193 194 195 196 197 198
	// These limits may increase over time, but are currently at
	// most 48 bits except on s390x. On all architectures, Linux
	// starts placing mmap'd regions at addresses that are
	// significantly below 48 bits, so even if it's possible to
	// exceed Go's 48 bit limit, it's extremely unlikely in
	// practice.
199
	//
200 201 202 203
	// On aix/ppc64, the limits is increased to 1<<60 to accept addresses
	// returned by mmap syscall. These are in range:
	//  0x0a00000000000000 - 0x0afffffffffffff
	//
204 205 206 207
	// On 32-bit platforms, we accept the full 32-bit address
	// space because doing so is cheap.
	// mips32 only has access to the low 2GB of virtual memory, so
	// we further limit it to 31 bits.
208 209
	//
	// WebAssembly currently has a limit of 4GB linear memory.
210
	heapAddrBits = (_64bit*(1-sys.GoarchWasm)*(1-sys.GoosAix))*48 + (1-_64bit+sys.GoarchWasm)*(32-(sys.GoarchMips+sys.GoarchMipsle)) + 60*sys.GoosAix
211 212

	// maxAlloc is the maximum size of an allocation. On 64-bit,
213 214
	// it's theoretically possible to allocate 1<<heapAddrBits bytes. On
	// 32-bit, however, this is one less than 1<<32 because the
215 216
	// number of bytes in the address space doesn't actually fit
	// in a uintptr.
217
	maxAlloc = (1 << heapAddrBits) - (1-_64bit)*1
218

219 220 221
	// The number of bits in a heap address, the size of heap
	// arenas, and the L1 and L2 arena map sizes are related by
	//
222
	//   (1 << addr bits) = arena size * L1 entries * L2 entries
223 224 225
	//
	// Currently, we balance these as follows:
	//
226 227 228
	//       Platform  Addr bits  Arena size  L1 entries   L2 entries
	// --------------  ---------  ----------  ----------  -----------
	//       */64-bit         48        64MB           1    4M (32MB)
229
	//     aix/64-bit         60       256MB        4096    4M (32MB)
230 231 232
	// windows/64-bit         48         4MB          64    1M  (8MB)
	//       */32-bit         32         4MB           1  1024  (4KB)
	//     */mips(le)         31         4MB           1   512  (2KB)
233

234 235 236
	// heapArenaBytes is the size of a heap arena. The heap
	// consists of mappings of size heapArenaBytes, aligned to
	// heapArenaBytes. The initial heap mapping is one arena.
237
	//
238 239 240 241 242 243 244 245
	// This is currently 64MB on 64-bit non-Windows and 4MB on
	// 32-bit and on Windows. We use smaller arenas on Windows
	// because all committed memory is charged to the process,
	// even if it's not touched. Hence, for processes with small
	// heaps, the mapped arena space needs to be commensurate.
	// This is particularly important with the race detector,
	// since it significantly amplifies the cost of committed
	// memory.
246 247 248 249 250
	heapArenaBytes = 1 << logHeapArenaBytes

	// logHeapArenaBytes is log_2 of heapArenaBytes. For clarity,
	// prefer using heapArenaBytes where possible (we need the
	// constant to compute some other constants).
251
	logHeapArenaBytes = (6+20)*(_64bit*(1-sys.GoosWindows)*(1-sys.GoosAix)*(1-sys.GoarchWasm)) + (2+20)*(_64bit*sys.GoosWindows) + (2+20)*(1-_64bit) + (8+20)*sys.GoosAix + (2+20)*sys.GoarchWasm
252 253 254 255

	// heapArenaBitmapBytes is the size of each heap arena's bitmap.
	heapArenaBitmapBytes = heapArenaBytes / (sys.PtrSize * 8 / 2)

256 257
	pagesPerArena = heapArenaBytes / pageSize

258 259 260 261 262 263 264 265 266
	// arenaL1Bits is the number of bits of the arena number
	// covered by the first level arena map.
	//
	// This number should be small, since the first level arena
	// map requires PtrSize*(1<<arenaL1Bits) of space in the
	// binary's BSS. It can be zero, in which case the first level
	// index is effectively unused. There is a performance benefit
	// to this, since the generated code can be more efficient,
	// but comes at the cost of having a large L2 mapping.
267 268 269 270
	//
	// We use the L1 map on 64-bit Windows because the arena size
	// is small, but the address space is still 48 bits, and
	// there's a high cost to having a large L2.
271 272 273 274
	//
	// We use the L1 map on aix/ppc64 to keep the same L2 value
	// as on Linux.
	arenaL1Bits = 6*(_64bit*sys.GoosWindows) + 12*sys.GoosAix
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

	// arenaL2Bits is the number of bits of the arena number
	// covered by the second level arena index.
	//
	// The size of each arena map allocation is proportional to
	// 1<<arenaL2Bits, so it's important that this not be too
	// large. 48 bits leads to 32MB arena index allocations, which
	// is about the practical threshold.
	arenaL2Bits = heapAddrBits - logHeapArenaBytes - arenaL1Bits

	// arenaL1Shift is the number of bits to shift an arena frame
	// number by to compute an index into the first level arena map.
	arenaL1Shift = arenaL2Bits

	// arenaBits is the total bits in a combined arena map index.
	// This is split between the index into the L1 arena map and
	// the L2 arena map.
	arenaBits = arenaL1Bits + arenaL2Bits

294
	// arenaBaseOffset is the pointer value that corresponds to
295
	// index 0 in the heap arena map.
296 297 298 299 300 301 302 303 304
	//
	// On amd64, the address space is 48 bits, sign extended to 64
	// bits. This offset lets us handle "negative" addresses (or
	// high addresses if viewed as unsigned).
	//
	// On other platforms, the user address space is contiguous
	// and starts at 0, so no offset is necessary.
	arenaBaseOffset uintptr = sys.GoarchAmd64 * (1 << 47)

Russ Cox's avatar
Russ Cox committed
305 306
	// Max number of threads to run garbage collection.
	// 2, 3, and 4 are all plausible maximums depending
307
	// on the hardware details of the machine. The garbage
Russ Cox's avatar
Russ Cox committed
308 309 310
	// collector scales well to 32 cpus.
	_MaxGcproc = 32

311 312 313 314 315 316
	// minLegalPointer is the smallest possible legal pointer.
	// This is the smallest possible architectural page size,
	// since we assume that the first page is never mapped.
	//
	// This should agree with minZeroPage in the compiler.
	minLegalPointer uintptr = 4096
317
)
Russ Cox's avatar
Russ Cox committed
318

319 320 321 322 323 324 325 326
// physPageSize is the size in bytes of the OS's physical pages.
// Mapping and unmapping operations must be done at multiples of
// physPageSize.
//
// This must be set by the OS init code (typically in osinit) before
// mallocinit.
var physPageSize uintptr

327
// physHugePageSize is the size in bytes of the OS's default physical huge
328 329
// page size whose allocation is opaque to the application. It is assumed
// and verified to be a power of two.
330 331 332 333
//
// If set, this must be set by the OS init code (typically in osinit) before
// mallocinit. However, setting it at all is optional, and leaving the default
// value is always safe (though potentially less efficient).
334 335 336 337 338 339 340 341 342
//
// Since physHugePageSize is always assumed to be a power of two,
// physHugePageShift is defined as physHugePageSize == 1 << physHugePageShift.
// The purpose of physHugePageShift is to avoid doing divisions in
// performance critical functions.
var (
	physHugePageSize  uintptr
	physHugePageShift uint
)
343

344
// OS memory management abstraction layer
Russ Cox's avatar
Russ Cox committed
345
//
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
// Regions of the address space managed by the runtime may be in one of four
// states at any given time:
// 1) None - Unreserved and unmapped, the default state of any region.
// 2) Reserved - Owned by the runtime, but accessing it would cause a fault.
//               Does not count against the process' memory footprint.
// 3) Prepared - Reserved, intended not to be backed by physical memory (though
//               an OS may implement this lazily). Can transition efficiently to
//               Ready. Accessing memory in such a region is undefined (may
//               fault, may give back unexpected zeroes, etc.).
// 4) Ready - may be accessed safely.
//
// This set of states is more than is strictly necessary to support all the
// currently supported platforms. One could get by with just None, Reserved, and
// Ready. However, the Prepared state gives us flexibility for performance
// purposes. For example, on POSIX-y operating systems, Reserved is usually a
// private anonymous mmap'd region with PROT_NONE set, and to transition
// to Ready would require setting PROT_READ|PROT_WRITE. However the
// underspecification of Prepared lets us use just MADV_FREE to transition from
// Ready to Prepared. Thus with the Prepared state we can set the permission
// bits just once early on, we can efficiently tell the OS that it's free to
// take pages away from us when we don't strictly need them.
//
// For each OS there is a common set of helpers defined that transition
// memory regions between these states. The helpers are as follows:
Russ Cox's avatar
Russ Cox committed
370
//
371 372 373 374
// sysAlloc transitions an OS-chosen region of memory from None to Ready.
// More specifically, it obtains a large chunk of zeroed memory from the
// operating system, typically on the order of a hundred kilobytes
// or a megabyte. This memory is always immediately available for use.
Russ Cox's avatar
Russ Cox committed
375
//
376 377 378 379 380 381
// sysFree transitions a memory region from any state to None. Therefore, it
// returns memory unconditionally. It is used if an out-of-memory error has been
// detected midway through an allocation or to carve out an aligned section of
// the address space. It is okay if sysFree is a no-op only if sysReserve always
// returns a memory region aligned to the heap allocator's alignment
// restrictions.
Russ Cox's avatar
Russ Cox committed
382
//
383 384 385 386
// sysReserve transitions a memory region from None to Reserved. It reserves
// address space in such a way that it would cause a fatal fault upon access
// (either via permissions or not committing the memory). Such a reservation is
// thus never backed by physical memory.
Russ Cox's avatar
Russ Cox committed
387
// If the pointer passed to it is non-nil, the caller wants the
388
// reservation there, but sysReserve can still choose another
389
// location if that one is unavailable.
390
// NOTE: sysReserve returns OS-aligned memory, but the heap allocator
Russ Cox's avatar
Russ Cox committed
391
// may use larger alignment, so the caller must be careful to realign the
392 393 394 395
// memory obtained by sysReserve.
//
// sysMap transitions a memory region from Reserved to Prepared. It ensures the
// memory region can be efficiently transitioned to Ready.
Russ Cox's avatar
Russ Cox committed
396
//
397 398 399 400 401
// sysUsed transitions a memory region from Prepared to Ready. It notifies the
// operating system that the memory region is needed and ensures that the region
// may be safely accessed. This is typically a no-op on systems that don't have
// an explicit commit step and hard over-commit limits, but is critical on
// Windows, for example.
Russ Cox's avatar
Russ Cox committed
402
//
403 404 405 406 407 408 409 410 411
// sysUnused transitions a memory region from Ready to Prepared. It notifies the
// operating system that the physical pages backing this memory region are no
// longer needed and can be reused for other purposes. The contents of a
// sysUnused memory region are considered forfeit and the region must not be
// accessed again until sysUsed is called.
//
// sysFault transitions a memory region from Ready or Prepared to Reserved. It
// marks a region such that it will always fault if accessed. Used only for
// debugging the runtime.
Russ Cox's avatar
Russ Cox committed
412 413 414 415 416 417

func mallocinit() {
	if class_to_size[_TinySizeClass] != _TinySize {
		throw("bad TinySizeClass")
	}

418 419
	testdefersizes()

420 421 422 423 424 425
	if heapArenaBitmapBytes&(heapArenaBitmapBytes-1) != 0 {
		// heapBits expects modular arithmetic on bitmap
		// addresses to work.
		throw("heapArenaBitmapBytes not a power of 2")
	}

426 427 428 429 430
	// Copy class sizes out for statistics table.
	for i := range class_to_size {
		memstats.by_size[i].size = uint32(class_to_size[i])
	}

431 432 433 434 435
	// Check physPageSize.
	if physPageSize == 0 {
		// The OS init code failed to fetch the physical page size.
		throw("failed to get system page size")
	}
436 437 438
	if physPageSize < minPhysPageSize {
		print("system page size (", physPageSize, ") is smaller than minimum page size (", minPhysPageSize, ")\n")
		throw("bad system page size")
439
	}
440 441 442
	if physPageSize&(physPageSize-1) != 0 {
		print("system page size (", physPageSize, ") must be a power of 2\n")
		throw("bad system page size")
443
	}
444 445 446 447 448 449 450 451 452 453 454
	if physHugePageSize&(physHugePageSize-1) != 0 {
		print("system huge page size (", physHugePageSize, ") must be a power of 2\n")
		throw("bad system huge page size")
	}
	if physHugePageSize != 0 {
		// Since physHugePageSize is a power of 2, it suffices to increase
		// physHugePageShift until 1<<physHugePageShift == physHugePageSize.
		for 1<<physHugePageShift != physHugePageSize {
			physHugePageShift++
		}
	}
455

456 457 458 459
	// Initialize the heap.
	mheap_.init()
	_g_ := getg()
	_g_.m.mcache = allocmcache()
Russ Cox's avatar
Russ Cox committed
460

461
	// Create initial arena growth hints.
462
	if sys.PtrSize == 8 {
463 464
		// On a 64-bit machine, we pick the following hints
		// because:
Russ Cox's avatar
Russ Cox committed
465
		//
466 467 468 469 470 471 472 473 474 475 476 477 478 479
		// 1. Starting from the middle of the address space
		// makes it easier to grow out a contiguous range
		// without running in to some other mapping.
		//
		// 2. This makes Go heap addresses more easily
		// recognizable when debugging.
		//
		// 3. Stack scanning in gccgo is still conservative,
		// so it's important that addresses be distinguishable
		// from other data.
		//
		// Starting at 0x00c0 means that the valid memory addresses
		// will begin 0x00c0, 0x00c1, ...
		// In little-endian, that's c0 00, c1 00, ... None of those are valid
Russ Cox's avatar
Russ Cox committed
480
		// UTF-8 sequences, and they are otherwise as far away from
481 482
		// ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
		// addresses. An earlier attempt to use 0x11f8 caused out of memory errors
Russ Cox's avatar
Russ Cox committed
483 484
		// on OS X during thread allocations.  0x00c0 causes conflicts with
		// AddressSanitizer which reserves all memory up to 0x0100.
485
		// These choices reduce the odds of a conservative garbage collector
Russ Cox's avatar
Russ Cox committed
486 487
		// not collecting memory because some non-pointer block of memory
		// had a bit pattern that matched a memory address.
Russ Cox's avatar
Russ Cox committed
488
		//
489 490 491
		// However, on arm64, we ignore all this advice above and slam the
		// allocation at 0x40 << 32 because when using 4k pages with 3-level
		// translation buffers, the user address space is limited to 39 bits
492
		// On darwin/arm64, the address space is even smaller.
493 494
		// On AIX, mmaps starts at 0x0A00000000000000 for 64-bit.
		// processes.
495 496
		for i := 0x7f; i >= 0; i-- {
			var p uintptr
497 498 499 500
			switch {
			case GOARCH == "arm64" && GOOS == "darwin":
				p = uintptr(i)<<40 | uintptrMask&(0x0013<<28)
			case GOARCH == "arm64":
501
				p = uintptr(i)<<40 | uintptrMask&(0x0040<<32)
502 503 504 505 506 507 508
			case GOOS == "aix":
				if i == 0 {
					// We don't use addresses directly after 0x0A00000000000000
					// to avoid collisions with others mmaps done by non-go programs.
					continue
				}
				p = uintptr(i)<<40 | uintptrMask&(0xa0<<52)
509 510 511 512 513 514 515 516
			case raceenabled:
				// The TSAN runtime requires the heap
				// to be in the range [0x00c000000000,
				// 0x00e000000000).
				p = uintptr(i)<<32 | uintptrMask&(0x00c0<<32)
				if p >= uintptrMask&0x00e000000000 {
					continue
				}
517
			default:
518 519
				p = uintptr(i)<<40 | uintptrMask&(0x00c0<<32)
			}
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
			hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
			hint.addr = p
			hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
		}
	} else {
		// On a 32-bit machine, we're much more concerned
		// about keeping the usable heap contiguous.
		// Hence:
		//
		// 1. We reserve space for all heapArenas up front so
		// they don't get interleaved with the heap. They're
		// ~258MB, so this isn't too bad. (We could reserve a
		// smaller amount of space up front if this is a
		// problem.)
		//
		// 2. We hint the heap to start right above the end of
		// the binary so we have the best chance of keeping it
		// contiguous.
		//
		// 3. We try to stake out a reasonably large initial
		// heap reservation.

542
		const arenaMetaSize = (1 << arenaBits) * unsafe.Sizeof(heapArena{})
543
		meta := uintptr(sysReserve(nil, arenaMetaSize))
544 545
		if meta != 0 {
			mheap_.heapArenaAlloc.init(meta, arenaMetaSize)
Russ Cox's avatar
Russ Cox committed
546 547
		}

548 549 550 551
		// We want to start the arena low, but if we're linked
		// against C code, it's possible global constructors
		// have called malloc and adjusted the process' brk.
		// Query the brk so we can avoid trying to map the
552 553
		// region over it (which will cause the kernel to put
		// the region somewhere else, likely at a high
554 555 556
		// address).
		procBrk := sbrk0()

557 558 559 560 561 562 563 564 565 566 567 568 569 570
		// If we ask for the end of the data segment but the
		// operating system requires a little more space
		// before we can start allocating, it will give out a
		// slightly higher pointer. Except QEMU, which is
		// buggy, as usual: it won't adjust the pointer
		// upward. So adjust it upward a little bit ourselves:
		// 1/4 MB to get away from the running binary image.
		p := firstmoduledata.end
		if p < procBrk {
			p = procBrk
		}
		if mheap_.heapArenaAlloc.next <= p && p < mheap_.heapArenaAlloc.end {
			p = mheap_.heapArenaAlloc.end
		}
571
		p = alignUp(p+(256<<10), heapArenaBytes)
572 573
		// Because we're worried about fragmentation on
		// 32-bit, we try to make a large initial reservation.
Russ Cox's avatar
Russ Cox committed
574 575 576
		arenaSizes := []uintptr{
			512 << 20,
			256 << 20,
577
			128 << 20,
Russ Cox's avatar
Russ Cox committed
578 579
		}
		for _, arenaSize := range arenaSizes {
580
			a, size := sysReserveAligned(unsafe.Pointer(p), arenaSize, heapArenaBytes)
581 582 583
			if a != nil {
				mheap_.arena.init(uintptr(a), size)
				p = uintptr(a) + size // For hint below
Russ Cox's avatar
Russ Cox committed
584 585 586
				break
			}
		}
587 588 589
		hint := (*arenaHint)(mheap_.arenaHintAlloc.alloc())
		hint.addr = p
		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
590
	}
Russ Cox's avatar
Russ Cox committed
591 592
}

593 594 595 596
// sysAlloc allocates heap arena space for at least n bytes. The
// returned pointer is always heapArenaBytes-aligned and backed by
// h.arenas metadata. The returned size is always a multiple of
// heapArenaBytes. sysAlloc returns nil on failure.
597
// There is no corresponding free function.
598
//
599 600 601
// sysAlloc returns a memory region in the Prepared state. This region must
// be transitioned to Ready before use.
//
602 603
// h must be locked.
func (h *mheap) sysAlloc(n uintptr) (v unsafe.Pointer, size uintptr) {
604
	n = alignUp(n, heapArenaBytes)
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

	// First, try the arena pre-reservation.
	v = h.arena.alloc(n, heapArenaBytes, &memstats.heap_sys)
	if v != nil {
		size = n
		goto mapped
	}

	// Try to grow the heap at a hint address.
	for h.arenaHints != nil {
		hint := h.arenaHints
		p := hint.addr
		if hint.down {
			p -= n
		}
620
		if p+n < p {
621 622
			// We can't use this, so don't ask.
			v = nil
623
		} else if arenaIndex(p+n-1) >= 1<<arenaBits {
624 625
			// Outside addressable heap. Can't use.
			v = nil
626
		} else {
627
			v = sysReserve(unsafe.Pointer(p), n)
628 629 630 631 632
		}
		if p == uintptr(v) {
			// Success. Update the hint.
			if !hint.down {
				p += n
Russ Cox's avatar
Russ Cox committed
633
			}
634 635 636 637 638 639 640 641 642
			hint.addr = p
			size = n
			break
		}
		// Failed. Discard this hint and try the next.
		//
		// TODO: This would be cleaner if sysReserve could be
		// told to only return the requested address. In
		// particular, this is already how Windows behaves, so
643
		// it would simplify things there.
644 645
		if v != nil {
			sysFree(v, n, nil)
Russ Cox's avatar
Russ Cox committed
646
		}
647 648
		h.arenaHints = hint.next
		h.arenaHintAlloc.free(unsafe.Pointer(hint))
Russ Cox's avatar
Russ Cox committed
649 650
	}

651
	if size == 0 {
652 653 654 655 656 657 658 659
		if raceenabled {
			// The race detector assumes the heap lives in
			// [0x00c000000000, 0x00e000000000), but we
			// just ran out of hints in this region. Give
			// a nice failure.
			throw("too many address space collisions for -race mode")
		}

660 661 662
		// All of the hints failed, so we'll take any
		// (sufficiently aligned) address the kernel will give
		// us.
663
		v, size = sysReserveAligned(nil, n, heapArenaBytes)
664 665
		if v == nil {
			return nil, 0
666
		}
Russ Cox's avatar
Russ Cox committed
667

668 669 670 671 672 673 674
		// Create new hints for extending this region.
		hint := (*arenaHint)(h.arenaHintAlloc.alloc())
		hint.addr, hint.down = uintptr(v), true
		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
		hint = (*arenaHint)(h.arenaHintAlloc.alloc())
		hint.addr = uintptr(v) + size
		hint.next, mheap_.arenaHints = mheap_.arenaHints, hint
Russ Cox's avatar
Russ Cox committed
675 676
	}

677 678 679 680 681 682
	// Check for bad pointers or pointers we can't use.
	{
		var bad string
		p := uintptr(v)
		if p+size < p {
			bad = "region exceeds uintptr range"
683
		} else if arenaIndex(p) >= 1<<arenaBits {
684
			bad = "base outside usable address space"
685
		} else if arenaIndex(p+size-1) >= 1<<arenaBits {
686 687 688 689 690 691 692 693
			bad = "end outside usable address space"
		}
		if bad != "" {
			// This should be impossible on most architectures,
			// but it would be really confusing to debug.
			print("runtime: memory allocated by OS [", hex(p), ", ", hex(p+size), ") not in usable address space: ", bad, "\n")
			throw("memory reservation exceeds address space limit")
		}
Russ Cox's avatar
Russ Cox committed
694 695
	}

696 697
	if uintptr(v)&(heapArenaBytes-1) != 0 {
		throw("misrounded allocation in sysAlloc")
Russ Cox's avatar
Russ Cox committed
698 699
	}

700
	// Transition from Reserved to Prepared.
701
	sysMap(v, size, &memstats.heap_sys)
702 703 704

mapped:
	// Create arena metadata.
705
	for ri := arenaIndex(uintptr(v)); ri <= arenaIndex(uintptr(v)+size-1); ri++ {
706 707 708 709 710 711 712 713 714 715 716
		l2 := h.arenas[ri.l1()]
		if l2 == nil {
			// Allocate an L2 arena map.
			l2 = (*[1 << arenaL2Bits]*heapArena)(persistentalloc(unsafe.Sizeof(*l2), sys.PtrSize, nil))
			if l2 == nil {
				throw("out of memory allocating heap arena map")
			}
			atomic.StorepNoWB(unsafe.Pointer(&h.arenas[ri.l1()]), unsafe.Pointer(l2))
		}

		if l2[ri.l2()] != nil {
717 718 719 720 721 722 723 724 725 726 727
			throw("arena already initialized")
		}
		var r *heapArena
		r = (*heapArena)(h.heapArenaAlloc.alloc(unsafe.Sizeof(*r), sys.PtrSize, &memstats.gc_sys))
		if r == nil {
			r = (*heapArena)(persistentalloc(unsafe.Sizeof(*r), sys.PtrSize, &memstats.gc_sys))
			if r == nil {
				throw("out of memory allocating heap arena metadata")
			}
		}

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
		// Add the arena to the arenas list.
		if len(h.allArenas) == cap(h.allArenas) {
			size := 2 * uintptr(cap(h.allArenas)) * sys.PtrSize
			if size == 0 {
				size = physPageSize
			}
			newArray := (*notInHeap)(persistentalloc(size, sys.PtrSize, &memstats.gc_sys))
			if newArray == nil {
				throw("out of memory allocating allArenas")
			}
			oldSlice := h.allArenas
			*(*notInHeapSlice)(unsafe.Pointer(&h.allArenas)) = notInHeapSlice{newArray, len(h.allArenas), int(size / sys.PtrSize)}
			copy(h.allArenas, oldSlice)
			// Do not free the old backing array because
			// there may be concurrent readers. Since we
			// double the array each time, this can lead
			// to at most 2x waste.
		}
		h.allArenas = h.allArenas[:len(h.allArenas)+1]
		h.allArenas[len(h.allArenas)-1] = ri

749 750 751 752
		// Store atomically just in case an object from the
		// new heap arena becomes visible before the heap lock
		// is released (which shouldn't happen, but there's
		// little downside to this).
753
		atomic.StorepNoWB(unsafe.Pointer(&l2[ri.l2()]), unsafe.Pointer(r))
Russ Cox's avatar
Russ Cox committed
754 755
	}

756 757 758
	// Tell the race detector about the new heap memory.
	if raceenabled {
		racemapshadow(v, size)
Russ Cox's avatar
Russ Cox committed
759 760
	}

761 762 763 764 765 766
	return
}

// sysReserveAligned is like sysReserve, but the returned pointer is
// aligned to align bytes. It may reserve either n or n+align bytes,
// so it returns the size that was reserved.
767
func sysReserveAligned(v unsafe.Pointer, size, align uintptr) (unsafe.Pointer, uintptr) {
768 769 770 771 772
	// Since the alignment is rather large in uses of this
	// function, we're not likely to get it by chance, so we ask
	// for a larger region and remove the parts we don't need.
	retries := 0
retry:
773
	p := uintptr(sysReserve(v, size+align))
774 775 776 777 778 779 780 781 782 783 784 785 786
	switch {
	case p == 0:
		return nil, 0
	case p&(align-1) == 0:
		// We got lucky and got an aligned region, so we can
		// use the whole thing.
		return unsafe.Pointer(p), size + align
	case GOOS == "windows":
		// On Windows we can't release pieces of a
		// reservation, so we release the whole thing and
		// re-reserve the aligned sub-region. This may race,
		// so we may have to try again.
		sysFree(unsafe.Pointer(p), size+align, nil)
787
		p = alignUp(p, align)
788
		p2 := sysReserve(unsafe.Pointer(p), size)
789 790 791 792 793 794 795 796 797 798 799 800
		if p != uintptr(p2) {
			// Must have raced. Try again.
			sysFree(p2, size, nil)
			if retries++; retries == 100 {
				throw("failed to allocate aligned heap memory; too many retries")
			}
			goto retry
		}
		// Success.
		return p2, size
	default:
		// Trim off the unaligned parts.
801
		pAligned := alignUp(p, align)
802 803 804 805 806 807 808
		sysFree(unsafe.Pointer(p), pAligned-p, nil)
		end := pAligned + size
		endLen := (p + size + align) - end
		if endLen > 0 {
			sysFree(unsafe.Pointer(end), endLen, nil)
		}
		return unsafe.Pointer(pAligned), size
Russ Cox's avatar
Russ Cox committed
809 810 811
	}
}

812 813
// base address for all 0-byte allocations
var zerobase uintptr
814

815 816
// nextFreeFast returns the next free object if one is quickly available.
// Otherwise it returns 0.
817
func nextFreeFast(s *mspan) gclinkptr {
818 819 820
	theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
	if theBit < 64 {
		result := s.freeindex + uintptr(theBit)
821
		if result < s.nelems {
822
			freeidx := result + 1
823
			if freeidx%64 == 0 && freeidx != s.nelems {
824
				return 0
825
			}
826
			s.allocCache >>= uint(theBit + 1)
827 828
			s.freeindex = freeidx
			s.allocCount++
829
			return gclinkptr(result*s.elemsize + s.base())
830 831 832 833 834
		}
	}
	return 0
}

835 836 837 838 839 840
// nextFree returns the next free object from the cached span if one is available.
// Otherwise it refills the cache with a span with an available object and
// returns that object along with a flag indicating that this was a heavy
// weight allocation. If it is a heavy weight allocation the caller must
// determine whether a new GC cycle needs to be started or if the GC is active
// whether this goroutine needs to assist the GC.
841 842 843
//
// Must run in a non-preemptible context since otherwise the owner of
// c could change.
844 845
func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
	s = c.alloc[spc]
846
	shouldhelpgc = false
847
	freeIndex := s.nextFreeIndex()
848 849
	if freeIndex == s.nelems {
		// The span is full.
850
		if uintptr(s.allocCount) != s.nelems {
851
			println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
852
			throw("s.allocCount != s.nelems && freeIndex == s.nelems")
853
		}
854
		c.refill(spc)
855
		shouldhelpgc = true
856
		s = c.alloc[spc]
857 858

		freeIndex = s.nextFreeIndex()
859
	}
860

861 862
	if freeIndex >= s.nelems {
		throw("freeIndex is not valid")
863
	}
864 865

	v = gclinkptr(freeIndex*s.elemsize + s.base())
866 867
	s.allocCount++
	if uintptr(s.allocCount) > s.nelems {
868
		println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
869
		throw("s.allocCount > s.nelems")
870
	}
871 872 873
	return
}

874 875
// Allocate an object of size bytes.
// Small objects are allocated from the per-P cache's free lists.
876
// Large objects (> 32 kB) are allocated straight from the heap.
877
func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
878 879 880
	if gcphase == _GCmarktermination {
		throw("mallocgc called with gcphase == _GCmarktermination")
	}
881

882
	if size == 0 {
883
		return unsafe.Pointer(&zerobase)
884 885
	}

886 887 888
	if debug.sbrk != 0 {
		align := uintptr(16)
		if typ != nil {
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
			// TODO(austin): This should be just
			//   align = uintptr(typ.align)
			// but that's only 4 on 32-bit platforms,
			// even if there's a uint64 field in typ (see #599).
			// This causes 64-bit atomic accesses to panic.
			// Hence, we use stricter alignment that matches
			// the normal allocator better.
			if size&7 == 0 {
				align = 8
			} else if size&3 == 0 {
				align = 4
			} else if size&1 == 0 {
				align = 2
			} else {
				align = 1
			}
905 906 907 908
		}
		return persistentalloc(size, align, &memstats.other_sys)
	}

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
	// assistG is the G to charge for this allocation, or nil if
	// GC is not currently active.
	var assistG *g
	if gcBlackenEnabled != 0 {
		// Charge the current user G for this allocation.
		assistG = getg()
		if assistG.m.curg != nil {
			assistG = assistG.m.curg
		}
		// Charge the allocation against the G. We'll account
		// for internal fragmentation at the end of mallocgc.
		assistG.gcAssistBytes -= int64(size)

		if assistG.gcAssistBytes < 0 {
			// This G is in debt. Assist the GC to correct
			// this before allocating. This must happen
			// before disabling preemption.
			gcAssistAlloc(assistG)
		}
	}

930 931 932 933
	// Set mp.mallocing to keep from being preempted by GC.
	mp := acquirem()
	if mp.mallocing != 0 {
		throw("malloc deadlock")
934
	}
935 936 937
	if mp.gsignal == getg() {
		throw("malloc during signal")
	}
938
	mp.mallocing = 1
939

940 941
	shouldhelpgc := false
	dataSize := size
942
	c := gomcache()
943
	var x unsafe.Pointer
944
	noscan := typ == nil || typ.ptrdata == 0
945
	if size <= maxSmallSize {
946
		if noscan && size < maxTinySize {
947 948 949 950 951
			// Tiny allocator.
			//
			// Tiny allocator combines several tiny allocation requests
			// into a single memory block. The resulting memory block
			// is freed when all subobjects are unreachable. The subobjects
952
			// must be noscan (don't have pointers), this ensures that
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
			// the amount of potentially wasted memory is bounded.
			//
			// Size of the memory block used for combining (maxTinySize) is tunable.
			// Current setting is 16 bytes, which relates to 2x worst case memory
			// wastage (when all but one subobjects are unreachable).
			// 8 bytes would result in no wastage at all, but provides less
			// opportunities for combining.
			// 32 bytes provides more opportunities for combining,
			// but can lead to 4x worst case wastage.
			// The best case winning is 8x regardless of block size.
			//
			// Objects obtained from tiny allocator must not be freed explicitly.
			// So when an object will be freed explicitly, we ensure that
			// its size >= maxTinySize.
			//
			// SetFinalizer has a special case for objects potentially coming
			// from tiny allocator, it such case it allows to set finalizers
			// for an inner byte of a memory block.
			//
			// The main targets of tiny allocator are small strings and
			// standalone escaping variables. On a json benchmark
			// the allocator reduces number of allocations by ~12% and
			// reduces heap size by ~20%.
976 977 978
			off := c.tinyoffset
			// Align tiny pointer for required (conservative) alignment.
			if size&7 == 0 {
979
				off = alignUp(off, 8)
980
			} else if size&3 == 0 {
981
				off = alignUp(off, 4)
982
			} else if size&1 == 0 {
983
				off = alignUp(off, 2)
984
			}
985
			if off+size <= maxTinySize && c.tiny != 0 {
986
				// The object fits into existing tiny block.
987
				x = unsafe.Pointer(c.tiny + off)
988 989
				c.tinyoffset = off + size
				c.local_tinyallocs++
990 991
				mp.mallocing = 0
				releasem(mp)
992
				return x
993 994
			}
			// Allocate a new maxTinySize block.
995
			span := c.alloc[tinySpanClass]
996
			v := nextFreeFast(span)
997
			if v == 0 {
998
				v, _, shouldhelpgc = c.nextFree(tinySpanClass)
999
			}
1000 1001 1002 1003 1004
			x = unsafe.Pointer(v)
			(*[2]uint64)(x)[0] = 0
			(*[2]uint64)(x)[1] = 0
			// See if we need to replace the existing tiny block with the new one
			// based on amount of remaining free space.
1005 1006
			if size < c.tinyoffset || c.tiny == 0 {
				c.tiny = uintptr(x)
1007
				c.tinyoffset = size
1008 1009 1010
			}
			size = maxTinySize
		} else {
1011 1012 1013
			var sizeclass uint8
			if size <= smallSizeMax-8 {
				sizeclass = size_to_class8[(size+smallSizeDiv-1)/smallSizeDiv]
1014
			} else {
1015
				sizeclass = size_to_class128[(size-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
1016 1017
			}
			size = uintptr(class_to_size[sizeclass])
1018 1019
			spc := makeSpanClass(sizeclass, noscan)
			span := c.alloc[spc]
1020
			v := nextFreeFast(span)
1021
			if v == 0 {
1022
				v, span, shouldhelpgc = c.nextFree(spc)
1023
			}
1024
			x = unsafe.Pointer(v)
1025
			if needzero && span.needzero != 0 {
1026
				memclrNoHeapPointers(unsafe.Pointer(v), size)
1027 1028 1029
			}
		}
	} else {
1030
		var s *mspan
1031
		shouldhelpgc = true
1032
		systemstack(func() {
1033
			s = largeAlloc(size, needzero, noscan)
1034
		})
1035
		s.freeindex = 1
1036
		s.allocCount = 1
1037
		x = unsafe.Pointer(s.base())
1038
		size = s.elemsize
1039 1040
	}

1041
	var scanSize uintptr
1042
	if !noscan {
1043 1044 1045 1046 1047 1048 1049 1050
		// If allocating a defer+arg block, now that we've picked a malloc size
		// large enough to hold everything, cut the "asked for" size down to
		// just the defer header, so that the GC bitmap will record the arg block
		// as containing nothing at all (as if it were unused space at the end of
		// a malloc block caused by size rounding).
		// The defer arg areas are scanned as part of scanstack.
		if typ == deferType {
			dataSize = unsafe.Sizeof(_defer{})
1051
		}
1052
		heapBitsSetType(uintptr(x), size, dataSize, typ)
1053 1054 1055 1056 1057
		if dataSize > typ.size {
			// Array allocation. If there are any
			// pointers, GC has to scan to the last
			// element.
			if typ.ptrdata != 0 {
1058
				scanSize = dataSize - typ.size + typ.ptrdata
1059 1060
			}
		} else {
1061
			scanSize = typ.ptrdata
1062
		}
1063
		c.local_scan += scanSize
1064
	}
1065

1066 1067 1068 1069 1070 1071 1072 1073
	// Ensure that the stores above that initialize x to
	// type-safe memory and set the heap bits occur before
	// the caller can make x observable to the garbage
	// collector. Otherwise, on weakly ordered machines,
	// the garbage collector could follow a pointer to x,
	// but see uninitialized memory or stale heap bits.
	publicationBarrier()

1074
	// Allocate black during GC.
1075 1076 1077
	// All slots hold nil so no scanning is needed.
	// This may be racing with GC so do it atomically if there can be
	// a race marking the bit.
1078
	if gcphase != _GCoff {
1079
		gcmarknewobject(uintptr(x), size, scanSize)
1080 1081
	}

1082 1083 1084
	if raceenabled {
		racemalloc(x, size)
	}
1085

1086 1087 1088
	if msanenabled {
		msanmalloc(x, size)
	}
1089

1090 1091
	mp.mallocing = 0
	releasem(mp)
1092

1093 1094 1095
	if debug.allocfreetrace != 0 {
		tracealloc(x, size, typ)
	}
1096 1097

	if rate := MemProfileRate; rate > 0 {
1098 1099
		if rate != 1 && size < c.next_sample {
			c.next_sample -= size
1100
		} else {
1101
			mp := acquirem()
1102
			profilealloc(mp, x, size)
1103
			releasem(mp)
1104 1105 1106
		}
	}

1107 1108 1109 1110 1111 1112
	if assistG != nil {
		// Account for internal fragmentation in the assist
		// debt now that we know it.
		assistG.gcAssistBytes -= int64(size - dataSize)
	}

1113 1114
	if shouldhelpgc {
		if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
1115
			gcStart(t)
1116
		}
1117 1118 1119 1120 1121
	}

	return x
}

1122
func largeAlloc(size uintptr, needzero bool, noscan bool) *mspan {
Russ Cox's avatar
Russ Cox committed
1123 1124 1125 1126 1127 1128 1129 1130 1131
	// print("largeAlloc size=", size, "\n")

	if size+_PageSize < size {
		throw("out of memory")
	}
	npages := size >> _PageShift
	if size&_PageMask != 0 {
		npages++
	}
1132 1133 1134 1135 1136 1137

	// Deduct credit for this span allocation and sweep if
	// necessary. mHeap_Alloc will also sweep npages, so this only
	// pays the debt down to npage pages.
	deductSweepCredit(npages*_PageSize, npages)

1138
	s := mheap_.alloc(npages, makeSpanClass(0, noscan), true, needzero)
Russ Cox's avatar
Russ Cox committed
1139 1140 1141
	if s == nil {
		throw("out of memory")
	}
1142
	s.limit = s.base() + size
1143
	heapBitsForAddr(s.base()).initSpan(s)
Russ Cox's avatar
Russ Cox committed
1144 1145 1146
	return s
}

1147
// implementation of new builtin
1148 1149
// compiler (both frontend and SSA backend) knows the signature
// of this function
1150
func newobject(typ *_type) unsafe.Pointer {
1151
	return mallocgc(typ.size, typ, true)
1152 1153
}

Russ Cox's avatar
Russ Cox committed
1154 1155
//go:linkname reflect_unsafe_New reflect.unsafe_New
func reflect_unsafe_New(typ *_type) unsafe.Pointer {
1156
	return mallocgc(typ.size, typ, true)
Russ Cox's avatar
Russ Cox committed
1157 1158
}

1159 1160 1161 1162 1163
//go:linkname reflectlite_unsafe_New internal/reflectlite.unsafe_New
func reflectlite_unsafe_New(typ *_type) unsafe.Pointer {
	return mallocgc(typ.size, typ, true)
}

1164 1165
// newarray allocates an array of n elements of type typ.
func newarray(typ *_type, n int) unsafe.Pointer {
1166 1167 1168
	if n == 1 {
		return mallocgc(typ.size, typ, true)
	}
1169 1170
	mem, overflow := math.MulUintptr(typ.size, uintptr(n))
	if overflow || mem > maxAlloc || n < 0 {
1171
		panic(plainError("runtime: allocation size out of range"))
1172
	}
1173
	return mallocgc(mem, typ, true)
1174 1175
}

Russ Cox's avatar
Russ Cox committed
1176
//go:linkname reflect_unsafe_NewArray reflect.unsafe_NewArray
1177
func reflect_unsafe_NewArray(typ *_type, n int) unsafe.Pointer {
Russ Cox's avatar
Russ Cox committed
1178 1179 1180
	return newarray(typ, n)
}

1181
func profilealloc(mp *m, x unsafe.Pointer, size uintptr) {
1182
	mp.mcache.next_sample = nextSample()
1183
	mProf_Malloc(x, size)
1184 1185
}

1186 1187 1188 1189 1190 1191 1192
// nextSample returns the next sampling point for heap profiling. The goal is
// to sample allocations on average every MemProfileRate bytes, but with a
// completely random distribution over the allocation timeline; this
// corresponds to a Poisson process with parameter MemProfileRate. In Poisson
// processes, the distance between two samples follows the exponential
// distribution (exp(MemProfileRate)), so the best return value is a random
// number taken from an exponential distribution whose mean is MemProfileRate.
1193
func nextSample() uintptr {
1194 1195 1196 1197 1198 1199 1200
	if GOOS == "plan9" {
		// Plan 9 doesn't support floating point in note handler.
		if g := getg(); g == g.m.gsignal {
			return nextSampleNoFP()
		}
	}

1201
	return uintptr(fastexprand(MemProfileRate))
1202
}
1203

1204 1205 1206 1207 1208
// fastexprand returns a random number from an exponential distribution with
// the specified mean.
func fastexprand(mean int) int32 {
	// Avoid overflow. Maximum possible step is
	// -ln(1/(1<<randomBitCount)) * mean, approximately 20 * mean.
1209
	switch {
1210 1211 1212
	case mean > 0x7000000:
		mean = 0x7000000
	case mean == 0:
1213 1214 1215
		return 0
	}

1216 1217 1218 1219 1220 1221 1222 1223
	// Take a random sample of the exponential distribution exp(-mean*x).
	// The probability distribution function is mean*exp(-mean*x), so the CDF is
	// p = 1 - exp(-mean*x), so
	// q = 1 - p == exp(-mean*x)
	// log_e(q) = -mean*x
	// -log_e(q)/mean = x
	// x = -log_e(q) * mean
	// x = log_2(q) * (-log_e(2)) * mean    ; Using log_2 for efficiency
1224
	const randomBitCount = 26
1225
	q := fastrand()%(1<<randomBitCount) + 1
1226 1227 1228 1229 1230
	qlog := fastlog2(float64(q)) - randomBitCount
	if qlog > 0 {
		qlog = 0
	}
	const minusLog2 = -0.6931471805599453 // -ln(2)
1231
	return int32(qlog*(minusLog2*float64(mean))) + 1
1232 1233
}

1234 1235
// nextSampleNoFP is similar to nextSample, but uses older,
// simpler code to avoid floating point.
1236
func nextSampleNoFP() uintptr {
1237 1238 1239 1240 1241 1242
	// Set first allocation sample size.
	rate := MemProfileRate
	if rate > 0x3fffffff { // make 2*rate not overflow
		rate = 0x3fffffff
	}
	if rate != 0 {
1243
		return uintptr(fastrand() % uint32(2*rate))
1244 1245 1246 1247
	}
	return 0
}

1248
type persistentAlloc struct {
1249
	base *notInHeap
1250
	off  uintptr
1251 1252
}

1253 1254 1255 1256 1257
var globalAlloc struct {
	mutex
	persistentAlloc
}

1258 1259 1260 1261 1262 1263 1264 1265 1266
// persistentChunkSize is the number of bytes we allocate when we grow
// a persistentAlloc.
const persistentChunkSize = 256 << 10

// persistentChunks is a list of all the persistent chunks we have
// allocated. The list is maintained through the first word in the
// persistent chunk. This is updated atomically.
var persistentChunks *notInHeap

1267 1268 1269 1270
// Wrapper around sysAlloc that can allocate small chunks.
// There is no associated free operation.
// Intended for things like function/type/debug-related persistent data.
// If align is 0, uses default align (currently 8).
1271
// The returned memory will be zeroed.
1272 1273
//
// Consider marking persistentalloc'd types go:notinheap.
1274
func persistentalloc(size, align uintptr, sysStat *uint64) unsafe.Pointer {
1275
	var p *notInHeap
1276 1277 1278
	systemstack(func() {
		p = persistentalloc1(size, align, sysStat)
	})
1279
	return unsafe.Pointer(p)
1280 1281 1282 1283 1284
}

// Must run on system stack because stack growth can (re)invoke it.
// See issue 9174.
//go:systemstack
1285
func persistentalloc1(size, align uintptr, sysStat *uint64) *notInHeap {
1286 1287 1288 1289
	const (
		maxBlock = 64 << 10 // VM reservation granularity is 64K on windows
	)

1290 1291 1292
	if size == 0 {
		throw("persistentalloc: size == 0")
	}
1293 1294
	if align != 0 {
		if align&(align-1) != 0 {
1295
			throw("persistentalloc: align is not a power of 2")
1296 1297
		}
		if align > _PageSize {
1298
			throw("persistentalloc: align is too large")
1299 1300 1301 1302 1303 1304
		}
	} else {
		align = 8
	}

	if size >= maxBlock {
1305
		return (*notInHeap)(sysAlloc(size, sysStat))
1306 1307
	}

1308 1309
	mp := acquirem()
	var persistent *persistentAlloc
1310 1311
	if mp != nil && mp.p != 0 {
		persistent = &mp.p.ptr().palloc
1312 1313 1314 1315
	} else {
		lock(&globalAlloc.mutex)
		persistent = &globalAlloc.persistentAlloc
	}
1316
	persistent.off = alignUp(persistent.off, align)
1317 1318
	if persistent.off+size > persistentChunkSize || persistent.base == nil {
		persistent.base = (*notInHeap)(sysAlloc(persistentChunkSize, &memstats.other_sys))
1319
		if persistent.base == nil {
1320 1321 1322
			if persistent == &globalAlloc.persistentAlloc {
				unlock(&globalAlloc.mutex)
			}
1323
			throw("runtime: cannot allocate memory")
1324
		}
1325 1326 1327 1328 1329 1330 1331 1332 1333

		// Add the new chunk to the persistentChunks list.
		for {
			chunks := uintptr(unsafe.Pointer(persistentChunks))
			*(*uintptr)(unsafe.Pointer(persistent.base)) = chunks
			if atomic.Casuintptr((*uintptr)(unsafe.Pointer(&persistentChunks)), chunks, uintptr(unsafe.Pointer(persistent.base))) {
				break
			}
		}
1334
		persistent.off = alignUp(sys.PtrSize, align)
1335
	}
1336
	p := persistent.base.add(persistent.off)
1337
	persistent.off += size
1338 1339 1340 1341
	releasem(mp)
	if persistent == &globalAlloc.persistentAlloc {
		unlock(&globalAlloc.mutex)
	}
1342

1343 1344 1345
	if sysStat != &memstats.other_sys {
		mSysStatInc(sysStat, size)
		mSysStatDec(&memstats.other_sys, size)
1346 1347 1348
	}
	return p
}
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
// inPersistentAlloc reports whether p points to memory allocated by
// persistentalloc. This must be nosplit because it is called by the
// cgo checker code, which is called by the write barrier code.
//go:nosplit
func inPersistentAlloc(p uintptr) bool {
	chunk := atomic.Loaduintptr((*uintptr)(unsafe.Pointer(&persistentChunks)))
	for chunk != 0 {
		if p >= chunk && p < chunk+persistentChunkSize {
			return true
		}
		chunk = *(*uintptr)(unsafe.Pointer(chunk))
	}
	return false
}

1365
// linearAlloc is a simple linear allocator that pre-reserves a region
1366 1367
// of memory and then maps that region into the Ready state as needed. The
// caller is responsible for locking.
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
type linearAlloc struct {
	next   uintptr // next free byte
	mapped uintptr // one byte past end of mapped space
	end    uintptr // end of reserved space
}

func (l *linearAlloc) init(base, size uintptr) {
	l.next, l.mapped = base, base
	l.end = base + size
}

func (l *linearAlloc) alloc(size, align uintptr, sysStat *uint64) unsafe.Pointer {
1380
	p := alignUp(l.next, align)
1381 1382 1383 1384
	if p+size > l.end {
		return nil
	}
	l.next = p + size
1385
	if pEnd := alignUp(l.next-1, physPageSize); pEnd > l.mapped {
1386
		// Transition from Reserved to Prepared to Ready.
1387
		sysMap(unsafe.Pointer(l.mapped), pEnd-l.mapped, sysStat)
1388
		sysUsed(unsafe.Pointer(l.mapped), pEnd-l.mapped)
1389 1390 1391 1392 1393
		l.mapped = pEnd
	}
	return unsafe.Pointer(p)
}

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
// notInHeap is off-heap memory allocated by a lower-level allocator
// like sysAlloc or persistentAlloc.
//
// In general, it's better to use real types marked as go:notinheap,
// but this serves as a generic type for situations where that isn't
// possible (like in the allocators).
//
// TODO: Use this as the return type of sysAlloc, persistentAlloc, etc?
//
//go:notinheap
type notInHeap struct{}

func (p *notInHeap) add(bytes uintptr) *notInHeap {
	return (*notInHeap)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + bytes))
}