malloc.goc 26.2 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2009 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.

// See malloc.h for overview.
//
// TODO(rsc): double-check stats.

9
package runtime
10
#include "runtime.h"
Russ Cox's avatar
Russ Cox committed
11
#include "arch_GOARCH.h"
12
#include "malloc.h"
13
#include "type.h"
14
#include "typekind.h"
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
15
#include "race.h"
16
#include "stack.h"
17
#include "../../cmd/ld/textflag.h"
18

Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
19
// Mark mheap as 'no pointers', it does not contain interesting pointers but occupies ~45K.
20
#pragma dataflag NOPTR
21
MHeap runtime·mheap;
22
MStats mstats;
23

24 25
int32	runtime·checking;

26
extern MStats mstats;	// defined in zruntime_def_$GOOS_$GOARCH.go
27

Russ Cox's avatar
Russ Cox committed
28
extern volatile intgo runtime·MemProfileRate;
29

30 31
static void* largealloc(uint32, uintptr*);

32 33 34
// Allocate an object of at least size bytes.
// Small objects are allocated from the per-thread cache's free lists.
// Large objects (> 32 kB) are allocated straight from the heap.
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
35
// If the block will be freed with runtime·free(), typ must be 0.
36
void*
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
37
runtime·mallocgc(uintptr size, uintptr typ, uint32 flag)
38
{
Russ Cox's avatar
Russ Cox committed
39
	int32 sizeclass;
40
	uintptr tinysize, size1;
Russ Cox's avatar
Russ Cox committed
41
	intgo rate;
42
	MCache *c;
43
	MCacheList *l;
44
	MLink *v, *next;
45
	byte *tiny;
46

Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
47 48 49 50 51 52
	if(size == 0) {
		// All 0-length allocations use this pointer.
		// The language does not require the allocations to
		// have distinct values.
		return &runtime·zerobase;
	}
Russ Cox's avatar
Russ Cox committed
53
	if(m->mallocing)
54
		runtime·throw("malloc/free - deadlock");
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
55 56 57
	// Disable preemption during settype_flush.
	// We can not use m->mallocing for this, because settype_flush calls mallocgc.
	m->locks++;
Russ Cox's avatar
Russ Cox committed
58
	m->mallocing = 1;
59

Jan Ziak's avatar
Jan Ziak committed
60 61 62
	if(DebugTypeAtBlockEnd)
		size += sizeof(uintptr);

63
	c = m->mcache;
64
	if(!runtime·debug.efence && size <= MaxSmallSize) {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
		if((flag&(FlagNoScan|FlagNoGC)) == FlagNoScan && size < TinySize) {
			// 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
			// must be FlagNoScan (don't have pointers), this ensures that
			// the amount of potentially wasted memory is bounded.
			//
			// Size of the memory block used for combining (TinySize) 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 >= TinySize.
			//
			// 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%.

Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
96
			tinysize = c->tinysize;
97
			if(size <= tinysize) {
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
98
				tiny = c->tiny;
99 100 101 102 103 104 105
				// Align tiny pointer for required (conservative) alignment.
				if((size&7) == 0)
					tiny = (byte*)ROUND((uintptr)tiny, 8);
				else if((size&3) == 0)
					tiny = (byte*)ROUND((uintptr)tiny, 4);
				else if((size&1) == 0)
					tiny = (byte*)ROUND((uintptr)tiny, 2);
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
106
				size1 = size + (tiny - c->tiny);
107 108 109
				if(size1 <= tinysize) {
					// The object fits into existing tiny block.
					v = (MLink*)tiny;
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
110 111
					c->tiny += size1;
					c->tinysize -= size1;
112 113 114 115 116 117 118 119 120 121 122 123
					m->mallocing = 0;
					m->locks--;
					if(m->locks == 0 && g->preempt)  // restore the preemption request in case we've cleared it in newstack
						g->stackguard0 = StackPreempt;
					return v;
				}
			}
			// Allocate a new TinySize block.
			l = &c->list[TinySizeClass];
			if(l->list == nil)
				runtime·MCache_Refill(c, TinySizeClass);
			v = l->list;
124 125 126 127
			next = v->next;
			if(next != nil)  // prefetching nil leads to a DTLB miss
				PREFETCH(next);
			l->list = next;
128 129 130 131 132 133
			l->nlist--;
			((uint64*)v)[0] = 0;
			((uint64*)v)[1] = 0;
			// See if we need to replace the existing tiny block with the new one
			// based on amount of remaining free space.
			if(TinySize-size > tinysize) {
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
134 135
				c->tiny = (byte*)v + size;
				c->tinysize = TinySize - size;
136 137 138 139
			}
			size = TinySize;
			goto done;
		}
140
		// Allocate from mcache free lists.
141 142 143 144 145
		// Inlined version of SizeToClass().
		if(size <= 1024-8)
			sizeclass = runtime·size_to_class8[(size+7)>>3];
		else
			sizeclass = runtime·size_to_class128[(size-1024+127) >> 7];
146
		size = runtime·class_to_size[sizeclass];
147 148 149 150
		l = &c->list[sizeclass];
		if(l->list == nil)
			runtime·MCache_Refill(c, sizeclass);
		v = l->list;
151 152 153 154
		next = v->next;
		if(next != nil)  // prefetching nil leads to a DTLB miss
			PREFETCH(next);
		l->list = next;
155
		l->nlist--;
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
156
		if(!(flag & FlagNoZero)) {
157 158
			v->next = nil;
			// block is zeroed iff second word is zero ...
159
			if(size > 2*sizeof(uintptr) && ((uintptr*)v)[1] != 0)
160 161
				runtime·memclr((byte*)v, size);
		}
162
	done:
163
		c->local_cachealloc += size;
Russ Cox's avatar
Russ Cox committed
164 165
	} else {
		// Allocate directly from heap.
166
		v = largealloc(flag, &size);
Russ Cox's avatar
Russ Cox committed
167
	}
168

169 170 171 172
	if(flag & FlagNoGC)
		runtime·marknogc(v);
	else if(!(flag & FlagNoScan))
		runtime·markscan(v);
Russ Cox's avatar
Russ Cox committed
173

Jan Ziak's avatar
Jan Ziak committed
174
	if(DebugTypeAtBlockEnd)
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
175 176
		*(uintptr*)((uintptr)v+size-sizeof(uintptr)) = typ;

177 178 179
	// TODO: save type even if FlagNoScan?  Potentially expensive but might help
	// heap profiling/tracing.
	if(UseSpanType && !(flag & FlagNoScan) && typ != 0) {
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
180 181 182 183 184 185 186 187
		uintptr *buf, i;

		buf = m->settype_buf;
		i = m->settype_bufsize;
		buf[i++] = (uintptr)v;
		buf[i++] = typ;
		m->settype_bufsize = i;
	}
Jan Ziak's avatar
Jan Ziak committed
188

Russ Cox's avatar
Russ Cox committed
189
	m->mallocing = 0;
190
	if(UseSpanType && !(flag & FlagNoScan) && typ != 0 && m->settype_bufsize == nelem(m->settype_buf))
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
191
		runtime·settype_flush(m);
192 193
	if(raceenabled)
		runtime·racemalloc(v, size);
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
194 195
	m->locks--;
	if(m->locks == 0 && g->preempt)  // restore the preemption request in case we've cleared it in newstack
196
		g->stackguard0 = StackPreempt;
Russ Cox's avatar
Russ Cox committed
197

198 199 200
	if(runtime·debug.allocfreetrace)
		goto profile;

201
	if(!(flag & FlagNoProfiling) && (rate = runtime·MemProfileRate) > 0) {
202 203 204 205 206 207
		if(size >= rate)
			goto profile;
		if(m->mcache->next_sample > size)
			m->mcache->next_sample -= size;
		else {
			// pick next profile time
Russ Cox's avatar
Russ Cox committed
208
			// If you change this, also change allocmcache.
209 210
			if(rate > 0x3fffffff)	// make 2*rate not overflow
				rate = 0x3fffffff;
211
			m->mcache->next_sample = runtime·fastrand1() % (2*rate);
212
		profile:
213
			runtime·MProf_Malloc(v, size, typ);
214 215 216
		}
	}

Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
217
	if(!(flag & FlagNoInvokeGC) && mstats.heap_alloc >= mstats.next_gc)
218
		runtime·gc(0);
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
219

Russ Cox's avatar
Russ Cox committed
220
	return v;
221 222
}

223 224 225 226 227 228 229 230 231
static void*
largealloc(uint32 flag, uintptr *sizep)
{
	uintptr npages, size;
	MSpan *s;
	void *v;

	// Allocate directly from heap.
	size = *sizep;
232 233
	if(size + PageSize < size)
		runtime·throw("out of memory");
234 235 236 237 238 239 240 241 242 243 244 245 246 247
	npages = size >> PageShift;
	if((size & PageMask) != 0)
		npages++;
	s = runtime·MHeap_Alloc(&runtime·mheap, npages, 0, 1, !(flag & FlagNoZero));
	if(s == nil)
		runtime·throw("out of memory");
	s->limit = (byte*)(s->start<<PageShift) + size;
	*sizep = npages<<PageShift;
	v = (void*)(s->start << PageShift);
	// setup for mark sweep
	runtime·markspan(v, 0, 0, true);
	return v;
}

Russ Cox's avatar
Russ Cox committed
248
void*
249
runtime·malloc(uintptr size)
Russ Cox's avatar
Russ Cox committed
250
{
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
251
	return runtime·mallocgc(size, 0, FlagNoInvokeGC);
Russ Cox's avatar
Russ Cox committed
252 253
}

254 255
// Free the object whose base pointer is v.
void
256
runtime·free(void *v)
257
{
258
	int32 sizeclass;
259 260
	MSpan *s;
	MCache *c;
261
	uintptr size;
262

Russ Cox's avatar
Russ Cox committed
263 264
	if(v == nil)
		return;
265
	
Maxim Pimenov's avatar
Maxim Pimenov committed
266
	// If you change this also change mgc0.c:/^sweep,
267
	// which has a copy of the guts of free.
Russ Cox's avatar
Russ Cox committed
268

Russ Cox's avatar
Russ Cox committed
269
	if(m->mallocing)
270
		runtime·throw("malloc/free - deadlock");
Russ Cox's avatar
Russ Cox committed
271 272
	m->mallocing = 1;

273
	if(!runtime·mlookup(v, nil, nil, &s)) {
274 275
		runtime·printf("free %p: not an allocated block\n", v);
		runtime·throw("free runtime·mlookup");
276
	}
277 278
	size = s->elemsize;
	sizeclass = s->sizeclass;
279 280 281 282
	// Objects that are smaller than TinySize can be allocated using tiny alloc,
	// if then such object is combined with an object with finalizer, we will crash.
	if(size < TinySize)
		runtime·throw("freeing too small block");
Russ Cox's avatar
Russ Cox committed
283

Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
284 285 286
	if(raceenabled)
		runtime·racefree(v);

287 288 289
	if(s->specials != nil)
		runtime·freeallspecials(s, v, size);

290
	c = m->mcache;
291
	if(sizeclass == 0) {
292
		// Large object.
293
		*(uintptr*)(s->start<<PageShift) = (uintptr)0xfeedfeedfeedfeedll;	// mark as "needs to be zeroed"
294 295 296
		// Must mark v freed before calling unmarkspan and MHeap_Free:
		// they might coalesce v into other spans and change the bitmap further.
		runtime·markfreed(v, size);
297
		runtime·unmarkspan(v, 1<<PageShift);
298 299 300 301
		if(runtime·debug.efence)
			runtime·SysFree((void*)(s->start<<PageShift), size, &mstats.heap_sys);
		else
			runtime·MHeap_Free(&runtime·mheap, s, 1);
302 303
		c->local_nlargefree++;
		c->local_largefree += size;
304 305
	} else {
		// Small object.
306
		if(size > 2*sizeof(uintptr))
307
			((uintptr*)v)[1] = (uintptr)0xfeedfeedfeedfeedll;	// mark as "needs to be zeroed"
308 309
		else if(size > sizeof(uintptr))
			((uintptr*)v)[1] = 0;
310 311 312 313
		// Must mark v freed before calling MCache_Free:
		// it might coalesce v and other blocks into a bigger span
		// and change the bitmap further.
		runtime·markfreed(v, size);
314
		c->local_nsmallfree[sizeclass]++;
315
		runtime·MCache_Free(c, v, sizeclass, size);
316
	}
Russ Cox's avatar
Russ Cox committed
317
	m->mallocing = 0;
318 319
}

Russ Cox's avatar
Russ Cox committed
320
int32
321
runtime·mlookup(void *v, byte **base, uintptr *size, MSpan **sp)
Russ Cox's avatar
Russ Cox committed
322
{
323
	uintptr n, i;
324
	byte *p;
Russ Cox's avatar
Russ Cox committed
325 326
	MSpan *s;

327
	m->mcache->local_nlookup++;
328 329
	if (sizeof(void*) == 4 && m->mcache->local_nlookup >= (1<<30)) {
		// purge cache stats to prevent overflow
330
		runtime·lock(&runtime·mheap);
331
		runtime·purgecachedstats(m->mcache);
332
		runtime·unlock(&runtime·mheap);
333 334
	}

335
	s = runtime·MHeap_LookupMaybe(&runtime·mheap, v);
336 337
	if(sp)
		*sp = s;
Russ Cox's avatar
Russ Cox committed
338
	if(s == nil) {
339
		runtime·checkfreed(v, 1);
Russ Cox's avatar
Russ Cox committed
340 341 342 343 344
		if(base)
			*base = nil;
		if(size)
			*size = 0;
		return 0;
Russ Cox's avatar
Russ Cox committed
345 346 347 348 349
	}

	p = (byte*)((uintptr)s->start<<PageShift);
	if(s->sizeclass == 0) {
		// Large object.
Russ Cox's avatar
Russ Cox committed
350 351 352 353 354
		if(base)
			*base = p;
		if(size)
			*size = s->npages<<PageShift;
		return 1;
Russ Cox's avatar
Russ Cox committed
355 356
	}

Jan Ziak's avatar
Jan Ziak committed
357
	n = s->elemsize;
358 359
	if(base) {
		i = ((byte*)v - p)/n;
Russ Cox's avatar
Russ Cox committed
360
		*base = p + i*n;
361
	}
Russ Cox's avatar
Russ Cox committed
362 363
	if(size)
		*size = n;
364

Russ Cox's avatar
Russ Cox committed
365
	return 1;
Russ Cox's avatar
Russ Cox committed
366 367
}

368
MCache*
369
runtime·allocmcache(void)
370
{
Russ Cox's avatar
Russ Cox committed
371
	intgo rate;
Russ Cox's avatar
Russ Cox committed
372 373
	MCache *c;

374 375 376
	runtime·lock(&runtime·mheap);
	c = runtime·FixAlloc_Alloc(&runtime·mheap.cachealloc);
	runtime·unlock(&runtime·mheap);
377
	runtime·memclr((byte*)c, sizeof(*c));
Russ Cox's avatar
Russ Cox committed
378 379 380 381 382

	// Set first allocation sample size.
	rate = runtime·MemProfileRate;
	if(rate > 0x3fffffff)	// make 2*rate not overflow
		rate = 0x3fffffff;
383 384
	if(rate != 0)
		c->next_sample = runtime·fastrand1() % (2*rate);
Russ Cox's avatar
Russ Cox committed
385

Russ Cox's avatar
Russ Cox committed
386
	return c;
387 388
}

389
void
390
runtime·freemcache(MCache *c)
391
{
392
	runtime·MCache_ReleaseAll(c);
393
	runtime·lock(&runtime·mheap);
394
	runtime·purgecachedstats(c);
395 396
	runtime·FixAlloc_Free(&runtime·mheap.cachealloc, c);
	runtime·unlock(&runtime·mheap);
397
}
398

399 400 401
void
runtime·purgecachedstats(MCache *c)
{
402
	MHeap *h;
403 404
	int32 i;

405
	// Protected by either heap or GC lock.
406
	h = &runtime·mheap;
407 408 409 410
	mstats.heap_alloc += c->local_cachealloc;
	c->local_cachealloc = 0;
	mstats.nlookup += c->local_nlookup;
	c->local_nlookup = 0;
411 412 413 414 415 416 417
	h->largefree += c->local_largefree;
	c->local_largefree = 0;
	h->nlargefree += c->local_nlargefree;
	c->local_nlargefree = 0;
	for(i=0; i<nelem(c->local_nsmallfree); i++) {
		h->nsmallfree[i] += c->local_nsmallfree[i];
		c->local_nsmallfree[i] = 0;
418
	}
419 420
}

421 422 423 424
// Size of the trailing by_size array differs between Go and C,
// NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
// sizeof_C_MStats is what C thinks about size of Go struct.
uintptr runtime·sizeof_C_MStats = sizeof(MStats) - (NumSizeClasses - 61) * sizeof(mstats.by_size[0]);
425

426 427
#define MaxArena32 (2U<<30)

428
void
429
runtime·mallocinit(void)
430
{
431
	byte *p;
432
	uintptr arena_size, bitmap_size, spans_size;
433
	extern byte end[];
434
	uintptr limit;
435
	uint64 i;
436

437
	p = nil;
Russ Cox's avatar
Russ Cox committed
438 439
	arena_size = 0;
	bitmap_size = 0;
440 441
	spans_size = 0;

Russ Cox's avatar
Russ Cox committed
442 443 444 445
	// for 64-bit build
	USED(p);
	USED(arena_size);
	USED(bitmap_size);
446
	USED(spans_size);
447

448
	runtime·InitSizes();
449

450 451 452
	if(runtime·class_to_size[TinySizeClass] != TinySize)
		runtime·throw("bad TinySizeClass");

453 454 455 456
	// limit = runtime·memlimit();
	// See https://code.google.com/p/go/issues/detail?id=5049
	// TODO(rsc): Fix after 1.1.
	limit = 0;
457

458 459 460
	// Set up the allocation arena, a contiguous area of memory where
	// allocated data will be found.  The arena begins with a bitmap large
	// enough to hold 4 bits per allocated word.
461
	if(sizeof(void*) == 8 && (limit == 0 || limit > (1<<30))) {
462
		// On a 64-bit machine, allocate from a single contiguous reservation.
463
		// 128 GB (MaxMem) should be big enough for now.
464 465
		//
		// The code will work with the reservation at any address, but ask
466
		// SysReserve to use 0x0000XXc000000000 if possible (XX=00...7f).
467
		// Allocating a 128 GB region takes away 37 bits, and the amd64
468
		// doesn't let us choose the top 17 bits, so that leaves the 11 bits
469
		// in the middle of 0x00c0 for us to choose.  Choosing 0x00c0 means
470
		// that the valid memory addresses will begin 0x00c0, 0x00c1, ..., 0x00df.
471 472
		// In little-endian, that's c0 00, c1 00, ..., df 00. None of those are valid
		// UTF-8 sequences, and they are otherwise as far away from 
473 474 475 476
		// 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
		// on OS X during thread allocations.  0x00c0 causes conflicts with
		// AddressSanitizer which reserves all memory up to 0x0100.
477 478 479 480
		// These choices are both for debuggability and to reduce the
		// odds of the conservative garbage collector not collecting memory
		// because some non-pointer block of memory had a bit pattern
		// that matched a memory address.
481
		//
482 483
		// Actually we reserve 136 GB (because the bitmap ends up being 8 GB)
		// but it hardly matters: e0 00 is not valid UTF-8 either.
484 485
		//
		// If this fails we fall back to the 32 bit memory mechanism
486
		arena_size = MaxMem;
487
		bitmap_size = arena_size / (sizeof(void*)*8/4);
488
		spans_size = arena_size / PageSize * sizeof(runtime·mheap.spans[0]);
489
		spans_size = ROUND(spans_size, PageSize);
490 491
		for(i = 0; i <= 0x7f; i++) {
			p = (void*)(i<<40 | 0x00c0ULL<<32);
492
			p = runtime·SysReserve(p, bitmap_size + spans_size + arena_size + PageSize);
493 494 495
			if(p != nil)
				break;
		}
496 497
	}
	if (p == nil) {
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		// On a 32-bit machine, we can't typically get away
		// with a giant virtual address space reservation.
		// Instead we map the memory information bitmap
		// immediately after the data segment, large enough
		// to handle another 2GB of mappings (256 MB),
		// along with a reservation for another 512 MB of memory.
		// When that gets used up, we'll start asking the kernel
		// for any memory anywhere and hope it's in the 2GB
		// following the bitmap (presumably the executable begins
		// near the bottom of memory, so we'll have to use up
		// most of memory before the kernel resorts to giving out
		// memory before the beginning of the text segment).
		//
		// Alternatively we could reserve 512 MB bitmap, enough
		// for 4GB of mappings, and then accept any memory the
		// kernel threw at us, but normally that's a waste of 512 MB
		// of address space, which is probably too much in a 32-bit world.
		bitmap_size = MaxArena32 / (sizeof(void*)*8/4);
		arena_size = 512<<20;
517
		spans_size = MaxArena32 / PageSize * sizeof(runtime·mheap.spans[0]);
518
		if(limit > 0 && arena_size+bitmap_size+spans_size > limit) {
519 520
			bitmap_size = (limit / 9) & ~((1<<PageShift) - 1);
			arena_size = bitmap_size * 8;
521
			spans_size = arena_size / PageSize * sizeof(runtime·mheap.spans[0]);
522
		}
523
		spans_size = ROUND(spans_size, PageSize);
524

525 526 527 528
		// SysReserve treats the address we ask for, end, as a hint,
		// not as an absolute requirement.  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
529 530 531 532 533
		// 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 and then round up
		// to a MB boundary.
534 535
		p = (byte*)ROUND((uintptr)end + (1<<18), 1<<20);
		p = runtime·SysReserve(p, bitmap_size + spans_size + arena_size + PageSize);
536 537
		if(p == nil)
			runtime·throw("runtime: cannot reserve arena virtual address space");
538
	}
539 540 541 542 543

	// PageSize can be larger than OS definition of page size,
	// so SysReserve can give us a PageSize-unaligned pointer.
	// To overcome this we ask for PageSize more and round up the pointer.
	p = (byte*)ROUND((uintptr)p, PageSize);
544

545
	runtime·mheap.spans = (MSpan**)p;
546 547 548 549
	runtime·mheap.bitmap = p + spans_size;
	runtime·mheap.arena_start = p + spans_size + bitmap_size;
	runtime·mheap.arena_used = runtime·mheap.arena_start;
	runtime·mheap.arena_end = runtime·mheap.arena_start + arena_size;
550 551

	// Initialize the rest of the allocator.	
552
	runtime·MHeap_Init(&runtime·mheap);
553
	m->mcache = runtime·allocmcache();
554 555

	// See if it works.
556
	runtime·free(runtime·malloc(TinySize));
557 558
}

559 560 561 562
void*
runtime·MHeap_SysAlloc(MHeap *h, uintptr n)
{
	byte *p;
563

564 565 566 567 568 569 570
	if(n > h->arena_end - h->arena_used) {
		// We are in 32-bit mode, maybe we didn't use all possible address space yet.
		// Reserve some more space.
		byte *new_end;
		uintptr needed;

		needed = (uintptr)h->arena_used + n - (uintptr)h->arena_end;
571
		needed = ROUND(needed, 256<<20);
572 573 574 575 576 577 578
		new_end = h->arena_end + needed;
		if(new_end <= h->arena_start + MaxArena32) {
			p = runtime·SysReserve(h->arena_end, new_end - h->arena_end);
			if(p == h->arena_end)
				h->arena_end = new_end;
		}
	}
579
	if(n <= h->arena_end - h->arena_used) {
580 581
		// Keep taking from our reservation.
		p = h->arena_used;
582
		runtime·SysMap(p, n, &mstats.heap_sys);
583
		h->arena_used += n;
584
		runtime·MHeap_MapBits(h);
585
		runtime·MHeap_MapSpans(h);
586 587
		if(raceenabled)
			runtime·racemapshadow(p, n);
588 589
		return p;
	}
590
	
591 592
	// If using 64-bit, our reservation is all we have.
	if(sizeof(void*) == 8 && (uintptr)h->bitmap >= 0xffffffffU)
593 594 595 596 597
		return nil;

	// On 32-bit, once the reservation is gone we can
	// try to get memory at a location chosen by the OS
	// and hope that it is in the range we allocated bitmap for.
598
	p = runtime·SysAlloc(n, &mstats.heap_sys);
599 600 601 602
	if(p == nil)
		return nil;

	if(p < h->arena_start || p+n - h->arena_start >= MaxArena32) {
603 604
		runtime·printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
			p, h->arena_start, h->arena_start+MaxArena32);
605
		runtime·SysFree(p, n, &mstats.heap_sys);
606 607 608 609 610 611 612 613
		return nil;
	}

	if(p+n > h->arena_used) {
		h->arena_used = p+n;
		if(h->arena_used > h->arena_end)
			h->arena_end = h->arena_used;
		runtime·MHeap_MapBits(h);
614
		runtime·MHeap_MapSpans(h);
615 616
		if(raceenabled)
			runtime·racemapshadow(p, n);
617 618 619
	}
	
	return p;
620 621
}

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
static struct
{
	Lock;
	byte*	pos;
	byte*	end;
} persistent;

enum
{
	PersistentAllocChunk	= 256<<10,
	PersistentAllocMaxBlock	= 64<<10,  // VM reservation granularity is 64K on windows
};

// 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).
void*
640
runtime·persistentalloc(uintptr size, uintptr align, uint64 *stat)
641 642 643
{
	byte *p;

644
	if(align != 0) {
645 646 647 648 649 650 651
		if(align&(align-1))
			runtime·throw("persistentalloc: align is now a power of 2");
		if(align > PageSize)
			runtime·throw("persistentalloc: align is too large");
	} else
		align = 8;
	if(size >= PersistentAllocMaxBlock)
652
		return runtime·SysAlloc(size, stat);
653 654 655
	runtime·lock(&persistent);
	persistent.pos = (byte*)ROUND((uintptr)persistent.pos, align);
	if(persistent.pos + size > persistent.end) {
656
		persistent.pos = runtime·SysAlloc(PersistentAllocChunk, &mstats.other_sys);
657 658 659 660 661 662 663 664 665
		if(persistent.pos == nil) {
			runtime·unlock(&persistent);
			runtime·throw("runtime: cannot allocate memory");
		}
		persistent.end = persistent.pos + PersistentAllocChunk;
	}
	p = persistent.pos;
	persistent.pos += size;
	runtime·unlock(&persistent);
666 667 668 669 670 671
	if(stat != &mstats.other_sys) {
		// reaccount the allocation against provided stat
		runtime·xadd64(stat, size);
		runtime·xadd64(&mstats.other_sys, -(uint64)size);
	}
	return p;
672 673
}

Jan Ziak's avatar
Jan Ziak committed
674 675 676
static Lock settype_lock;

void
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
677
runtime·settype_flush(M *mp)
Jan Ziak's avatar
Jan Ziak committed
678 679 680 681 682 683 684 685 686 687
{
	uintptr *buf, *endbuf;
	uintptr size, ofs, j, t;
	uintptr ntypes, nbytes2, nbytes3;
	uintptr *data2;
	byte *data3;
	void *v;
	uintptr typ, p;
	MSpan *s;

688 689
	buf = mp->settype_buf;
	endbuf = buf + mp->settype_bufsize;
Jan Ziak's avatar
Jan Ziak committed
690 691 692 693 694 695 696 697 698 699 700

	runtime·lock(&settype_lock);
	while(buf < endbuf) {
		v = (void*)*buf;
		*buf = 0;
		buf++;
		typ = *buf;
		buf++;

		// (Manually inlined copy of runtime·MHeap_Lookup)
		p = (uintptr)v>>PageShift;
701
		p -= (uintptr)runtime·mheap.arena_start >> PageShift;
702
		s = runtime·mheap.spans[p];
Jan Ziak's avatar
Jan Ziak committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716

		if(s->sizeclass == 0) {
			s->types.compression = MTypes_Single;
			s->types.data = typ;
			continue;
		}

		size = s->elemsize;
		ofs = ((uintptr)v - (s->start<<PageShift)) / size;

		switch(s->types.compression) {
		case MTypes_Empty:
			ntypes = (s->npages << PageShift) / size;
			nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
717
			data3 = runtime·mallocgc(nbytes3, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
Jan Ziak's avatar
Jan Ziak committed
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
			s->types.compression = MTypes_Bytes;
			s->types.data = (uintptr)data3;
			((uintptr*)data3)[1] = typ;
			data3[8*sizeof(uintptr) + ofs] = 1;
			break;

		case MTypes_Words:
			((uintptr*)s->types.data)[ofs] = typ;
			break;

		case MTypes_Bytes:
			data3 = (byte*)s->types.data;
			for(j=1; j<8; j++) {
				if(((uintptr*)data3)[j] == typ) {
					break;
				}
				if(((uintptr*)data3)[j] == 0) {
					((uintptr*)data3)[j] = typ;
					break;
				}
			}
			if(j < 8) {
				data3[8*sizeof(uintptr) + ofs] = j;
			} else {
				ntypes = (s->npages << PageShift) / size;
				nbytes2 = ntypes * sizeof(uintptr);
744
				data2 = runtime·mallocgc(nbytes2, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
Jan Ziak's avatar
Jan Ziak committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
				s->types.compression = MTypes_Words;
				s->types.data = (uintptr)data2;

				// Move the contents of data3 to data2. Then deallocate data3.
				for(j=0; j<ntypes; j++) {
					t = data3[8*sizeof(uintptr) + j];
					t = ((uintptr*)data3)[t];
					data2[j] = t;
				}
				data2[ofs] = typ;
			}
			break;
		}
	}
	runtime·unlock(&settype_lock);

761
	mp->settype_bufsize = 0;
Jan Ziak's avatar
Jan Ziak committed
762 763 764 765 766 767 768 769 770
}

uintptr
runtime·gettype(void *v)
{
	MSpan *s;
	uintptr t, ofs;
	byte *data;

771
	s = runtime·MHeap_LookupMaybe(&runtime·mheap, v);
Jan Ziak's avatar
Jan Ziak committed
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
	if(s != nil) {
		t = 0;
		switch(s->types.compression) {
		case MTypes_Empty:
			break;
		case MTypes_Single:
			t = s->types.data;
			break;
		case MTypes_Words:
			ofs = (uintptr)v - (s->start<<PageShift);
			t = ((uintptr*)s->types.data)[ofs/s->elemsize];
			break;
		case MTypes_Bytes:
			ofs = (uintptr)v - (s->start<<PageShift);
			data = (byte*)s->types.data;
			t = data[8*sizeof(uintptr) + ofs/s->elemsize];
			t = ((uintptr*)data)[t];
			break;
		default:
			runtime·throw("runtime·gettype: invalid compression kind");
		}
		if(0) {
			runtime·lock(&settype_lock);
			runtime·printf("%p -> %d,%X\n", v, (int32)s->types.compression, (int64)t);
			runtime·unlock(&settype_lock);
		}
		return t;
	}
	return 0;
}

Russ Cox's avatar
Russ Cox committed
803 804 805
// Runtime stubs.

void*
806
runtime·mal(uintptr n)
807
{
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
808
	return runtime·mallocgc(n, 0, 0);
Russ Cox's avatar
Russ Cox committed
809 810
}

811
#pragma textflag NOSPLIT
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
812 813 814
void
runtime·new(Type *typ, uint8 *ret)
{
815
	ret = runtime·mallocgc(typ->size, (uintptr)typ | TypeInfo_SingleObject, typ->kind&KindNoPointers ? FlagNoScan : 0);
816
	FLUSH(&ret);
817 818
}

819 820
static void*
cnew(Type *typ, intgo n, int32 objtyp)
821
{
822 823 824 825
	if((objtyp&(PtrSize-1)) != objtyp)
		runtime·throw("runtime: invalid objtyp");
	if(n < 0 || (typ->size > 0 && n > MaxMem/typ->size))
		runtime·panicstring("runtime: allocation size out of range");
826
	return runtime·mallocgc(typ->size*n, (uintptr)typ | objtyp, typ->kind&KindNoPointers ? FlagNoScan : 0);
827 828
}

829 830 831 832 833 834 835 836 837 838 839 840 841
// same as runtime·new, but callable from C
void*
runtime·cnew(Type *typ)
{
	return cnew(typ, 1, TypeInfo_SingleObject);
}

void*
runtime·cnewarray(Type *typ, intgo n)
{
	return cnew(typ, n, TypeInfo_Array);
}

842
func GC() {
843
	runtime·gc(1);
844
}
845 846 847 848 849

func SetFinalizer(obj Eface, finalizer Eface) {
	byte *base;
	uintptr size;
	FuncType *ft;
Russ Cox's avatar
Russ Cox committed
850 851
	int32 i;
	uintptr nret;
852
	Type *t;
853 854
	Type *fint;
	PtrType *ot;
855
	Iface iface;
856

857
	if(obj.type == nil) {
858
		runtime·printf("runtime.SetFinalizer: first argument is nil interface\n");
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
859
		goto throw;
860 861
	}
	if(obj.type->kind != KindPtr) {
862
		runtime·printf("runtime.SetFinalizer: first argument is %S, not pointer\n", *obj.type->string);
863 864
		goto throw;
	}
865
	ot = (PtrType*)obj.type;
866 867 868
	// As an implementation detail we do not run finalizers for zero-sized objects,
	// because we use &runtime·zerobase for all such allocations.
	if(ot->elem != nil && ot->elem->size == 0)
869
		return;
870
	if(!runtime·mlookup(obj.data, &base, &size, nil) || obj.data != base) {
871 872 873 874 875 876
		// As an implementation detail we allow to set finalizers for an inner byte
		// of an object if it could come from tiny alloc (see mallocgc for details).
		if(ot->elem == nil || (ot->elem->kind&KindNoPointers) == 0 || ot->elem->size >= TinySize) {
			runtime·printf("runtime.SetFinalizer: pointer not at beginning of allocated block\n");
			goto throw;
		}
877 878
	}
	if(finalizer.type != nil) {
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
879 880
		if(finalizer.type->kind != KindFunc)
			goto badfunc;
881
		ft = (FuncType*)finalizer.type;
882 883 884
		if(ft->dotdotdot || ft->in.len != 1)
			goto badfunc;
		fint = *(Type**)ft->in.array;
885 886 887 888 889 890 891 892 893 894
		if(fint == obj.type) {
			// ok - same type
		} else if(fint->kind == KindPtr && (fint->x == nil || fint->x->name == nil || obj.type->x == nil || obj.type->x->name == nil) && ((PtrType*)fint)->elem == ((PtrType*)obj.type)->elem) {
			// ok - not same type, but both pointers,
			// one or the other is unnamed, and same element type, so assignable.
		} else if(fint->kind == KindInterface && ((InterfaceType*)fint)->mhdr.len == 0) {
			// ok - satisfies empty interface
		} else if(fint->kind == KindInterface && runtime·ifaceE2I2((InterfaceType*)fint, obj, &iface)) {
			// ok - satisfies non-empty interface
		} else
895
			goto badfunc;
896

897
		// compute size needed for return parameters
898
		nret = 0;
899 900
		for(i=0; i<ft->out.len; i++) {
			t = ((Type**)ft->out.array)[i];
901
			nret = ROUND(nret, t->align) + t->size;
902
		}
903
		nret = ROUND(nret, sizeof(void*));
904 905 906 907 908 909 910 911
		ot = (PtrType*)obj.type;
		if(!runtime·addfinalizer(obj.data, finalizer.data, nret, fint, ot)) {
			runtime·printf("runtime.SetFinalizer: finalizer already set\n");
			goto throw;
		}
	} else {
		// NOTE: asking to remove a finalizer when there currently isn't one set is OK.
		runtime·removefinalizer(obj.data);
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
912 913 914 915
	}
	return;

badfunc:
916
	runtime·printf("runtime.SetFinalizer: cannot pass %S to finalizer %S\n", *obj.type->string, *finalizer.type->string);
Dmitriy Vyukov's avatar
Dmitriy Vyukov committed
917 918
throw:
	runtime·throw("runtime.SetFinalizer");
919
}