mheap.c 8.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// 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.

// Page heap.
//
// See malloc.h for overview.
//
// When a MSpan is in the heap free list, state == MSpanFree
// and heapmap(s->start) == span, heapmap(s->start+s->npages-1) == span.
//
// When a MSpan is allocated, state == MSpanInUse
// and heapmap(i) == span for all s->start <= i < s->start+s->npages.

#include "runtime.h"
#include "malloc.h"

static MSpan *MHeap_AllocLocked(MHeap*, uintptr, int32);
static bool MHeap_Grow(MHeap*, uintptr);
static void MHeap_FreeLocked(MHeap*, MSpan*);
static MSpan *MHeap_AllocLarge(MHeap*, uintptr);
static MSpan *BestFit(MSpan*, uintptr, MSpan*);

24 25 26 27 28 29 30 31 32 33 34 35
static void
RecordSpan(void *vh, byte *p)
{
	MHeap *h;
	MSpan *s;

	h = vh;
	s = (MSpan*)p;
	s->allnext = h->allspans;
	h->allspans = s;
}

36 37 38 39
// Initialize the heap; fetch memory using alloc.
void
MHeap_Init(MHeap *h, void *(*alloc)(uintptr))
{
40
	uint32 i;
41

42 43
	FixAlloc_Init(&h->spanalloc, sizeof(MSpan), alloc, RecordSpan, h);
	FixAlloc_Init(&h->cachealloc, sizeof(MCache), alloc, nil, nil);
44 45 46 47 48 49 50 51 52 53 54 55
	MHeapMap_Init(&h->map, alloc);
	// h->mapcache needs no init
	for(i=0; i<nelem(h->free); i++)
		MSpanList_Init(&h->free[i]);
	MSpanList_Init(&h->large);
	for(i=0; i<nelem(h->central); i++)
		MCentral_Init(&h->central[i], i);
}

// Allocate a new span of npage pages from the heap
// and record its size class in the HeapMap and HeapMapCache.
MSpan*
56
MHeap_Alloc(MHeap *h, uintptr npage, int32 sizeclass, int32 acct)
57 58 59 60
{
	MSpan *s;

	lock(h);
61 62
	mstats.heap_alloc += m->mcache->local_alloc;
	m->mcache->local_alloc = 0;
63
	s = MHeap_AllocLocked(h, npage, sizeclass);
64
	if(s != nil) {
Russ Cox's avatar
Russ Cox committed
65
		mstats.heap_inuse += npage<<PageShift;
66 67 68
		if(acct)
			mstats.heap_alloc += npage<<PageShift;
	}
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 96 97 98 99 100 101 102 103 104 105 106
	unlock(h);
	return s;
}

static MSpan*
MHeap_AllocLocked(MHeap *h, uintptr npage, int32 sizeclass)
{
	uintptr n;
	MSpan *s, *t;

	// Try in fixed-size lists up to max.
	for(n=npage; n < nelem(h->free); n++) {
		if(!MSpanList_IsEmpty(&h->free[n])) {
			s = h->free[n].next;
			goto HaveSpan;
		}
	}

	// Best fit in list of large spans.
	if((s = MHeap_AllocLarge(h, npage)) == nil) {
		if(!MHeap_Grow(h, npage))
			return nil;
		if((s = MHeap_AllocLarge(h, npage)) == nil)
			return nil;
	}

HaveSpan:
	// Mark span in use.
	if(s->state != MSpanFree)
		throw("MHeap_AllocLocked - MSpan not free");
	if(s->npages < npage)
		throw("MHeap_AllocLocked - bad npages");
	MSpanList_Remove(s);
	s->state = MSpanInUse;

	if(s->npages > npage) {
		// Trim extra and put it back in the heap.
		t = FixAlloc_Alloc(&h->spanalloc);
Russ Cox's avatar
Russ Cox committed
107 108
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
109 110 111 112 113 114 115 116 117
		MSpan_Init(t, s->start + npage, s->npages - npage);
		s->npages = npage;
		MHeapMap_Set(&h->map, t->start - 1, s);
		MHeapMap_Set(&h->map, t->start, t);
		MHeapMap_Set(&h->map, t->start + t->npages - 1, t);
		t->state = MSpanInUse;
		MHeap_FreeLocked(h, t);
	}

118
	// Record span info, because gc needs to be
119 120
	// able to map interior pointer to containing span.
	s->sizeclass = sizeclass;
Russ Cox's avatar
Russ Cox committed
121
	for(n=0; n<npage; n++)
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
		MHeapMap_Set(&h->map, s->start+n, s);
	return s;
}

// Allocate a span of exactly npage pages from the list of large spans.
static MSpan*
MHeap_AllocLarge(MHeap *h, uintptr npage)
{
	return BestFit(&h->large, npage, nil);
}

// Search list for smallest span with >= npage pages.
// If there are multiple smallest spans, take the one
// with the earliest starting address.
static MSpan*
BestFit(MSpan *list, uintptr npage, MSpan *best)
{
	MSpan *s;

	for(s=list->next; s != list; s=s->next) {
		if(s->npages < npage)
			continue;
		if(best == nil
		|| s->npages < best->npages
		|| (s->npages == best->npages && s->start < best->start))
			best = s;
	}
	return best;
}

// Try to add at least npage pages of memory to the heap,
// returning whether it worked.
static bool
MHeap_Grow(MHeap *h, uintptr npage)
{
	uintptr ask;
	void *v;
	MSpan *s;

	// Ask for a big chunk, to reduce the number of mappings
	// the operating system needs to track; also amortizes
	// the overhead of an operating system mapping.
Russ Cox's avatar
Russ Cox committed
164 165
	// For Native Client, allocate a multiple of 64kB (16 pages).
	npage = (npage+15)&~15;
166 167 168 169 170 171 172 173 174 175 176 177 178 179
	ask = npage<<PageShift;
	if(ask < HeapAllocChunk)
		ask = HeapAllocChunk;

	v = SysAlloc(ask);
	if(v == nil) {
		if(ask > (npage<<PageShift)) {
			ask = npage<<PageShift;
			v = SysAlloc(ask);
		}
		if(v == nil)
			return false;
	}

Russ Cox's avatar
Russ Cox committed
180 181 182 183 184
	if((byte*)v < h->min || h->min == nil)
		h->min = v;
	if((byte*)v+ask > h->max)
		h->max = (byte*)v+ask;

185 186 187 188 189 190 191 192
	// NOTE(rsc): In tcmalloc, if we've accumulated enough
	// system allocations, the heap map gets entirely allocated
	// in 32-bit mode.  (In 64-bit mode that's not practical.)
	if(!MHeapMap_Preallocate(&h->map, ((uintptr)v>>PageShift) - 1, (ask>>PageShift) + 2)) {
		SysFree(v, ask);
		return false;
	}

Russ Cox's avatar
Russ Cox committed
193 194
	// Create a fake "in use" span and free it, so that the
	// right coalescing happens.
195
	s = FixAlloc_Alloc(&h->spanalloc);
Russ Cox's avatar
Russ Cox committed
196 197
	mstats.mspan_inuse = h->spanalloc.inuse;
	mstats.mspan_sys = h->spanalloc.sys;
198 199 200 201 202 203 204 205 206
	MSpan_Init(s, (uintptr)v>>PageShift, ask>>PageShift);
	MHeapMap_Set(&h->map, s->start, s);
	MHeapMap_Set(&h->map, s->start + s->npages - 1, s);
	s->state = MSpanInUse;
	MHeap_FreeLocked(h, s);
	return true;
}

// Look up the span at the given page number.
Russ Cox's avatar
Russ Cox committed
207 208
// Page number is guaranteed to be in map
// and is guaranteed to be start or end of span.
209 210 211 212 213 214
MSpan*
MHeap_Lookup(MHeap *h, PageID p)
{
	return MHeapMap_Get(&h->map, p);
}

Russ Cox's avatar
Russ Cox committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
// Look up the span at the given page number.
// Page number is *not* guaranteed to be in map
// and may be anywhere in the span.
// Map entries for the middle of a span are only
// valid for allocated spans.  Free spans may have
// other garbage in their middles, so we have to
// check for that.
MSpan*
MHeap_LookupMaybe(MHeap *h, PageID p)
{
	MSpan *s;

	s = MHeapMap_GetMaybe(&h->map, p);
	if(s == nil || p < s->start || p - s->start >= s->npages)
		return nil;
230 231
	if(s->state != MSpanInUse)
		return nil;
Russ Cox's avatar
Russ Cox committed
232 233 234
	return s;
}

235 236
// Free the span back into the heap.
void
237
MHeap_Free(MHeap *h, MSpan *s, int32 acct)
238 239
{
	lock(h);
240 241
	mstats.heap_alloc += m->mcache->local_alloc;
	m->mcache->local_alloc = 0;
Russ Cox's avatar
Russ Cox committed
242
	mstats.heap_inuse -= s->npages<<PageShift;
243 244
	if(acct)
		mstats.heap_alloc -= s->npages<<PageShift;
245 246 247 248 249 250 251 252 253
	MHeap_FreeLocked(h, s);
	unlock(h);
}

static void
MHeap_FreeLocked(MHeap *h, MSpan *s)
{
	MSpan *t;

Russ Cox's avatar
Russ Cox committed
254 255
	if(s->state != MSpanInUse || s->ref != 0) {
		printf("MHeap_FreeLocked - span %p ptr %p state %d ref %d\n", s, s->start<<PageShift, s->state, s->ref);
256
		throw("MHeap_FreeLocked - invalid free");
Russ Cox's avatar
Russ Cox committed
257
	}
258 259 260 261 262 263 264 265 266
	s->state = MSpanFree;
	MSpanList_Remove(s);

	// Coalesce with earlier, later spans.
	if((t = MHeapMap_Get(&h->map, s->start - 1)) != nil && t->state != MSpanInUse) {
		s->start = t->start;
		s->npages += t->npages;
		MHeapMap_Set(&h->map, s->start, s);
		MSpanList_Remove(t);
267
		t->state = MSpanDead;
268
		FixAlloc_Free(&h->spanalloc, t);
Russ Cox's avatar
Russ Cox committed
269 270
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
271 272 273 274 275
	}
	if((t = MHeapMap_Get(&h->map, s->start + s->npages)) != nil && t->state != MSpanInUse) {
		s->npages += t->npages;
		MHeapMap_Set(&h->map, s->start + s->npages - 1, s);
		MSpanList_Remove(t);
276
		t->state = MSpanDead;
277
		FixAlloc_Free(&h->spanalloc, t);
Russ Cox's avatar
Russ Cox committed
278 279
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
	}

	// Insert s into appropriate list.
	if(s->npages < nelem(h->free))
		MSpanList_Insert(&h->free[s->npages], s);
	else
		MSpanList_Insert(&h->large, s);

	// TODO(rsc): IncrementalScavenge() to return memory to OS.
}

// Initialize a new span with the given start and npages.
void
MSpan_Init(MSpan *span, PageID start, uintptr npages)
{
	span->next = nil;
	span->prev = nil;
	span->start = start;
	span->npages = npages;
	span->freelist = nil;
	span->ref = 0;
	span->sizeclass = 0;
	span->state = 0;
}

// Initialize an empty doubly-linked list.
void
MSpanList_Init(MSpan *list)
{
309
	list->state = MSpanListHead;
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
	list->next = list;
	list->prev = list;
}

void
MSpanList_Remove(MSpan *span)
{
	if(span->prev == nil && span->next == nil)
		return;
	span->prev->next = span->next;
	span->next->prev = span->prev;
	span->prev = nil;
	span->next = nil;
}

bool
MSpanList_IsEmpty(MSpan *list)
{
	return list->next == list;
}

void
MSpanList_Insert(MSpan *list, MSpan *span)
{
	if(span->next != nil || span->prev != nil)
		throw("MSpanList_Insert");
	span->next = list->next;
	span->prev = list;
	span->next->prev = span;
	span->prev->next = span;
}