annotate libsanitizer/sanitizer_common/sanitizer_allocator_primary64.h @ 118:fd00160c1b76

ifdef TARGET_64BIT
author mir3636
date Tue, 27 Feb 2018 15:01:35 +0900
parents 04ced10e8804
children 1830386684a0
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
111
kono
parents:
diff changeset
1 //===-- sanitizer_allocator_primary64.h -------------------------*- C++ -*-===//
kono
parents:
diff changeset
2 //
kono
parents:
diff changeset
3 // This file is distributed under the University of Illinois Open Source
kono
parents:
diff changeset
4 // License. See LICENSE.TXT for details.
kono
parents:
diff changeset
5 //
kono
parents:
diff changeset
6 //===----------------------------------------------------------------------===//
kono
parents:
diff changeset
7 //
kono
parents:
diff changeset
8 // Part of the Sanitizer Allocator.
kono
parents:
diff changeset
9 //
kono
parents:
diff changeset
10 //===----------------------------------------------------------------------===//
kono
parents:
diff changeset
11 #ifndef SANITIZER_ALLOCATOR_H
kono
parents:
diff changeset
12 #error This file must be included inside sanitizer_allocator.h
kono
parents:
diff changeset
13 #endif
kono
parents:
diff changeset
14
kono
parents:
diff changeset
15 template<class SizeClassAllocator> struct SizeClassAllocator64LocalCache;
kono
parents:
diff changeset
16
kono
parents:
diff changeset
17 // SizeClassAllocator64 -- allocator for 64-bit address space.
kono
parents:
diff changeset
18 // The template parameter Params is a class containing the actual parameters.
kono
parents:
diff changeset
19 //
kono
parents:
diff changeset
20 // Space: a portion of address space of kSpaceSize bytes starting at SpaceBeg.
kono
parents:
diff changeset
21 // If kSpaceBeg is ~0 then SpaceBeg is chosen dynamically my mmap.
kono
parents:
diff changeset
22 // Otherwise SpaceBeg=kSpaceBeg (fixed address).
kono
parents:
diff changeset
23 // kSpaceSize is a power of two.
kono
parents:
diff changeset
24 // At the beginning the entire space is mprotect-ed, then small parts of it
kono
parents:
diff changeset
25 // are mapped on demand.
kono
parents:
diff changeset
26 //
kono
parents:
diff changeset
27 // Region: a part of Space dedicated to a single size class.
kono
parents:
diff changeset
28 // There are kNumClasses Regions of equal size.
kono
parents:
diff changeset
29 //
kono
parents:
diff changeset
30 // UserChunk: a piece of memory returned to user.
kono
parents:
diff changeset
31 // MetaChunk: kMetadataSize bytes of metadata associated with a UserChunk.
kono
parents:
diff changeset
32
kono
parents:
diff changeset
33 // FreeArray is an array free-d chunks (stored as 4-byte offsets)
kono
parents:
diff changeset
34 //
kono
parents:
diff changeset
35 // A Region looks like this:
kono
parents:
diff changeset
36 // UserChunk1 ... UserChunkN <gap> MetaChunkN ... MetaChunk1 FreeArray
kono
parents:
diff changeset
37
kono
parents:
diff changeset
38 struct SizeClassAllocator64FlagMasks { // Bit masks.
kono
parents:
diff changeset
39 enum {
kono
parents:
diff changeset
40 kRandomShuffleChunks = 1,
kono
parents:
diff changeset
41 };
kono
parents:
diff changeset
42 };
kono
parents:
diff changeset
43
kono
parents:
diff changeset
44 template <class Params>
kono
parents:
diff changeset
45 class SizeClassAllocator64 {
kono
parents:
diff changeset
46 public:
kono
parents:
diff changeset
47 static const uptr kSpaceBeg = Params::kSpaceBeg;
kono
parents:
diff changeset
48 static const uptr kSpaceSize = Params::kSpaceSize;
kono
parents:
diff changeset
49 static const uptr kMetadataSize = Params::kMetadataSize;
kono
parents:
diff changeset
50 typedef typename Params::SizeClassMap SizeClassMap;
kono
parents:
diff changeset
51 typedef typename Params::MapUnmapCallback MapUnmapCallback;
kono
parents:
diff changeset
52
kono
parents:
diff changeset
53 static const bool kRandomShuffleChunks =
kono
parents:
diff changeset
54 Params::kFlags & SizeClassAllocator64FlagMasks::kRandomShuffleChunks;
kono
parents:
diff changeset
55
kono
parents:
diff changeset
56 typedef SizeClassAllocator64<Params> ThisT;
kono
parents:
diff changeset
57 typedef SizeClassAllocator64LocalCache<ThisT> AllocatorCache;
kono
parents:
diff changeset
58
kono
parents:
diff changeset
59 // When we know the size class (the region base) we can represent a pointer
kono
parents:
diff changeset
60 // as a 4-byte integer (offset from the region start shifted right by 4).
kono
parents:
diff changeset
61 typedef u32 CompactPtrT;
kono
parents:
diff changeset
62 static const uptr kCompactPtrScale = 4;
kono
parents:
diff changeset
63 CompactPtrT PointerToCompactPtr(uptr base, uptr ptr) const {
kono
parents:
diff changeset
64 return static_cast<CompactPtrT>((ptr - base) >> kCompactPtrScale);
kono
parents:
diff changeset
65 }
kono
parents:
diff changeset
66 uptr CompactPtrToPointer(uptr base, CompactPtrT ptr32) const {
kono
parents:
diff changeset
67 return base + (static_cast<uptr>(ptr32) << kCompactPtrScale);
kono
parents:
diff changeset
68 }
kono
parents:
diff changeset
69
kono
parents:
diff changeset
70 void Init(s32 release_to_os_interval_ms) {
kono
parents:
diff changeset
71 uptr TotalSpaceSize = kSpaceSize + AdditionalSize();
kono
parents:
diff changeset
72 if (kUsingConstantSpaceBeg) {
kono
parents:
diff changeset
73 CHECK_EQ(kSpaceBeg, reinterpret_cast<uptr>(
kono
parents:
diff changeset
74 MmapFixedNoAccess(kSpaceBeg, TotalSpaceSize)));
kono
parents:
diff changeset
75 } else {
kono
parents:
diff changeset
76 NonConstSpaceBeg =
kono
parents:
diff changeset
77 reinterpret_cast<uptr>(MmapNoAccess(TotalSpaceSize));
kono
parents:
diff changeset
78 CHECK_NE(NonConstSpaceBeg, ~(uptr)0);
kono
parents:
diff changeset
79 }
kono
parents:
diff changeset
80 SetReleaseToOSIntervalMs(release_to_os_interval_ms);
kono
parents:
diff changeset
81 MapWithCallbackOrDie(SpaceEnd(), AdditionalSize());
kono
parents:
diff changeset
82 }
kono
parents:
diff changeset
83
kono
parents:
diff changeset
84 s32 ReleaseToOSIntervalMs() const {
kono
parents:
diff changeset
85 return atomic_load(&release_to_os_interval_ms_, memory_order_relaxed);
kono
parents:
diff changeset
86 }
kono
parents:
diff changeset
87
kono
parents:
diff changeset
88 void SetReleaseToOSIntervalMs(s32 release_to_os_interval_ms) {
kono
parents:
diff changeset
89 atomic_store(&release_to_os_interval_ms_, release_to_os_interval_ms,
kono
parents:
diff changeset
90 memory_order_relaxed);
kono
parents:
diff changeset
91 }
kono
parents:
diff changeset
92
kono
parents:
diff changeset
93 static bool CanAllocate(uptr size, uptr alignment) {
kono
parents:
diff changeset
94 return size <= SizeClassMap::kMaxSize &&
kono
parents:
diff changeset
95 alignment <= SizeClassMap::kMaxSize;
kono
parents:
diff changeset
96 }
kono
parents:
diff changeset
97
kono
parents:
diff changeset
98 NOINLINE void ReturnToAllocator(AllocatorStats *stat, uptr class_id,
kono
parents:
diff changeset
99 const CompactPtrT *chunks, uptr n_chunks) {
kono
parents:
diff changeset
100 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
101 uptr region_beg = GetRegionBeginBySizeClass(class_id);
kono
parents:
diff changeset
102 CompactPtrT *free_array = GetFreeArray(region_beg);
kono
parents:
diff changeset
103
kono
parents:
diff changeset
104 BlockingMutexLock l(&region->mutex);
kono
parents:
diff changeset
105 uptr old_num_chunks = region->num_freed_chunks;
kono
parents:
diff changeset
106 uptr new_num_freed_chunks = old_num_chunks + n_chunks;
kono
parents:
diff changeset
107 // Failure to allocate free array space while releasing memory is non
kono
parents:
diff changeset
108 // recoverable.
kono
parents:
diff changeset
109 if (UNLIKELY(!EnsureFreeArraySpace(region, region_beg,
kono
parents:
diff changeset
110 new_num_freed_chunks)))
kono
parents:
diff changeset
111 DieOnFailure::OnOOM();
kono
parents:
diff changeset
112 for (uptr i = 0; i < n_chunks; i++)
kono
parents:
diff changeset
113 free_array[old_num_chunks + i] = chunks[i];
kono
parents:
diff changeset
114 region->num_freed_chunks = new_num_freed_chunks;
kono
parents:
diff changeset
115 region->stats.n_freed += n_chunks;
kono
parents:
diff changeset
116
kono
parents:
diff changeset
117 MaybeReleaseToOS(class_id);
kono
parents:
diff changeset
118 }
kono
parents:
diff changeset
119
kono
parents:
diff changeset
120 NOINLINE bool GetFromAllocator(AllocatorStats *stat, uptr class_id,
kono
parents:
diff changeset
121 CompactPtrT *chunks, uptr n_chunks) {
kono
parents:
diff changeset
122 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
123 uptr region_beg = GetRegionBeginBySizeClass(class_id);
kono
parents:
diff changeset
124 CompactPtrT *free_array = GetFreeArray(region_beg);
kono
parents:
diff changeset
125
kono
parents:
diff changeset
126 BlockingMutexLock l(&region->mutex);
kono
parents:
diff changeset
127 if (UNLIKELY(region->num_freed_chunks < n_chunks)) {
kono
parents:
diff changeset
128 if (UNLIKELY(!PopulateFreeArray(stat, class_id, region,
kono
parents:
diff changeset
129 n_chunks - region->num_freed_chunks)))
kono
parents:
diff changeset
130 return false;
kono
parents:
diff changeset
131 CHECK_GE(region->num_freed_chunks, n_chunks);
kono
parents:
diff changeset
132 }
kono
parents:
diff changeset
133 region->num_freed_chunks -= n_chunks;
kono
parents:
diff changeset
134 uptr base_idx = region->num_freed_chunks;
kono
parents:
diff changeset
135 for (uptr i = 0; i < n_chunks; i++)
kono
parents:
diff changeset
136 chunks[i] = free_array[base_idx + i];
kono
parents:
diff changeset
137 region->stats.n_allocated += n_chunks;
kono
parents:
diff changeset
138 return true;
kono
parents:
diff changeset
139 }
kono
parents:
diff changeset
140
kono
parents:
diff changeset
141 bool PointerIsMine(const void *p) {
kono
parents:
diff changeset
142 uptr P = reinterpret_cast<uptr>(p);
kono
parents:
diff changeset
143 if (kUsingConstantSpaceBeg && (kSpaceBeg % kSpaceSize) == 0)
kono
parents:
diff changeset
144 return P / kSpaceSize == kSpaceBeg / kSpaceSize;
kono
parents:
diff changeset
145 return P >= SpaceBeg() && P < SpaceEnd();
kono
parents:
diff changeset
146 }
kono
parents:
diff changeset
147
kono
parents:
diff changeset
148 uptr GetRegionBegin(const void *p) {
kono
parents:
diff changeset
149 if (kUsingConstantSpaceBeg)
kono
parents:
diff changeset
150 return reinterpret_cast<uptr>(p) & ~(kRegionSize - 1);
kono
parents:
diff changeset
151 uptr space_beg = SpaceBeg();
kono
parents:
diff changeset
152 return ((reinterpret_cast<uptr>(p) - space_beg) & ~(kRegionSize - 1)) +
kono
parents:
diff changeset
153 space_beg;
kono
parents:
diff changeset
154 }
kono
parents:
diff changeset
155
kono
parents:
diff changeset
156 uptr GetRegionBeginBySizeClass(uptr class_id) const {
kono
parents:
diff changeset
157 return SpaceBeg() + kRegionSize * class_id;
kono
parents:
diff changeset
158 }
kono
parents:
diff changeset
159
kono
parents:
diff changeset
160 uptr GetSizeClass(const void *p) {
kono
parents:
diff changeset
161 if (kUsingConstantSpaceBeg && (kSpaceBeg % kSpaceSize) == 0)
kono
parents:
diff changeset
162 return ((reinterpret_cast<uptr>(p)) / kRegionSize) % kNumClassesRounded;
kono
parents:
diff changeset
163 return ((reinterpret_cast<uptr>(p) - SpaceBeg()) / kRegionSize) %
kono
parents:
diff changeset
164 kNumClassesRounded;
kono
parents:
diff changeset
165 }
kono
parents:
diff changeset
166
kono
parents:
diff changeset
167 void *GetBlockBegin(const void *p) {
kono
parents:
diff changeset
168 uptr class_id = GetSizeClass(p);
kono
parents:
diff changeset
169 uptr size = ClassIdToSize(class_id);
kono
parents:
diff changeset
170 if (!size) return nullptr;
kono
parents:
diff changeset
171 uptr chunk_idx = GetChunkIdx((uptr)p, size);
kono
parents:
diff changeset
172 uptr reg_beg = GetRegionBegin(p);
kono
parents:
diff changeset
173 uptr beg = chunk_idx * size;
kono
parents:
diff changeset
174 uptr next_beg = beg + size;
kono
parents:
diff changeset
175 if (class_id >= kNumClasses) return nullptr;
kono
parents:
diff changeset
176 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
177 if (region->mapped_user >= next_beg)
kono
parents:
diff changeset
178 return reinterpret_cast<void*>(reg_beg + beg);
kono
parents:
diff changeset
179 return nullptr;
kono
parents:
diff changeset
180 }
kono
parents:
diff changeset
181
kono
parents:
diff changeset
182 uptr GetActuallyAllocatedSize(void *p) {
kono
parents:
diff changeset
183 CHECK(PointerIsMine(p));
kono
parents:
diff changeset
184 return ClassIdToSize(GetSizeClass(p));
kono
parents:
diff changeset
185 }
kono
parents:
diff changeset
186
kono
parents:
diff changeset
187 uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
kono
parents:
diff changeset
188
kono
parents:
diff changeset
189 void *GetMetaData(const void *p) {
kono
parents:
diff changeset
190 uptr class_id = GetSizeClass(p);
kono
parents:
diff changeset
191 uptr size = ClassIdToSize(class_id);
kono
parents:
diff changeset
192 uptr chunk_idx = GetChunkIdx(reinterpret_cast<uptr>(p), size);
kono
parents:
diff changeset
193 uptr region_beg = GetRegionBeginBySizeClass(class_id);
kono
parents:
diff changeset
194 return reinterpret_cast<void *>(GetMetadataEnd(region_beg) -
kono
parents:
diff changeset
195 (1 + chunk_idx) * kMetadataSize);
kono
parents:
diff changeset
196 }
kono
parents:
diff changeset
197
kono
parents:
diff changeset
198 uptr TotalMemoryUsed() {
kono
parents:
diff changeset
199 uptr res = 0;
kono
parents:
diff changeset
200 for (uptr i = 0; i < kNumClasses; i++)
kono
parents:
diff changeset
201 res += GetRegionInfo(i)->allocated_user;
kono
parents:
diff changeset
202 return res;
kono
parents:
diff changeset
203 }
kono
parents:
diff changeset
204
kono
parents:
diff changeset
205 // Test-only.
kono
parents:
diff changeset
206 void TestOnlyUnmap() {
kono
parents:
diff changeset
207 UnmapWithCallbackOrDie(SpaceBeg(), kSpaceSize + AdditionalSize());
kono
parents:
diff changeset
208 }
kono
parents:
diff changeset
209
kono
parents:
diff changeset
210 static void FillMemoryProfile(uptr start, uptr rss, bool file, uptr *stats,
kono
parents:
diff changeset
211 uptr stats_size) {
kono
parents:
diff changeset
212 for (uptr class_id = 0; class_id < stats_size; class_id++)
kono
parents:
diff changeset
213 if (stats[class_id] == start)
kono
parents:
diff changeset
214 stats[class_id] = rss;
kono
parents:
diff changeset
215 }
kono
parents:
diff changeset
216
kono
parents:
diff changeset
217 void PrintStats(uptr class_id, uptr rss) {
kono
parents:
diff changeset
218 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
219 if (region->mapped_user == 0) return;
kono
parents:
diff changeset
220 uptr in_use = region->stats.n_allocated - region->stats.n_freed;
kono
parents:
diff changeset
221 uptr avail_chunks = region->allocated_user / ClassIdToSize(class_id);
kono
parents:
diff changeset
222 Printf(
kono
parents:
diff changeset
223 "%s %02zd (%6zd): mapped: %6zdK allocs: %7zd frees: %7zd inuse: %6zd "
kono
parents:
diff changeset
224 "num_freed_chunks %7zd avail: %6zd rss: %6zdK releases: %6zd "
kono
parents:
diff changeset
225 "last released: %6zdK region: 0x%zx\n",
kono
parents:
diff changeset
226 region->exhausted ? "F" : " ", class_id, ClassIdToSize(class_id),
kono
parents:
diff changeset
227 region->mapped_user >> 10, region->stats.n_allocated,
kono
parents:
diff changeset
228 region->stats.n_freed, in_use, region->num_freed_chunks, avail_chunks,
kono
parents:
diff changeset
229 rss >> 10, region->rtoi.num_releases,
kono
parents:
diff changeset
230 region->rtoi.last_released_bytes >> 10,
kono
parents:
diff changeset
231 SpaceBeg() + kRegionSize * class_id);
kono
parents:
diff changeset
232 }
kono
parents:
diff changeset
233
kono
parents:
diff changeset
234 void PrintStats() {
kono
parents:
diff changeset
235 uptr total_mapped = 0;
kono
parents:
diff changeset
236 uptr n_allocated = 0;
kono
parents:
diff changeset
237 uptr n_freed = 0;
kono
parents:
diff changeset
238 for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
kono
parents:
diff changeset
239 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
240 total_mapped += region->mapped_user;
kono
parents:
diff changeset
241 n_allocated += region->stats.n_allocated;
kono
parents:
diff changeset
242 n_freed += region->stats.n_freed;
kono
parents:
diff changeset
243 }
kono
parents:
diff changeset
244 Printf("Stats: SizeClassAllocator64: %zdM mapped in %zd allocations; "
kono
parents:
diff changeset
245 "remains %zd\n",
kono
parents:
diff changeset
246 total_mapped >> 20, n_allocated, n_allocated - n_freed);
kono
parents:
diff changeset
247 uptr rss_stats[kNumClasses];
kono
parents:
diff changeset
248 for (uptr class_id = 0; class_id < kNumClasses; class_id++)
kono
parents:
diff changeset
249 rss_stats[class_id] = SpaceBeg() + kRegionSize * class_id;
kono
parents:
diff changeset
250 GetMemoryProfile(FillMemoryProfile, rss_stats, kNumClasses);
kono
parents:
diff changeset
251 for (uptr class_id = 1; class_id < kNumClasses; class_id++)
kono
parents:
diff changeset
252 PrintStats(class_id, rss_stats[class_id]);
kono
parents:
diff changeset
253 }
kono
parents:
diff changeset
254
kono
parents:
diff changeset
255 // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
kono
parents:
diff changeset
256 // introspection API.
kono
parents:
diff changeset
257 void ForceLock() {
kono
parents:
diff changeset
258 for (uptr i = 0; i < kNumClasses; i++) {
kono
parents:
diff changeset
259 GetRegionInfo(i)->mutex.Lock();
kono
parents:
diff changeset
260 }
kono
parents:
diff changeset
261 }
kono
parents:
diff changeset
262
kono
parents:
diff changeset
263 void ForceUnlock() {
kono
parents:
diff changeset
264 for (int i = (int)kNumClasses - 1; i >= 0; i--) {
kono
parents:
diff changeset
265 GetRegionInfo(i)->mutex.Unlock();
kono
parents:
diff changeset
266 }
kono
parents:
diff changeset
267 }
kono
parents:
diff changeset
268
kono
parents:
diff changeset
269 // Iterate over all existing chunks.
kono
parents:
diff changeset
270 // The allocator must be locked when calling this function.
kono
parents:
diff changeset
271 void ForEachChunk(ForEachChunkCallback callback, void *arg) {
kono
parents:
diff changeset
272 for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
kono
parents:
diff changeset
273 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
274 uptr chunk_size = ClassIdToSize(class_id);
kono
parents:
diff changeset
275 uptr region_beg = SpaceBeg() + class_id * kRegionSize;
kono
parents:
diff changeset
276 for (uptr chunk = region_beg;
kono
parents:
diff changeset
277 chunk < region_beg + region->allocated_user;
kono
parents:
diff changeset
278 chunk += chunk_size) {
kono
parents:
diff changeset
279 // Too slow: CHECK_EQ((void *)chunk, GetBlockBegin((void *)chunk));
kono
parents:
diff changeset
280 callback(chunk, arg);
kono
parents:
diff changeset
281 }
kono
parents:
diff changeset
282 }
kono
parents:
diff changeset
283 }
kono
parents:
diff changeset
284
kono
parents:
diff changeset
285 static uptr ClassIdToSize(uptr class_id) {
kono
parents:
diff changeset
286 return SizeClassMap::Size(class_id);
kono
parents:
diff changeset
287 }
kono
parents:
diff changeset
288
kono
parents:
diff changeset
289 static uptr AdditionalSize() {
kono
parents:
diff changeset
290 return RoundUpTo(sizeof(RegionInfo) * kNumClassesRounded,
kono
parents:
diff changeset
291 GetPageSizeCached());
kono
parents:
diff changeset
292 }
kono
parents:
diff changeset
293
kono
parents:
diff changeset
294 typedef SizeClassMap SizeClassMapT;
kono
parents:
diff changeset
295 static const uptr kNumClasses = SizeClassMap::kNumClasses;
kono
parents:
diff changeset
296 static const uptr kNumClassesRounded = SizeClassMap::kNumClassesRounded;
kono
parents:
diff changeset
297
kono
parents:
diff changeset
298 // A packed array of counters. Each counter occupies 2^n bits, enough to store
kono
parents:
diff changeset
299 // counter's max_value. Ctor will try to allocate the required buffer via
kono
parents:
diff changeset
300 // mapper->MapPackedCounterArrayBuffer and the caller is expected to check
kono
parents:
diff changeset
301 // whether the initialization was successful by checking IsAllocated() result.
kono
parents:
diff changeset
302 // For the performance sake, none of the accessors check the validity of the
kono
parents:
diff changeset
303 // arguments, it is assumed that index is always in [0, n) range and the value
kono
parents:
diff changeset
304 // is not incremented past max_value.
kono
parents:
diff changeset
305 template<class MemoryMapperT>
kono
parents:
diff changeset
306 class PackedCounterArray {
kono
parents:
diff changeset
307 public:
kono
parents:
diff changeset
308 PackedCounterArray(u64 num_counters, u64 max_value, MemoryMapperT *mapper)
kono
parents:
diff changeset
309 : n(num_counters), memory_mapper(mapper) {
kono
parents:
diff changeset
310 CHECK_GT(num_counters, 0);
kono
parents:
diff changeset
311 CHECK_GT(max_value, 0);
kono
parents:
diff changeset
312 constexpr u64 kMaxCounterBits = sizeof(*buffer) * 8ULL;
kono
parents:
diff changeset
313 // Rounding counter storage size up to the power of two allows for using
kono
parents:
diff changeset
314 // bit shifts calculating particular counter's index and offset.
kono
parents:
diff changeset
315 uptr counter_size_bits =
kono
parents:
diff changeset
316 RoundUpToPowerOfTwo(MostSignificantSetBitIndex(max_value) + 1);
kono
parents:
diff changeset
317 CHECK_LE(counter_size_bits, kMaxCounterBits);
kono
parents:
diff changeset
318 counter_size_bits_log = Log2(counter_size_bits);
kono
parents:
diff changeset
319 counter_mask = ~0ULL >> (kMaxCounterBits - counter_size_bits);
kono
parents:
diff changeset
320
kono
parents:
diff changeset
321 uptr packing_ratio = kMaxCounterBits >> counter_size_bits_log;
kono
parents:
diff changeset
322 CHECK_GT(packing_ratio, 0);
kono
parents:
diff changeset
323 packing_ratio_log = Log2(packing_ratio);
kono
parents:
diff changeset
324 bit_offset_mask = packing_ratio - 1;
kono
parents:
diff changeset
325
kono
parents:
diff changeset
326 buffer_size =
kono
parents:
diff changeset
327 (RoundUpTo(n, 1ULL << packing_ratio_log) >> packing_ratio_log) *
kono
parents:
diff changeset
328 sizeof(*buffer);
kono
parents:
diff changeset
329 buffer = reinterpret_cast<u64*>(
kono
parents:
diff changeset
330 memory_mapper->MapPackedCounterArrayBuffer(buffer_size));
kono
parents:
diff changeset
331 }
kono
parents:
diff changeset
332 ~PackedCounterArray() {
kono
parents:
diff changeset
333 if (buffer) {
kono
parents:
diff changeset
334 memory_mapper->UnmapPackedCounterArrayBuffer(
kono
parents:
diff changeset
335 reinterpret_cast<uptr>(buffer), buffer_size);
kono
parents:
diff changeset
336 }
kono
parents:
diff changeset
337 }
kono
parents:
diff changeset
338
kono
parents:
diff changeset
339 bool IsAllocated() const {
kono
parents:
diff changeset
340 return !!buffer;
kono
parents:
diff changeset
341 }
kono
parents:
diff changeset
342
kono
parents:
diff changeset
343 u64 GetCount() const {
kono
parents:
diff changeset
344 return n;
kono
parents:
diff changeset
345 }
kono
parents:
diff changeset
346
kono
parents:
diff changeset
347 uptr Get(uptr i) const {
kono
parents:
diff changeset
348 DCHECK_LT(i, n);
kono
parents:
diff changeset
349 uptr index = i >> packing_ratio_log;
kono
parents:
diff changeset
350 uptr bit_offset = (i & bit_offset_mask) << counter_size_bits_log;
kono
parents:
diff changeset
351 return (buffer[index] >> bit_offset) & counter_mask;
kono
parents:
diff changeset
352 }
kono
parents:
diff changeset
353
kono
parents:
diff changeset
354 void Inc(uptr i) const {
kono
parents:
diff changeset
355 DCHECK_LT(Get(i), counter_mask);
kono
parents:
diff changeset
356 uptr index = i >> packing_ratio_log;
kono
parents:
diff changeset
357 uptr bit_offset = (i & bit_offset_mask) << counter_size_bits_log;
kono
parents:
diff changeset
358 buffer[index] += 1ULL << bit_offset;
kono
parents:
diff changeset
359 }
kono
parents:
diff changeset
360
kono
parents:
diff changeset
361 void IncRange(uptr from, uptr to) const {
kono
parents:
diff changeset
362 DCHECK_LE(from, to);
kono
parents:
diff changeset
363 for (uptr i = from; i <= to; i++)
kono
parents:
diff changeset
364 Inc(i);
kono
parents:
diff changeset
365 }
kono
parents:
diff changeset
366
kono
parents:
diff changeset
367 private:
kono
parents:
diff changeset
368 const u64 n;
kono
parents:
diff changeset
369 u64 counter_size_bits_log;
kono
parents:
diff changeset
370 u64 counter_mask;
kono
parents:
diff changeset
371 u64 packing_ratio_log;
kono
parents:
diff changeset
372 u64 bit_offset_mask;
kono
parents:
diff changeset
373
kono
parents:
diff changeset
374 MemoryMapperT* const memory_mapper;
kono
parents:
diff changeset
375 u64 buffer_size;
kono
parents:
diff changeset
376 u64* buffer;
kono
parents:
diff changeset
377 };
kono
parents:
diff changeset
378
kono
parents:
diff changeset
379 template<class MemoryMapperT>
kono
parents:
diff changeset
380 class FreePagesRangeTracker {
kono
parents:
diff changeset
381 public:
kono
parents:
diff changeset
382 explicit FreePagesRangeTracker(MemoryMapperT* mapper)
kono
parents:
diff changeset
383 : memory_mapper(mapper),
kono
parents:
diff changeset
384 page_size_scaled_log(Log2(GetPageSizeCached() >> kCompactPtrScale)),
kono
parents:
diff changeset
385 in_the_range(false), current_page(0), current_range_start_page(0) {}
kono
parents:
diff changeset
386
kono
parents:
diff changeset
387 void NextPage(bool freed) {
kono
parents:
diff changeset
388 if (freed) {
kono
parents:
diff changeset
389 if (!in_the_range) {
kono
parents:
diff changeset
390 current_range_start_page = current_page;
kono
parents:
diff changeset
391 in_the_range = true;
kono
parents:
diff changeset
392 }
kono
parents:
diff changeset
393 } else {
kono
parents:
diff changeset
394 CloseOpenedRange();
kono
parents:
diff changeset
395 }
kono
parents:
diff changeset
396 current_page++;
kono
parents:
diff changeset
397 }
kono
parents:
diff changeset
398
kono
parents:
diff changeset
399 void Done() {
kono
parents:
diff changeset
400 CloseOpenedRange();
kono
parents:
diff changeset
401 }
kono
parents:
diff changeset
402
kono
parents:
diff changeset
403 private:
kono
parents:
diff changeset
404 void CloseOpenedRange() {
kono
parents:
diff changeset
405 if (in_the_range) {
kono
parents:
diff changeset
406 memory_mapper->ReleasePageRangeToOS(
kono
parents:
diff changeset
407 current_range_start_page << page_size_scaled_log,
kono
parents:
diff changeset
408 current_page << page_size_scaled_log);
kono
parents:
diff changeset
409 in_the_range = false;
kono
parents:
diff changeset
410 }
kono
parents:
diff changeset
411 }
kono
parents:
diff changeset
412
kono
parents:
diff changeset
413 MemoryMapperT* const memory_mapper;
kono
parents:
diff changeset
414 const uptr page_size_scaled_log;
kono
parents:
diff changeset
415 bool in_the_range;
kono
parents:
diff changeset
416 uptr current_page;
kono
parents:
diff changeset
417 uptr current_range_start_page;
kono
parents:
diff changeset
418 };
kono
parents:
diff changeset
419
kono
parents:
diff changeset
420 // Iterates over the free_array to identify memory pages containing freed
kono
parents:
diff changeset
421 // chunks only and returns these pages back to OS.
kono
parents:
diff changeset
422 // allocated_pages_count is the total number of pages allocated for the
kono
parents:
diff changeset
423 // current bucket.
kono
parents:
diff changeset
424 template<class MemoryMapperT>
kono
parents:
diff changeset
425 static void ReleaseFreeMemoryToOS(CompactPtrT *free_array,
kono
parents:
diff changeset
426 uptr free_array_count, uptr chunk_size,
kono
parents:
diff changeset
427 uptr allocated_pages_count,
kono
parents:
diff changeset
428 MemoryMapperT *memory_mapper) {
kono
parents:
diff changeset
429 const uptr page_size = GetPageSizeCached();
kono
parents:
diff changeset
430
kono
parents:
diff changeset
431 // Figure out the number of chunks per page and whether we can take a fast
kono
parents:
diff changeset
432 // path (the number of chunks per page is the same for all pages).
kono
parents:
diff changeset
433 uptr full_pages_chunk_count_max;
kono
parents:
diff changeset
434 bool same_chunk_count_per_page;
kono
parents:
diff changeset
435 if (chunk_size <= page_size && page_size % chunk_size == 0) {
kono
parents:
diff changeset
436 // Same number of chunks per page, no cross overs.
kono
parents:
diff changeset
437 full_pages_chunk_count_max = page_size / chunk_size;
kono
parents:
diff changeset
438 same_chunk_count_per_page = true;
kono
parents:
diff changeset
439 } else if (chunk_size <= page_size && page_size % chunk_size != 0 &&
kono
parents:
diff changeset
440 chunk_size % (page_size % chunk_size) == 0) {
kono
parents:
diff changeset
441 // Some chunks are crossing page boundaries, which means that the page
kono
parents:
diff changeset
442 // contains one or two partial chunks, but all pages contain the same
kono
parents:
diff changeset
443 // number of chunks.
kono
parents:
diff changeset
444 full_pages_chunk_count_max = page_size / chunk_size + 1;
kono
parents:
diff changeset
445 same_chunk_count_per_page = true;
kono
parents:
diff changeset
446 } else if (chunk_size <= page_size) {
kono
parents:
diff changeset
447 // Some chunks are crossing page boundaries, which means that the page
kono
parents:
diff changeset
448 // contains one or two partial chunks.
kono
parents:
diff changeset
449 full_pages_chunk_count_max = page_size / chunk_size + 2;
kono
parents:
diff changeset
450 same_chunk_count_per_page = false;
kono
parents:
diff changeset
451 } else if (chunk_size > page_size && chunk_size % page_size == 0) {
kono
parents:
diff changeset
452 // One chunk covers multiple pages, no cross overs.
kono
parents:
diff changeset
453 full_pages_chunk_count_max = 1;
kono
parents:
diff changeset
454 same_chunk_count_per_page = true;
kono
parents:
diff changeset
455 } else if (chunk_size > page_size) {
kono
parents:
diff changeset
456 // One chunk covers multiple pages, Some chunks are crossing page
kono
parents:
diff changeset
457 // boundaries. Some pages contain one chunk, some contain two.
kono
parents:
diff changeset
458 full_pages_chunk_count_max = 2;
kono
parents:
diff changeset
459 same_chunk_count_per_page = false;
kono
parents:
diff changeset
460 } else {
kono
parents:
diff changeset
461 UNREACHABLE("All chunk_size/page_size ratios must be handled.");
kono
parents:
diff changeset
462 }
kono
parents:
diff changeset
463
kono
parents:
diff changeset
464 PackedCounterArray<MemoryMapperT> counters(allocated_pages_count,
kono
parents:
diff changeset
465 full_pages_chunk_count_max,
kono
parents:
diff changeset
466 memory_mapper);
kono
parents:
diff changeset
467 if (!counters.IsAllocated())
kono
parents:
diff changeset
468 return;
kono
parents:
diff changeset
469
kono
parents:
diff changeset
470 const uptr chunk_size_scaled = chunk_size >> kCompactPtrScale;
kono
parents:
diff changeset
471 const uptr page_size_scaled = page_size >> kCompactPtrScale;
kono
parents:
diff changeset
472 const uptr page_size_scaled_log = Log2(page_size_scaled);
kono
parents:
diff changeset
473
kono
parents:
diff changeset
474 // Iterate over free chunks and count how many free chunks affect each
kono
parents:
diff changeset
475 // allocated page.
kono
parents:
diff changeset
476 if (chunk_size <= page_size && page_size % chunk_size == 0) {
kono
parents:
diff changeset
477 // Each chunk affects one page only.
kono
parents:
diff changeset
478 for (uptr i = 0; i < free_array_count; i++)
kono
parents:
diff changeset
479 counters.Inc(free_array[i] >> page_size_scaled_log);
kono
parents:
diff changeset
480 } else {
kono
parents:
diff changeset
481 // In all other cases chunks might affect more than one page.
kono
parents:
diff changeset
482 for (uptr i = 0; i < free_array_count; i++) {
kono
parents:
diff changeset
483 counters.IncRange(
kono
parents:
diff changeset
484 free_array[i] >> page_size_scaled_log,
kono
parents:
diff changeset
485 (free_array[i] + chunk_size_scaled - 1) >> page_size_scaled_log);
kono
parents:
diff changeset
486 }
kono
parents:
diff changeset
487 }
kono
parents:
diff changeset
488
kono
parents:
diff changeset
489 // Iterate over pages detecting ranges of pages with chunk counters equal
kono
parents:
diff changeset
490 // to the expected number of chunks for the particular page.
kono
parents:
diff changeset
491 FreePagesRangeTracker<MemoryMapperT> range_tracker(memory_mapper);
kono
parents:
diff changeset
492 if (same_chunk_count_per_page) {
kono
parents:
diff changeset
493 // Fast path, every page has the same number of chunks affecting it.
kono
parents:
diff changeset
494 for (uptr i = 0; i < counters.GetCount(); i++)
kono
parents:
diff changeset
495 range_tracker.NextPage(counters.Get(i) == full_pages_chunk_count_max);
kono
parents:
diff changeset
496 } else {
kono
parents:
diff changeset
497 // Show path, go through the pages keeping count how many chunks affect
kono
parents:
diff changeset
498 // each page.
kono
parents:
diff changeset
499 const uptr pn =
kono
parents:
diff changeset
500 chunk_size < page_size ? page_size_scaled / chunk_size_scaled : 1;
kono
parents:
diff changeset
501 const uptr pnc = pn * chunk_size_scaled;
kono
parents:
diff changeset
502 // The idea is to increment the current page pointer by the first chunk
kono
parents:
diff changeset
503 // size, middle portion size (the portion of the page covered by chunks
kono
parents:
diff changeset
504 // except the first and the last one) and then the last chunk size, adding
kono
parents:
diff changeset
505 // up the number of chunks on the current page and checking on every step
kono
parents:
diff changeset
506 // whether the page boundary was crossed.
kono
parents:
diff changeset
507 uptr prev_page_boundary = 0;
kono
parents:
diff changeset
508 uptr current_boundary = 0;
kono
parents:
diff changeset
509 for (uptr i = 0; i < counters.GetCount(); i++) {
kono
parents:
diff changeset
510 uptr page_boundary = prev_page_boundary + page_size_scaled;
kono
parents:
diff changeset
511 uptr chunks_per_page = pn;
kono
parents:
diff changeset
512 if (current_boundary < page_boundary) {
kono
parents:
diff changeset
513 if (current_boundary > prev_page_boundary)
kono
parents:
diff changeset
514 chunks_per_page++;
kono
parents:
diff changeset
515 current_boundary += pnc;
kono
parents:
diff changeset
516 if (current_boundary < page_boundary) {
kono
parents:
diff changeset
517 chunks_per_page++;
kono
parents:
diff changeset
518 current_boundary += chunk_size_scaled;
kono
parents:
diff changeset
519 }
kono
parents:
diff changeset
520 }
kono
parents:
diff changeset
521 prev_page_boundary = page_boundary;
kono
parents:
diff changeset
522
kono
parents:
diff changeset
523 range_tracker.NextPage(counters.Get(i) == chunks_per_page);
kono
parents:
diff changeset
524 }
kono
parents:
diff changeset
525 }
kono
parents:
diff changeset
526 range_tracker.Done();
kono
parents:
diff changeset
527 }
kono
parents:
diff changeset
528
kono
parents:
diff changeset
529 private:
kono
parents:
diff changeset
530 friend class MemoryMapper;
kono
parents:
diff changeset
531
kono
parents:
diff changeset
532 static const uptr kRegionSize = kSpaceSize / kNumClassesRounded;
kono
parents:
diff changeset
533 // FreeArray is the array of free-d chunks (stored as 4-byte offsets).
kono
parents:
diff changeset
534 // In the worst case it may reguire kRegionSize/SizeClassMap::kMinSize
kono
parents:
diff changeset
535 // elements, but in reality this will not happen. For simplicity we
kono
parents:
diff changeset
536 // dedicate 1/8 of the region's virtual space to FreeArray.
kono
parents:
diff changeset
537 static const uptr kFreeArraySize = kRegionSize / 8;
kono
parents:
diff changeset
538
kono
parents:
diff changeset
539 static const bool kUsingConstantSpaceBeg = kSpaceBeg != ~(uptr)0;
kono
parents:
diff changeset
540 uptr NonConstSpaceBeg;
kono
parents:
diff changeset
541 uptr SpaceBeg() const {
kono
parents:
diff changeset
542 return kUsingConstantSpaceBeg ? kSpaceBeg : NonConstSpaceBeg;
kono
parents:
diff changeset
543 }
kono
parents:
diff changeset
544 uptr SpaceEnd() const { return SpaceBeg() + kSpaceSize; }
kono
parents:
diff changeset
545 // kRegionSize must be >= 2^32.
kono
parents:
diff changeset
546 COMPILER_CHECK((kRegionSize) >= (1ULL << (SANITIZER_WORDSIZE / 2)));
kono
parents:
diff changeset
547 // kRegionSize must be <= 2^36, see CompactPtrT.
kono
parents:
diff changeset
548 COMPILER_CHECK((kRegionSize) <= (1ULL << (SANITIZER_WORDSIZE / 2 + 4)));
kono
parents:
diff changeset
549 // Call mmap for user memory with at least this size.
kono
parents:
diff changeset
550 static const uptr kUserMapSize = 1 << 16;
kono
parents:
diff changeset
551 // Call mmap for metadata memory with at least this size.
kono
parents:
diff changeset
552 static const uptr kMetaMapSize = 1 << 16;
kono
parents:
diff changeset
553 // Call mmap for free array memory with at least this size.
kono
parents:
diff changeset
554 static const uptr kFreeArrayMapSize = 1 << 16;
kono
parents:
diff changeset
555
kono
parents:
diff changeset
556 atomic_sint32_t release_to_os_interval_ms_;
kono
parents:
diff changeset
557
kono
parents:
diff changeset
558 struct Stats {
kono
parents:
diff changeset
559 uptr n_allocated;
kono
parents:
diff changeset
560 uptr n_freed;
kono
parents:
diff changeset
561 };
kono
parents:
diff changeset
562
kono
parents:
diff changeset
563 struct ReleaseToOsInfo {
kono
parents:
diff changeset
564 uptr n_freed_at_last_release;
kono
parents:
diff changeset
565 uptr num_releases;
kono
parents:
diff changeset
566 u64 last_release_at_ns;
kono
parents:
diff changeset
567 u64 last_released_bytes;
kono
parents:
diff changeset
568 };
kono
parents:
diff changeset
569
kono
parents:
diff changeset
570 struct RegionInfo {
kono
parents:
diff changeset
571 BlockingMutex mutex;
kono
parents:
diff changeset
572 uptr num_freed_chunks; // Number of elements in the freearray.
kono
parents:
diff changeset
573 uptr mapped_free_array; // Bytes mapped for freearray.
kono
parents:
diff changeset
574 uptr allocated_user; // Bytes allocated for user memory.
kono
parents:
diff changeset
575 uptr allocated_meta; // Bytes allocated for metadata.
kono
parents:
diff changeset
576 uptr mapped_user; // Bytes mapped for user memory.
kono
parents:
diff changeset
577 uptr mapped_meta; // Bytes mapped for metadata.
kono
parents:
diff changeset
578 u32 rand_state; // Seed for random shuffle, used if kRandomShuffleChunks.
kono
parents:
diff changeset
579 bool exhausted; // Whether region is out of space for new chunks.
kono
parents:
diff changeset
580 Stats stats;
kono
parents:
diff changeset
581 ReleaseToOsInfo rtoi;
kono
parents:
diff changeset
582 };
kono
parents:
diff changeset
583 COMPILER_CHECK(sizeof(RegionInfo) >= kCacheLineSize);
kono
parents:
diff changeset
584
kono
parents:
diff changeset
585 u32 Rand(u32 *state) { // ANSI C linear congruential PRNG.
kono
parents:
diff changeset
586 return (*state = *state * 1103515245 + 12345) >> 16;
kono
parents:
diff changeset
587 }
kono
parents:
diff changeset
588
kono
parents:
diff changeset
589 u32 RandN(u32 *state, u32 n) { return Rand(state) % n; } // [0, n)
kono
parents:
diff changeset
590
kono
parents:
diff changeset
591 void RandomShuffle(u32 *a, u32 n, u32 *rand_state) {
kono
parents:
diff changeset
592 if (n <= 1) return;
kono
parents:
diff changeset
593 for (u32 i = n - 1; i > 0; i--)
kono
parents:
diff changeset
594 Swap(a[i], a[RandN(rand_state, i + 1)]);
kono
parents:
diff changeset
595 }
kono
parents:
diff changeset
596
kono
parents:
diff changeset
597 RegionInfo *GetRegionInfo(uptr class_id) const {
kono
parents:
diff changeset
598 CHECK_LT(class_id, kNumClasses);
kono
parents:
diff changeset
599 RegionInfo *regions =
kono
parents:
diff changeset
600 reinterpret_cast<RegionInfo *>(SpaceBeg() + kSpaceSize);
kono
parents:
diff changeset
601 return &regions[class_id];
kono
parents:
diff changeset
602 }
kono
parents:
diff changeset
603
kono
parents:
diff changeset
604 uptr GetMetadataEnd(uptr region_beg) const {
kono
parents:
diff changeset
605 return region_beg + kRegionSize - kFreeArraySize;
kono
parents:
diff changeset
606 }
kono
parents:
diff changeset
607
kono
parents:
diff changeset
608 uptr GetChunkIdx(uptr chunk, uptr size) const {
kono
parents:
diff changeset
609 if (!kUsingConstantSpaceBeg)
kono
parents:
diff changeset
610 chunk -= SpaceBeg();
kono
parents:
diff changeset
611
kono
parents:
diff changeset
612 uptr offset = chunk % kRegionSize;
kono
parents:
diff changeset
613 // Here we divide by a non-constant. This is costly.
kono
parents:
diff changeset
614 // size always fits into 32-bits. If the offset fits too, use 32-bit div.
kono
parents:
diff changeset
615 if (offset >> (SANITIZER_WORDSIZE / 2))
kono
parents:
diff changeset
616 return offset / size;
kono
parents:
diff changeset
617 return (u32)offset / (u32)size;
kono
parents:
diff changeset
618 }
kono
parents:
diff changeset
619
kono
parents:
diff changeset
620 CompactPtrT *GetFreeArray(uptr region_beg) const {
kono
parents:
diff changeset
621 return reinterpret_cast<CompactPtrT *>(GetMetadataEnd(region_beg));
kono
parents:
diff changeset
622 }
kono
parents:
diff changeset
623
kono
parents:
diff changeset
624 bool MapWithCallback(uptr beg, uptr size) {
kono
parents:
diff changeset
625 uptr mapped = reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(beg, size));
kono
parents:
diff changeset
626 if (UNLIKELY(!mapped))
kono
parents:
diff changeset
627 return false;
kono
parents:
diff changeset
628 CHECK_EQ(beg, mapped);
kono
parents:
diff changeset
629 MapUnmapCallback().OnMap(beg, size);
kono
parents:
diff changeset
630 return true;
kono
parents:
diff changeset
631 }
kono
parents:
diff changeset
632
kono
parents:
diff changeset
633 void MapWithCallbackOrDie(uptr beg, uptr size) {
kono
parents:
diff changeset
634 CHECK_EQ(beg, reinterpret_cast<uptr>(MmapFixedOrDie(beg, size)));
kono
parents:
diff changeset
635 MapUnmapCallback().OnMap(beg, size);
kono
parents:
diff changeset
636 }
kono
parents:
diff changeset
637
kono
parents:
diff changeset
638 void UnmapWithCallbackOrDie(uptr beg, uptr size) {
kono
parents:
diff changeset
639 MapUnmapCallback().OnUnmap(beg, size);
kono
parents:
diff changeset
640 UnmapOrDie(reinterpret_cast<void *>(beg), size);
kono
parents:
diff changeset
641 }
kono
parents:
diff changeset
642
kono
parents:
diff changeset
643 bool EnsureFreeArraySpace(RegionInfo *region, uptr region_beg,
kono
parents:
diff changeset
644 uptr num_freed_chunks) {
kono
parents:
diff changeset
645 uptr needed_space = num_freed_chunks * sizeof(CompactPtrT);
kono
parents:
diff changeset
646 if (region->mapped_free_array < needed_space) {
kono
parents:
diff changeset
647 uptr new_mapped_free_array = RoundUpTo(needed_space, kFreeArrayMapSize);
kono
parents:
diff changeset
648 CHECK_LE(new_mapped_free_array, kFreeArraySize);
kono
parents:
diff changeset
649 uptr current_map_end = reinterpret_cast<uptr>(GetFreeArray(region_beg)) +
kono
parents:
diff changeset
650 region->mapped_free_array;
kono
parents:
diff changeset
651 uptr new_map_size = new_mapped_free_array - region->mapped_free_array;
kono
parents:
diff changeset
652 if (UNLIKELY(!MapWithCallback(current_map_end, new_map_size)))
kono
parents:
diff changeset
653 return false;
kono
parents:
diff changeset
654 region->mapped_free_array = new_mapped_free_array;
kono
parents:
diff changeset
655 }
kono
parents:
diff changeset
656 return true;
kono
parents:
diff changeset
657 }
kono
parents:
diff changeset
658
kono
parents:
diff changeset
659 NOINLINE bool PopulateFreeArray(AllocatorStats *stat, uptr class_id,
kono
parents:
diff changeset
660 RegionInfo *region, uptr requested_count) {
kono
parents:
diff changeset
661 // region->mutex is held.
kono
parents:
diff changeset
662 const uptr size = ClassIdToSize(class_id);
kono
parents:
diff changeset
663 const uptr new_space_beg = region->allocated_user;
kono
parents:
diff changeset
664 const uptr new_space_end = new_space_beg + requested_count * size;
kono
parents:
diff changeset
665 const uptr region_beg = GetRegionBeginBySizeClass(class_id);
kono
parents:
diff changeset
666
kono
parents:
diff changeset
667 // Map more space for chunks, if necessary.
kono
parents:
diff changeset
668 if (new_space_end > region->mapped_user) {
kono
parents:
diff changeset
669 if (!kUsingConstantSpaceBeg && region->mapped_user == 0)
kono
parents:
diff changeset
670 region->rand_state = static_cast<u32>(region_beg >> 12); // From ASLR.
kono
parents:
diff changeset
671 // Do the mmap for the user memory.
kono
parents:
diff changeset
672 uptr map_size = kUserMapSize;
kono
parents:
diff changeset
673 while (new_space_end > region->mapped_user + map_size)
kono
parents:
diff changeset
674 map_size += kUserMapSize;
kono
parents:
diff changeset
675 CHECK_GE(region->mapped_user + map_size, new_space_end);
kono
parents:
diff changeset
676 if (UNLIKELY(!MapWithCallback(region_beg + region->mapped_user,
kono
parents:
diff changeset
677 map_size)))
kono
parents:
diff changeset
678 return false;
kono
parents:
diff changeset
679 stat->Add(AllocatorStatMapped, map_size);
kono
parents:
diff changeset
680 region->mapped_user += map_size;
kono
parents:
diff changeset
681 }
kono
parents:
diff changeset
682 const uptr new_chunks_count = (region->mapped_user - new_space_beg) / size;
kono
parents:
diff changeset
683
kono
parents:
diff changeset
684 // Calculate the required space for metadata.
kono
parents:
diff changeset
685 const uptr requested_allocated_meta =
kono
parents:
diff changeset
686 region->allocated_meta + new_chunks_count * kMetadataSize;
kono
parents:
diff changeset
687 uptr requested_mapped_meta = region->mapped_meta;
kono
parents:
diff changeset
688 while (requested_allocated_meta > requested_mapped_meta)
kono
parents:
diff changeset
689 requested_mapped_meta += kMetaMapSize;
kono
parents:
diff changeset
690 // Check whether this size class is exhausted.
kono
parents:
diff changeset
691 if (region->mapped_user + requested_mapped_meta >
kono
parents:
diff changeset
692 kRegionSize - kFreeArraySize) {
kono
parents:
diff changeset
693 if (!region->exhausted) {
kono
parents:
diff changeset
694 region->exhausted = true;
kono
parents:
diff changeset
695 Printf("%s: Out of memory. ", SanitizerToolName);
kono
parents:
diff changeset
696 Printf("The process has exhausted %zuMB for size class %zu.\n",
kono
parents:
diff changeset
697 kRegionSize >> 20, size);
kono
parents:
diff changeset
698 }
kono
parents:
diff changeset
699 return false;
kono
parents:
diff changeset
700 }
kono
parents:
diff changeset
701 // Map more space for metadata, if necessary.
kono
parents:
diff changeset
702 if (requested_mapped_meta > region->mapped_meta) {
kono
parents:
diff changeset
703 if (UNLIKELY(!MapWithCallback(
kono
parents:
diff changeset
704 GetMetadataEnd(region_beg) - requested_mapped_meta,
kono
parents:
diff changeset
705 requested_mapped_meta - region->mapped_meta)))
kono
parents:
diff changeset
706 return false;
kono
parents:
diff changeset
707 region->mapped_meta = requested_mapped_meta;
kono
parents:
diff changeset
708 }
kono
parents:
diff changeset
709
kono
parents:
diff changeset
710 // If necessary, allocate more space for the free array and populate it with
kono
parents:
diff changeset
711 // newly allocated chunks.
kono
parents:
diff changeset
712 const uptr total_freed_chunks = region->num_freed_chunks + new_chunks_count;
kono
parents:
diff changeset
713 if (UNLIKELY(!EnsureFreeArraySpace(region, region_beg, total_freed_chunks)))
kono
parents:
diff changeset
714 return false;
kono
parents:
diff changeset
715 CompactPtrT *free_array = GetFreeArray(region_beg);
kono
parents:
diff changeset
716 for (uptr i = 0, chunk = new_space_beg; i < new_chunks_count;
kono
parents:
diff changeset
717 i++, chunk += size)
kono
parents:
diff changeset
718 free_array[total_freed_chunks - 1 - i] = PointerToCompactPtr(0, chunk);
kono
parents:
diff changeset
719 if (kRandomShuffleChunks)
kono
parents:
diff changeset
720 RandomShuffle(&free_array[region->num_freed_chunks], new_chunks_count,
kono
parents:
diff changeset
721 &region->rand_state);
kono
parents:
diff changeset
722
kono
parents:
diff changeset
723 // All necessary memory is mapped and now it is safe to advance all
kono
parents:
diff changeset
724 // 'allocated_*' counters.
kono
parents:
diff changeset
725 region->num_freed_chunks += new_chunks_count;
kono
parents:
diff changeset
726 region->allocated_user += new_chunks_count * size;
kono
parents:
diff changeset
727 CHECK_LE(region->allocated_user, region->mapped_user);
kono
parents:
diff changeset
728 region->allocated_meta = requested_allocated_meta;
kono
parents:
diff changeset
729 CHECK_LE(region->allocated_meta, region->mapped_meta);
kono
parents:
diff changeset
730 region->exhausted = false;
kono
parents:
diff changeset
731
kono
parents:
diff changeset
732 // TODO(alekseyshl): Consider bumping last_release_at_ns here to prevent
kono
parents:
diff changeset
733 // MaybeReleaseToOS from releasing just allocated pages or protect these
kono
parents:
diff changeset
734 // not yet used chunks some other way.
kono
parents:
diff changeset
735
kono
parents:
diff changeset
736 return true;
kono
parents:
diff changeset
737 }
kono
parents:
diff changeset
738
kono
parents:
diff changeset
739 class MemoryMapper {
kono
parents:
diff changeset
740 public:
kono
parents:
diff changeset
741 MemoryMapper(const ThisT& base_allocator, uptr class_id)
kono
parents:
diff changeset
742 : allocator(base_allocator),
kono
parents:
diff changeset
743 region_base(base_allocator.GetRegionBeginBySizeClass(class_id)),
kono
parents:
diff changeset
744 released_ranges_count(0),
kono
parents:
diff changeset
745 released_bytes(0) {
kono
parents:
diff changeset
746 }
kono
parents:
diff changeset
747
kono
parents:
diff changeset
748 uptr GetReleasedRangesCount() const {
kono
parents:
diff changeset
749 return released_ranges_count;
kono
parents:
diff changeset
750 }
kono
parents:
diff changeset
751
kono
parents:
diff changeset
752 uptr GetReleasedBytes() const {
kono
parents:
diff changeset
753 return released_bytes;
kono
parents:
diff changeset
754 }
kono
parents:
diff changeset
755
kono
parents:
diff changeset
756 uptr MapPackedCounterArrayBuffer(uptr buffer_size) {
kono
parents:
diff changeset
757 // TODO(alekseyshl): The idea to explore is to check if we have enough
kono
parents:
diff changeset
758 // space between num_freed_chunks*sizeof(CompactPtrT) and
kono
parents:
diff changeset
759 // mapped_free_array to fit buffer_size bytes and use that space instead
kono
parents:
diff changeset
760 // of mapping a temporary one.
kono
parents:
diff changeset
761 return reinterpret_cast<uptr>(
kono
parents:
diff changeset
762 MmapOrDieOnFatalError(buffer_size, "ReleaseToOSPageCounters"));
kono
parents:
diff changeset
763 }
kono
parents:
diff changeset
764
kono
parents:
diff changeset
765 void UnmapPackedCounterArrayBuffer(uptr buffer, uptr buffer_size) {
kono
parents:
diff changeset
766 UnmapOrDie(reinterpret_cast<void *>(buffer), buffer_size);
kono
parents:
diff changeset
767 }
kono
parents:
diff changeset
768
kono
parents:
diff changeset
769 // Releases [from, to) range of pages back to OS.
kono
parents:
diff changeset
770 void ReleasePageRangeToOS(CompactPtrT from, CompactPtrT to) {
kono
parents:
diff changeset
771 const uptr from_page = allocator.CompactPtrToPointer(region_base, from);
kono
parents:
diff changeset
772 const uptr to_page = allocator.CompactPtrToPointer(region_base, to);
kono
parents:
diff changeset
773 ReleaseMemoryPagesToOS(from_page, to_page);
kono
parents:
diff changeset
774 released_ranges_count++;
kono
parents:
diff changeset
775 released_bytes += to_page - from_page;
kono
parents:
diff changeset
776 }
kono
parents:
diff changeset
777
kono
parents:
diff changeset
778 private:
kono
parents:
diff changeset
779 const ThisT& allocator;
kono
parents:
diff changeset
780 const uptr region_base;
kono
parents:
diff changeset
781 uptr released_ranges_count;
kono
parents:
diff changeset
782 uptr released_bytes;
kono
parents:
diff changeset
783 };
kono
parents:
diff changeset
784
kono
parents:
diff changeset
785 // Attempts to release RAM occupied by freed chunks back to OS. The region is
kono
parents:
diff changeset
786 // expected to be locked.
kono
parents:
diff changeset
787 void MaybeReleaseToOS(uptr class_id) {
kono
parents:
diff changeset
788 RegionInfo *region = GetRegionInfo(class_id);
kono
parents:
diff changeset
789 const uptr chunk_size = ClassIdToSize(class_id);
kono
parents:
diff changeset
790 const uptr page_size = GetPageSizeCached();
kono
parents:
diff changeset
791
kono
parents:
diff changeset
792 uptr n = region->num_freed_chunks;
kono
parents:
diff changeset
793 if (n * chunk_size < page_size)
kono
parents:
diff changeset
794 return; // No chance to release anything.
kono
parents:
diff changeset
795 if ((region->stats.n_freed -
kono
parents:
diff changeset
796 region->rtoi.n_freed_at_last_release) * chunk_size < page_size) {
kono
parents:
diff changeset
797 return; // Nothing new to release.
kono
parents:
diff changeset
798 }
kono
parents:
diff changeset
799
kono
parents:
diff changeset
800 s32 interval_ms = ReleaseToOSIntervalMs();
kono
parents:
diff changeset
801 if (interval_ms < 0)
kono
parents:
diff changeset
802 return;
kono
parents:
diff changeset
803
kono
parents:
diff changeset
804 if (region->rtoi.last_release_at_ns + interval_ms * 1000000ULL > NanoTime())
kono
parents:
diff changeset
805 return; // Memory was returned recently.
kono
parents:
diff changeset
806
kono
parents:
diff changeset
807 MemoryMapper memory_mapper(*this, class_id);
kono
parents:
diff changeset
808
kono
parents:
diff changeset
809 ReleaseFreeMemoryToOS<MemoryMapper>(
kono
parents:
diff changeset
810 GetFreeArray(GetRegionBeginBySizeClass(class_id)), n, chunk_size,
kono
parents:
diff changeset
811 RoundUpTo(region->allocated_user, page_size) / page_size,
kono
parents:
diff changeset
812 &memory_mapper);
kono
parents:
diff changeset
813
kono
parents:
diff changeset
814 if (memory_mapper.GetReleasedRangesCount() > 0) {
kono
parents:
diff changeset
815 region->rtoi.n_freed_at_last_release = region->stats.n_freed;
kono
parents:
diff changeset
816 region->rtoi.num_releases += memory_mapper.GetReleasedRangesCount();
kono
parents:
diff changeset
817 region->rtoi.last_released_bytes = memory_mapper.GetReleasedBytes();
kono
parents:
diff changeset
818 }
kono
parents:
diff changeset
819 region->rtoi.last_release_at_ns = NanoTime();
kono
parents:
diff changeset
820 }
kono
parents:
diff changeset
821 };