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 c->local_cachealloc += size;
52 // Take n elements off l and return them to the central free list.
54 ReleaseN(MCache *c, MCacheList *l, int32 n, int32 sizeclass)
59 // Cut off first n elements.
67 if(l->nlist < l->nlistmin)
68 l->nlistmin = l->nlist;
69 c->size -= n*runtime_class_to_size[sizeclass];
71 // Return them to central free list.
72 runtime_MCentral_FreeList(&runtime_mheap->central[sizeclass], n, first);
76 runtime_MCache_Free(MCache *c, void *v, int32 sizeclass, uintptr size)
83 l = &c->list[sizeclass];
89 c->local_cachealloc -= size;
92 if(l->nlist >= MaxMCacheListLen) {
93 // Release a chunk back.
94 ReleaseN(c, l, runtime_class_to_transfercount[sizeclass], sizeclass);
97 if(c->size >= MaxMCacheSize) {
99 for(i=0; i<NumSizeClasses; i++) {
103 // n is the minimum number of elements we've seen on
104 // the list since the last scavenge. If n > 0, it means that
105 // we could have gotten by with n fewer elements
106 // without needing to consult the central free list.
107 // Move toward that situation by releasing n/2 of them.
111 ReleaseN(c, l, n, i);
113 l->nlistmin = l->nlist;
119 runtime_MCache_ReleaseAll(MCache *c)
124 for(i=0; i<NumSizeClasses; i++) {
126 ReleaseN(c, l, l->nlist, i);