1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Per-thread (in Go, per-M) malloc cache for small objects.
7 // See malloc.h for an overview.
14 runtime_MCache_Alloc(MCache *c, int32 sizeclass, uintptr size, int32 zeroed)
20 // Allocate from list.
21 l = &c->list[sizeclass];
23 // Replenish using central lists.
24 n = runtime_MCentral_AllocList(&runtime_mheap.central[sizeclass],
25 runtime_class_to_transfercount[sizeclass], &first);
27 runtime_throw("out of memory");
35 if(l->nlist < l->nlistmin)
36 l->nlistmin = l->nlist;
39 // v is zeroed except for the link pointer
40 // that we used above; zero that.
43 // block is zeroed iff second word is zero ...
44 if(size > sizeof(uintptr) && ((uintptr*)v)[1] != 0)
45 runtime_memclr((byte*)v, size);
47 // ... except for the link pointer
48 // that we used above; zero that.
52 c->local_cachealloc += size;
57 // Take n elements off l and return them to the central free list.
59 ReleaseN(MCache *c, MCacheList *l, int32 n, int32 sizeclass)
64 // Cut off first n elements.
72 if(l->nlist < l->nlistmin)
73 l->nlistmin = l->nlist;
74 c->size -= n*runtime_class_to_size[sizeclass];
76 // Return them to central free list.
77 runtime_MCentral_FreeList(&runtime_mheap.central[sizeclass], n, first);
81 runtime_MCache_Free(MCache *c, void *v, int32 sizeclass, uintptr size)
88 l = &c->list[sizeclass];
94 c->local_cachealloc -= size;
97 if(l->nlist >= MaxMCacheListLen) {
98 // Release a chunk back.
99 ReleaseN(c, l, runtime_class_to_transfercount[sizeclass], sizeclass);
102 if(c->size >= MaxMCacheSize) {
104 for(i=0; i<NumSizeClasses; i++) {
108 // n is the minimum number of elements we've seen on
109 // the list since the last scavenge. If n > 0, it means that
110 // we could have gotten by with n fewer elements
111 // without needing to consult the central free list.
112 // Move toward that situation by releasing n/2 of them.
116 ReleaseN(c, l, n, i);
118 l->nlistmin = l->nlist;
124 runtime_MCache_ReleaseAll(MCache *c)
129 for(i=0; i<NumSizeClasses; i++) {
131 ReleaseN(c, l, l->nlist, i);