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.
13 runtime_MCache_Alloc(MCache
*c
, int32 sizeclass
, uintptr size
, int32 zeroed
)
19 // Allocate from list.
20 l
= &c
->list
[sizeclass
];
22 // Replenish using central lists.
23 n
= runtime_MCentral_AllocList(&runtime_mheap
.central
[sizeclass
],
24 runtime_class_to_transfercount
[sizeclass
], &first
);
32 if(l
->nlist
< l
->nlistmin
)
33 l
->nlistmin
= l
->nlist
;
36 // v is zeroed except for the link pointer
37 // that we used above; zero that.
40 // block is zeroed iff second word is zero ...
41 if(size
> sizeof(uintptr
) && ((uintptr
*)v
)[1] != 0)
42 runtime_memclr((byte
*)v
, size
);
44 // ... except for the link pointer
45 // that we used above; zero that.
49 c
->local_alloc
+= size
;
54 // Take n elements off l and return them to the central free list.
56 ReleaseN(MCache
*c
, MCacheList
*l
, int32 n
, int32 sizeclass
)
61 // Cut off first n elements.
69 if(l
->nlist
< l
->nlistmin
)
70 l
->nlistmin
= l
->nlist
;
71 c
->size
-= n
*runtime_class_to_size
[sizeclass
];
73 // Return them to central free list.
74 runtime_MCentral_FreeList(&runtime_mheap
.central
[sizeclass
], n
, first
);
78 runtime_MCache_Free(MCache
*c
, void *v
, int32 sizeclass
, uintptr size
)
85 l
= &c
->list
[sizeclass
];
91 c
->local_alloc
-= size
;
94 if(l
->nlist
>= MaxMCacheListLen
) {
95 // Release a chunk back.
96 ReleaseN(c
, l
, runtime_class_to_transfercount
[sizeclass
], sizeclass
);
99 if(c
->size
>= MaxMCacheSize
) {
101 for(i
=0; i
<NumSizeClasses
; i
++) {
105 // n is the minimum number of elements we've seen on
106 // the list since the last scavenge. If n > 0, it means that
107 // we could have gotten by with n fewer elements
108 // without needing to consult the central free list.
109 // Move toward that situation by releasing n/2 of them.
113 ReleaseN(c
, l
, n
, i
);
115 l
->nlistmin
= l
->nlist
;
121 runtime_MCache_ReleaseAll(MCache
*c
)
126 for(i
=0; i
<NumSizeClasses
; i
++) {
128 ReleaseN(c
, l
, l
->nlist
, i
);