OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "base/debug/activity_tracker.h" | |
6 | |
7 #include "base/debug/stack_trace.h" | |
8 #include "base/feature_list.h" | |
9 #include "base/files/file.h" | |
10 #include "base/files/file_path.h" | |
11 #include "base/files/memory_mapped_file.h" | |
12 #include "base/logging.h" | |
13 #include "base/memory/ptr_util.h" | |
14 #include "base/metrics/field_trial.h" | |
15 #include "base/metrics/histogram_macros.h" | |
16 #include "base/pending_task.h" | |
17 #include "base/process/process.h" | |
18 #include "base/process/process_handle.h" | |
19 #include "base/stl_util.h" | |
20 #include "base/strings/string_util.h" | |
21 #include "base/threading/platform_thread.h" | |
22 | |
23 namespace base { | |
24 namespace debug { | |
25 | |
26 namespace { | |
27 | |
28 // A number that identifies the memory as having been initialized. It's | |
29 // arbitrary but happens to be the first 8 bytes of SHA1(ThreadActivityTracker). | |
30 // A version number is added on so that major structure changes won't try to | |
31 // read an older version (since the cookie won't match). | |
32 const uint64_t kHeaderCookie = 0xC0029B240D4A3092ULL + 1; // v1 | |
33 | |
34 // The minimum depth a stack should support. | |
35 const int kMinStackDepth = 2; | |
36 | |
37 } // namespace | |
38 | |
39 | |
40 #if !defined(OS_NACL) // NACL doesn't support any kind of file access in build. | |
41 void SetupGlobalActivityTrackerFieldTrial(const FilePath& file) { | |
42 const Feature kActivityTrackerFeature{ | |
43 "ActivityTracking", FEATURE_DISABLED_BY_DEFAULT | |
44 }; | |
45 | |
46 if (!base::FeatureList::IsEnabled(kActivityTrackerFeature)) | |
47 return; | |
48 | |
49 // TODO(bcwhite): Adjust these numbers once there is real data to show | |
50 // just how much of an arena is necessary. | |
51 const size_t kMemorySize = 1 << 20; // 1 MiB | |
52 const int kStackDepth = 4; | |
53 const uint64_t kAllocatorId = 0; | |
54 const char kAllocatorName[] = "ActivityTracker"; | |
55 | |
56 GlobalActivityTracker::CreateWithFile( | |
57 file.AddExtension(PersistentMemoryAllocator::kFileExtension), | |
58 kMemorySize, kAllocatorId, kAllocatorName, kStackDepth); | |
59 } | |
60 #endif // !defined(OS_NACL) | |
61 | |
62 | |
63 // This information is kept for every thread that is tracked. It is filled | |
64 // the very first time the thread is seen. All fields must be of exact sizes | |
65 // so there is no issue moving between 32 and 64-bit builds. | |
66 struct ThreadActivityTracker::Header { | |
67 // This unique number indicates a valid initialization of the memory. | |
68 uint64_t cookie; | |
69 | |
70 // The process-id and thread-id to which this data belongs. These identifiers | |
71 // are not guaranteed to mean anything but are unique, in combination, among | |
72 // all active trackers. | |
73 int64_t process_id; | |
74 union { | |
75 int64_t as_id; | |
76 #if defined(OS_WIN) | |
77 // On Windows, the handle itself is often a pseudo-handle with a common | |
78 // value meaning "this thread" and so the thread-id is used. The former | |
79 // can be converted to a thread-id with a system call. | |
80 PlatformThreadId as_tid; | |
81 #elif defined(OS_POSIX) | |
82 // On Posix, the handle is always a unique identifier so no conversion | |
83 // needs to be done. However, it's value is officially opaque so there | |
84 // is no one correct way to convert it to a numerical identifier. | |
85 PlatformThreadHandle::Handle as_handle; | |
86 #endif | |
87 } thread_ref; | |
88 | |
89 // The start-time and start-ticks when the data was created. Each activity | |
90 // record has a |time_internal| value that can be converted to a "wall time" | |
91 // with these two values. | |
92 int64_t start_time; | |
93 int64_t start_ticks; | |
94 | |
95 // The number of Activity slots in the data. | |
96 uint32_t stack_slots; | |
97 | |
98 // The current depth of the stack. This may be greater than the number of | |
99 // slots. If the depth exceeds the number of slots, the newest entries | |
100 // won't be recorded. | |
101 std::atomic<uint32_t> current_depth; | |
102 | |
103 // A memory location used to indicate if changes have been made to the stack | |
104 // that would invalidate an in-progress read of its contents. The active | |
105 // tracker will zero the value whenever something gets popped from the | |
106 // stack. A monitoring tracker can write a non-zero value here, copy the | |
107 // stack contents, and read the value to know, if it is still non-zero, that | |
108 // the contents didn't change while being copied. This can handle concurrent | |
109 // snapshot operations only if each snapshot writes a different bit (which | |
110 // is not the current implementation so no parallel snapshots allowed). | |
111 std::atomic<uint32_t> stack_unchanged; | |
112 | |
113 // The name of the thread (up to a maximum length). Dynamic-length names | |
114 // are not practical since the memory has to come from the same persistent | |
115 // allocator that holds this structure and to which this object has no | |
116 // reference. | |
117 char thread_name[32]; | |
118 }; | |
119 | |
120 // It doesn't matter what is contained in this (though it will be all zeros) | |
121 // as only the address of it is important. | |
122 const ThreadActivityTracker::ActivityData | |
123 ThreadActivityTracker::kNullActivityData = {}; | |
124 | |
125 ThreadActivityTracker::ActivityData | |
126 ThreadActivityTracker::ActivityData::ForThread( | |
127 const PlatformThreadHandle& handle) { | |
128 // Header already has a conversion union; reuse that. | |
129 ThreadActivityTracker::Header header; | |
130 header.thread_ref.as_id = 0; // Zero the union in case other is smaller. | |
131 #if defined(OS_WIN) | |
132 header.thread_ref.as_tid = ::GetThreadId(handle.platform_handle()); | |
133 #elif defined(OS_POSIX) | |
134 header.thread_ref.as_handle = handle.platform_handle(); | |
135 #endif | |
136 return ForThread(header.thread_ref.as_id); | |
137 } | |
138 | |
139 ThreadActivityTracker::ActivitySnapshot::ActivitySnapshot() {} | |
140 ThreadActivityTracker::ActivitySnapshot::~ActivitySnapshot() {} | |
141 | |
142 | |
143 ThreadActivityTracker::ThreadActivityTracker(void* base, size_t size) | |
144 : header_(static_cast<Header*>(base)), | |
145 stack_(reinterpret_cast<Activity*>(reinterpret_cast<char*>(base) + | |
146 sizeof(Header))), | |
147 stack_slots_( | |
148 static_cast<uint32_t>((size - sizeof(Header)) / sizeof(Activity))) { | |
149 DCHECK(thread_checker_.CalledOnValidThread()); | |
150 | |
151 // Verify the parameters but fail gracefully if they're not valid so that | |
152 // production code based on external inputs will not crash. IsValid() will | |
153 // return false in this case. | |
154 if (!base || | |
155 // Ensure there is enough space for the header and at least a few records. | |
156 size < sizeof(Header) + kMinStackDepth * sizeof(Activity) || | |
157 // Ensure that the |stack_slots_| calculation didn't overflow. | |
158 (size - sizeof(Header)) / sizeof(Activity) > | |
159 std::numeric_limits<uint32_t>::max()) { | |
160 NOTREACHED(); | |
161 return; | |
162 } | |
163 | |
164 // Ensure that the thread reference doesn't exceed the size of the ID number. | |
165 // This won't compile at the global scope because Header is a private struct. | |
166 static_assert( | |
167 sizeof(header_->thread_ref) == sizeof(header_->thread_ref.as_id), | |
168 "PlatformThreadHandle::Handle is too big to hold in 64-bit ID"); | |
169 | |
170 // Ensure that the alignment of Activity.data is properly aligned to a | |
171 // 64-bit boundary so there are no interoperability-issues across cpu | |
172 // architectures. | |
173 static_assert(offsetof(Activity, data) % sizeof(uint64_t) == 0, | |
174 "ActivityData.data is not 64-bit aligned"); | |
175 | |
176 // Provided memory should either be completely initialized or all zeros. | |
177 if (header_->cookie == 0) { | |
178 // This is a new file. Double-check other fields and then initialize. | |
179 DCHECK_EQ(0, header_->process_id); | |
180 DCHECK_EQ(0, header_->thread_ref.as_id); | |
181 DCHECK_EQ(0, header_->start_time); | |
182 DCHECK_EQ(0, header_->start_ticks); | |
183 DCHECK_EQ(0U, header_->stack_slots); | |
184 DCHECK_EQ(0U, header_->current_depth.load(std::memory_order_relaxed)); | |
185 DCHECK_EQ(0U, header_->stack_unchanged.load(std::memory_order_relaxed)); | |
186 DCHECK_EQ(0, stack_[0].time_internal); | |
187 DCHECK_EQ(0U, stack_[0].origin_address); | |
188 DCHECK_EQ(0U, stack_[0].call_stack[0]); | |
189 DCHECK_EQ(0U, stack_[0].data.task.sequence_id); | |
190 | |
191 header_->process_id = GetCurrentProcId(); | |
192 #if defined(OS_WIN) | |
193 header_->thread_ref.as_tid = PlatformThread::CurrentId(); | |
194 #elif defined(OS_POSIX) | |
195 header_->thread_ref.as_handle = | |
196 PlatformThread::CurrentHandle().platform_handle(); | |
197 #endif | |
198 header_->start_time = base::Time::Now().ToInternalValue(); | |
199 header_->start_ticks = base::TimeTicks::Now().ToInternalValue(); | |
200 header_->stack_slots = stack_slots_; | |
201 strlcpy(header_->thread_name, PlatformThread::GetName(), | |
202 sizeof(header_->thread_name)); | |
203 header_->cookie = kHeaderCookie; | |
204 valid_ = true; | |
205 DCHECK(IsValid()); | |
206 } else { | |
207 // This is a file with existing data. Perform basic consistency checks. | |
208 valid_ = true; | |
209 valid_ = IsValid(); | |
210 } | |
211 } | |
212 | |
213 ThreadActivityTracker::~ThreadActivityTracker() {} | |
214 | |
215 void ThreadActivityTracker::PushActivity(const void* origin, | |
216 ActivityType type, | |
217 const ActivityData& data) { | |
218 // A thread-checker creates a lock to check the thread-id which means | |
219 // re-entry into this code if lock acquisitions are being tracked. | |
220 DCHECK(type == ACT_LOCK_ACQUIRE || thread_checker_.CalledOnValidThread()); | |
221 | |
222 // Get the current depth of the stack. No access to other memory guarded | |
223 // by this variable is done here so a "relaxed" load is acceptable. | |
224 uint32_t depth = header_->current_depth.load(std::memory_order_relaxed); | |
225 | |
226 // Handle the case where the stack depth has exceeded the storage capacity. | |
227 // Extra entries will be lost leaving only the base of the stack. | |
228 if (depth >= stack_slots_) { | |
229 // Since no other threads modify the data, no compare/exchange is needed. | |
230 // Since no other memory is being modified, a "relaxed" store is acceptable. | |
231 header_->current_depth.store(depth + 1, std::memory_order_relaxed); | |
232 return; | |
233 } | |
234 | |
235 // Get a pointer to the next activity and load it. No atomicity is required | |
236 // here because the memory is known only to this thread. It will be made | |
237 // known to other threads once the depth is incremented. | |
238 Activity* activity = &stack_[depth]; | |
239 activity->time_internal = base::TimeTicks::Now().ToInternalValue(); | |
240 activity->origin_address = reinterpret_cast<uintptr_t>(origin); | |
241 activity->activity_type = type; | |
242 activity->data = data; | |
243 | |
244 #if defined(SYZYASAN) | |
245 // Create a stacktrace from the current location and get the addresses. | |
246 StackTrace stack_trace; | |
247 size_t stack_depth; | |
248 const void* const* stack_addrs = stack_trace.Addresses(&stack_depth); | |
249 // Copy the stack addresses, ignoring the first one (here). | |
250 size_t i; | |
251 for (i = 1; i < stack_depth && i < kActivityCallStackSize; ++i) { | |
252 activity->call_stack[i - 1] = reinterpret_cast<uintptr_t>(stack_addrs[i]); | |
253 } | |
254 activity->call_stack[i - 1] = 0; | |
255 #else | |
256 // Since the memory was initially zero and nothing ever overwrites it in | |
257 // this "else" case, there is no need to write even the null terminator. | |
258 //activity->call_stack[0] = 0; | |
259 #endif | |
260 | |
261 // Save the incremented depth. Because this guards |activity| memory filled | |
262 // above that may be read by another thread once the recorded depth changes, | |
263 // a "release" store is required. | |
264 header_->current_depth.store(depth + 1, std::memory_order_release); | |
265 } | |
266 | |
267 void ThreadActivityTracker::ChangeActivity(ActivityType type, | |
268 const ActivityData& data) { | |
269 DCHECK(thread_checker_.CalledOnValidThread()); | |
270 DCHECK(type != ACT_NULL || &data != &kNullActivityData); | |
271 | |
272 // Get the current depth of the stack and acquire the data held there. | |
273 uint32_t depth = header_->current_depth.load(std::memory_order_acquire); | |
274 DCHECK_LT(0U, depth); | |
275 | |
276 // Update the information if it is being recorded (i.e. within slot limit). | |
277 if (depth <= stack_slots_) { | |
278 Activity* activity = &stack_[depth - 1]; | |
279 | |
280 if (type != ACT_NULL) { | |
281 DCHECK_EQ(activity->activity_type & ACT_CATEGORY_MASK, | |
282 type & ACT_CATEGORY_MASK); | |
283 activity->activity_type = type; | |
284 } | |
285 | |
286 if (&data != &kNullActivityData) | |
287 activity->data = data; | |
288 } | |
289 } | |
290 | |
291 void ThreadActivityTracker::PopActivity() { | |
292 // Do an atomic decrement of the depth. No changes to stack entries guarded | |
293 // by this variable are done here so a "relaxed" operation is acceptable. | |
294 // |depth| will receive the value BEFORE it was modified. | |
295 uint32_t depth = | |
296 header_->current_depth.fetch_sub(1, std::memory_order_relaxed); | |
297 | |
298 // Validate that everything is running correctly. | |
299 DCHECK_LT(0U, depth); | |
300 | |
301 // A thread-checker creates a lock to check the thread-id which means | |
302 // re-entry into this code if lock acquisitions are being tracked. | |
303 DCHECK(stack_[depth - 1].activity_type == ACT_LOCK_ACQUIRE || | |
304 thread_checker_.CalledOnValidThread()); | |
305 | |
306 // The stack has shrunk meaning that some other thread trying to copy the | |
307 // contents for reporting purposes could get bad data. That thread would | |
308 // have written a non-zero value into |stack_unchanged|; clearing it here | |
309 // will let that thread detect that something did change. This needs to | |
310 // happen after the atomic |depth| operation above so a "release" store | |
311 // is required. | |
312 header_->stack_unchanged.store(0, std::memory_order_release); | |
313 } | |
314 | |
315 bool ThreadActivityTracker::IsValid() const { | |
316 if (header_->cookie != kHeaderCookie || | |
317 header_->process_id == 0 || | |
318 header_->thread_ref.as_id == 0 || | |
319 header_->start_time == 0 || | |
320 header_->start_ticks == 0 || | |
321 header_->stack_slots != stack_slots_ || | |
322 header_->thread_name[sizeof(header_->thread_name) - 1] != '\0') { | |
323 return false; | |
324 } | |
325 | |
326 return valid_; | |
327 } | |
328 | |
329 bool ThreadActivityTracker::Snapshot(ActivitySnapshot* output_snapshot) const { | |
330 DCHECK(output_snapshot); | |
331 | |
332 // There is no "called on valid thread" check for this method as it can be | |
333 // called from other threads or even other processes. It is also the reason | |
334 // why atomic operations must be used in certain places above. | |
335 | |
336 // It's possible for the data to change while reading it in such a way that it | |
337 // invalidates the read. Make several attempts but don't try forever. | |
338 const int kMaxAttempts = 10; | |
339 uint32_t depth; | |
340 | |
341 // Stop here if the data isn't valid. | |
342 if (!IsValid()) | |
343 return false; | |
344 | |
345 // Allocate the maximum size for the stack so it doesn't have to be done | |
346 // during the time-sensitive snapshot operation. It is shrunk once the | |
347 // actual size is known. | |
348 output_snapshot->activity_stack.resize(stack_slots_); | |
manzagop (departed)
2016/07/26 21:25:34
nit: use reserve for a clearer intent?
bcwhite
2016/07/29 17:38:39
Done.
| |
349 | |
350 for (int attempt = 0; attempt < kMaxAttempts; ++attempt) { | |
351 // Remember the process and thread IDs to ensure they aren't replaced | |
352 // during the snapshot operation. | |
353 const int64_t starting_process_id = header_->process_id; | |
354 const int64_t starting_thread_id = header_->thread_ref.as_id; | |
355 | |
356 // Write a non-zero value to |stack_unchanged| so it's possible to detect | |
357 // at the end that nothing has changed since copying the data began. A | |
358 // "cst" operation is required to ensure it occurs before everything else. | |
359 // Using "cst" memory ordering is relatively expensive but this is only | |
360 // done during analysis so doesn't directly affect the worker threads. | |
361 header_->stack_unchanged.store(1, std::memory_order_seq_cst); | |
362 | |
363 // Fetching the current depth also "acquires" the contents of the stack. | |
364 depth = header_->current_depth.load(std::memory_order_acquire); | |
365 uint32_t count = std::min(depth, stack_slots_); | |
366 if (count > 0) { | |
367 // Copy the existing contents. Memcpy is used for speed. | |
368 memcpy(&output_snapshot->activity_stack[0], stack_, | |
369 count * sizeof(Activity)); | |
370 } | |
371 output_snapshot->activity_stack.resize(count); | |
manzagop (departed)
2016/07/26 21:25:34
Resize before the copy so we never copy outside th
bcwhite
2016/07/29 17:38:38
Done, though it was previously resized/reserved to
manzagop (departed)
2016/07/29 18:44:33
Ah, the issue I was seeing is across many attempts
bcwhite
2016/08/01 14:51:37
Acknowledged.
| |
372 | |
373 // Retry if something changed during the copy. A "cst" operation ensures | |
374 // it must happen after all the above operations. | |
375 if (!header_->stack_unchanged.load(std::memory_order_seq_cst)) | |
376 continue; | |
377 | |
378 // Stack copied. Record it's full depth. | |
379 output_snapshot->activity_stack_depth = depth; | |
380 | |
381 // TODO(bcwhite): Snapshot other things here. | |
382 | |
383 // Get the general thread information. | |
384 output_snapshot->process_id = header_->process_id; | |
385 output_snapshot->thread_id = header_->thread_ref.as_id; | |
386 output_snapshot->thread_name = | |
387 std::string(header_->thread_name, sizeof(header_->thread_name) - 1); | |
388 | |
389 // All characters of the thread-name buffer were copied so as to not break | |
390 // if the trailing NUL were missing. Now limit the length if the actual | |
391 // name is shorter. | |
392 output_snapshot->thread_name.resize( | |
393 strlen(output_snapshot->thread_name.c_str())); | |
394 | |
395 // If the process or thread ID has changed then the tracker has exited and | |
396 // the memory reused by a new one. Try again. | |
397 if (output_snapshot->process_id != starting_process_id || | |
398 output_snapshot->thread_id != starting_thread_id) { | |
399 continue; | |
400 } | |
401 | |
402 // Only successful if the data is still valid once everything is done since | |
403 // it's possible for the thread to end somewhere in the middle and all its | |
404 // values become garbage. | |
405 if (!IsValid()) | |
406 return false; | |
407 | |
408 // Change all the timestamps in the activities from "ticks" to "wall" time. | |
409 const Time start_time = Time::FromInternalValue(header_->start_time); | |
410 const int64_t start_ticks = header_->start_ticks; | |
411 for (Activity& activity : output_snapshot->activity_stack) { | |
412 activity.time_internal = | |
413 (start_time + | |
414 TimeDelta::FromInternalValue(activity.time_internal - start_ticks)) | |
415 .ToInternalValue(); | |
416 } | |
417 | |
418 // Success! | |
419 return true; | |
420 } | |
421 | |
422 // Too many attempts. | |
423 return false; | |
424 } | |
425 | |
426 // static | |
427 size_t ThreadActivityTracker::SizeForStackDepth(int stack_depth) { | |
428 return static_cast<size_t>(stack_depth) * sizeof(Activity) + sizeof(Header); | |
429 } | |
430 | |
431 | |
432 GlobalActivityTracker* GlobalActivityTracker::g_tracker_ = nullptr; | |
433 | |
434 GlobalActivityTracker::ManagedActivityTracker::ManagedActivityTracker( | |
435 PersistentMemoryAllocator::Reference mem_reference, | |
436 void* base, | |
437 size_t size) | |
438 : ThreadActivityTracker(base, size), | |
439 mem_reference_(mem_reference), | |
440 mem_base_(base) {} | |
441 | |
442 GlobalActivityTracker::ManagedActivityTracker::~ManagedActivityTracker() { | |
443 // The global |g_tracker_| must point to the owner of this class since all | |
444 // objects of this type must be destructed before |g_tracker_| can be changed | |
445 // (something that only occurs in tests). | |
446 DCHECK(g_tracker_); | |
447 g_tracker_->ReturnTrackerMemory(this); | |
448 } | |
449 | |
450 void GlobalActivityTracker::CreateWithAllocator( | |
451 std::unique_ptr<PersistentMemoryAllocator> allocator, | |
452 int stack_depth) { | |
453 // There's no need to do anything with the result. It is self-managing. | |
454 GlobalActivityTracker* global_tracker = | |
455 new GlobalActivityTracker(std::move(allocator), stack_depth); | |
456 // Create a tracker for this thread since it is known. | |
457 global_tracker->CreateTrackerForCurrentThread(); | |
458 } | |
459 | |
460 #if !defined(OS_NACL) | |
461 // static | |
462 void GlobalActivityTracker::CreateWithFile(const FilePath& file_path, | |
463 size_t size, | |
464 uint64_t id, | |
465 StringPiece name, | |
466 int stack_depth) { | |
467 DCHECK(!file_path.empty()); | |
468 DCHECK_GE(static_cast<uint64_t>(std::numeric_limits<int64_t>::max()), size); | |
469 | |
470 // Create and map the file into memory and make it globally available. | |
471 std::unique_ptr<MemoryMappedFile> mapped_file(new MemoryMappedFile()); | |
472 bool success = | |
473 mapped_file->Initialize(File(file_path, | |
474 File::FLAG_CREATE_ALWAYS | File::FLAG_READ | | |
475 File::FLAG_WRITE | File::FLAG_SHARE_DELETE), | |
476 {0, static_cast<int64_t>(size)}, | |
477 MemoryMappedFile::READ_WRITE_EXTEND); | |
478 DCHECK(success); | |
479 CreateWithAllocator(WrapUnique(new FilePersistentMemoryAllocator( | |
480 std::move(mapped_file), size, id, name, false)), | |
481 stack_depth); | |
482 } | |
483 #endif // !defined(OS_NACL) | |
484 | |
485 // static | |
486 void GlobalActivityTracker::CreateWithLocalMemory(size_t size, | |
487 uint64_t id, | |
488 StringPiece name, | |
489 int stack_depth) { | |
490 CreateWithAllocator( | |
491 WrapUnique(new LocalPersistentMemoryAllocator(size, id, name)), | |
492 stack_depth); | |
493 } | |
494 | |
495 ThreadActivityTracker* GlobalActivityTracker::CreateTrackerForCurrentThread() { | |
496 DCHECK(!this_thread_tracker_.Get()); | |
497 | |
498 PersistentMemoryAllocator::Reference mem_reference = 0; | |
499 void* mem_base = nullptr; | |
500 | |
501 // Get the current count of available memories, acquiring the array values. | |
502 int count = available_memories_count_.load(std::memory_order_acquire); | |
503 while (count > 0) { | |
504 // There is a memory block that was previously released (and zeroed) so | |
505 // just re-use that rather than allocating a new one. Use "relaxed" because | |
506 // the value is guarded by the |count| "acquire". A zero reference replaces | |
507 // the existing value so that it can't be used by another thread that | |
508 // manages to interrupt this one before the count can be decremented. | |
509 // A zero reference is also required for the "push" operation to work | |
510 // once the count finally does get decremented. | |
511 mem_reference = | |
512 available_memories_[count - 1].exchange(0, std::memory_order_relaxed); | |
513 | |
514 // If the reference is zero, it's already been taken but count hasn't yet | |
515 // been decremented. Give that other thread a chance to finish then reload | |
516 // the "count" value and try again. | |
517 if (!mem_reference) { | |
518 PlatformThread::YieldCurrentThread(); | |
519 count = available_memories_count_.load(std::memory_order_acquire); | |
520 continue; | |
521 } | |
522 | |
523 // Decrement the count indicating that the value has been taken. If this | |
524 // fails then another thread has pushed something new and incremented the | |
525 // count. | |
526 // NOTE: |oldcount| will be loaded with the existing value. | |
527 int oldcount = count; | |
528 if (!available_memories_count_.compare_exchange_strong( | |
529 oldcount, count - 1, std::memory_order_acquire, | |
530 std::memory_order_acquire)) { | |
531 DCHECK_LT(count, oldcount); | |
532 | |
533 // Restore the reference that was zeroed above and try again. | |
534 available_memories_[count - 1].store(mem_reference, | |
535 std::memory_order_relaxed); | |
536 count = oldcount; | |
537 continue; | |
538 } | |
539 | |
540 // Turn the reference back into one of the activity-tracker type. | |
541 mem_base = allocator_->GetAsObject<char>(mem_reference, | |
542 kTypeIdActivityTrackerFree); | |
543 DCHECK(mem_base); | |
544 DCHECK_LE(stack_memory_size_, allocator_->GetAllocSize(mem_reference)); | |
545 allocator_->ChangeType(mem_reference, kTypeIdActivityTracker, | |
manzagop (departed)
2016/07/26 21:25:34
DCHECK this returns true?
bcwhite
2016/07/29 17:38:38
Done.
| |
546 kTypeIdActivityTrackerFree); | |
547 | |
548 // Success. | |
549 break; | |
550 } | |
551 | |
552 // Handle the case where no previously-used memories are available. | |
553 if (count == 0) { | |
554 // Allocate a block of memory from the persistent segment. | |
555 mem_reference = | |
556 allocator_->Allocate(stack_memory_size_, kTypeIdActivityTracker); | |
557 if (mem_reference) { | |
558 // Success. Convert the reference to an actual memory address. | |
559 mem_base = | |
560 allocator_->GetAsObject<char>(mem_reference, kTypeIdActivityTracker); | |
561 // Make the allocation iterable so it can be found by other processes. | |
562 allocator_->MakeIterable(mem_reference); | |
563 } else { | |
564 // Failure. This shouldn't happen. | |
565 NOTREACHED(); | |
566 // But if it does, probably because the allocator wasn't given enough | |
567 // memory to satisfy all possible requests, handle it gracefully by | |
568 // allocating the required memory from the heap. | |
569 mem_base = new char[stack_memory_size_]; | |
570 memset(mem_base, 0, stack_memory_size_); | |
571 // Report the thread-count at which the allocator was full so that the | |
572 // failure can be seen and underlying memory resized appropriately. | |
573 UMA_HISTOGRAM_COUNTS_1000( | |
574 "UMA.ActivityTracker.ThreadTrackers.MemLimitTrackerCount", | |
575 thread_tracker_count_.load(std::memory_order_relaxed)); | |
576 } | |
577 } | |
578 | |
579 // Create a tracker with the acquired memory and set it as the tracker | |
580 // for this particular thread in thread-local-storage. | |
581 DCHECK(mem_base); | |
582 ManagedActivityTracker* tracker = | |
583 new ManagedActivityTracker(mem_reference, mem_base, stack_memory_size_); | |
584 DCHECK(tracker->IsValid()); | |
585 this_thread_tracker_.Set(tracker); | |
586 int old_count = thread_tracker_count_.fetch_add(1, std::memory_order_relaxed); | |
587 | |
588 UMA_HISTOGRAM_ENUMERATION("UMA.ActivityTracker.ThreadTrackers.Count", | |
589 old_count + 1, kMaxThreadCount); | |
590 return tracker; | |
591 } | |
592 | |
593 void GlobalActivityTracker::ReleaseTrackerForCurrentThreadForTesting() { | |
594 ThreadActivityTracker* tracker = | |
595 reinterpret_cast<ThreadActivityTracker*>(this_thread_tracker_.Get()); | |
596 if (tracker) { | |
597 this_thread_tracker_.Free(); | |
598 delete tracker; | |
599 } | |
600 } | |
601 | |
602 GlobalActivityTracker::GlobalActivityTracker( | |
603 std::unique_ptr<PersistentMemoryAllocator> allocator, | |
604 int stack_depth) | |
605 : allocator_(std::move(allocator)), | |
606 stack_memory_size_(ThreadActivityTracker::SizeForStackDepth(stack_depth)), | |
607 this_thread_tracker_(&OnTLSDestroy), | |
608 thread_tracker_count_(0), | |
609 available_memories_count_(0) { | |
610 // Clear the available-memories array. | |
611 memset(available_memories_, 0, sizeof(available_memories_)); | |
612 | |
613 // Ensure the passed memory is valid and empty (iterator finds nothing). | |
614 uint32_t type; | |
615 DCHECK(!PersistentMemoryAllocator::Iterator(allocator_.get()).GetNext(&type)); | |
616 | |
617 // Ensure that there is no other global object and then make this one such. | |
618 DCHECK(!g_tracker_); | |
619 g_tracker_ = this; | |
620 } | |
621 | |
622 GlobalActivityTracker::~GlobalActivityTracker() { | |
623 DCHECK_EQ(g_tracker_, this); | |
624 DCHECK_EQ(0, thread_tracker_count_.load(std::memory_order_relaxed)); | |
625 g_tracker_ = nullptr; | |
626 } | |
627 | |
628 void GlobalActivityTracker::ReturnTrackerMemory( | |
629 ManagedActivityTracker* tracker) { | |
630 PersistentMemoryAllocator::Reference mem_reference = tracker->mem_reference_; | |
631 void* mem_base = tracker->mem_base_; | |
632 | |
633 // Zero the memory so that it is ready for use if needed again later. It's | |
634 // better to clear the memory now, when a thread is exiting, than to do it | |
635 // when it is first needed by a thread doing actual work. | |
636 memset(mem_base, 0, stack_memory_size_); | |
637 | |
638 // Remove the destructed tracker from the set of known ones. | |
639 DCHECK_LE(1, thread_tracker_count_.load(std::memory_order_relaxed)); | |
640 thread_tracker_count_.fetch_sub(1, std::memory_order_relaxed); | |
641 | |
642 // Deal with the memory that was used by the tracker. | |
643 if (mem_reference) { | |
644 // The memory was within the persistent memory allocator. Change its type | |
645 // so that iteration won't find it. | |
646 allocator_->ChangeType(mem_reference, kTypeIdActivityTrackerFree, | |
647 kTypeIdActivityTracker); | |
648 // There is no way to free memory from a persistent allocator so instead | |
649 // push it on the internal list of available memory blocks. | |
650 while (true) { | |
651 // Get the existing count of available memories and ensure we won't | |
652 // burst the array. Acquire the values in the array. | |
653 int count = available_memories_count_.load(std::memory_order_acquire); | |
654 if (count >= kMaxThreadCount) { | |
655 NOTREACHED(); | |
656 // Storage is full. Just forget about this memory. It won't be re-used | |
657 // but there's no real loss. | |
658 break; | |
659 } | |
660 | |
661 // Write the reference of the memory being returned to this slot in the | |
662 // array. Empty slots have a value of zero so do an atomic compare-and- | |
663 // exchange to ensure that a race condition doesn't exist with another | |
664 // thread doing the same. | |
665 PersistentMemoryAllocator::Reference mem_expected = 0; | |
666 if (!available_memories_[count].compare_exchange_strong( | |
667 mem_expected, mem_reference, std::memory_order_release, | |
668 std::memory_order_relaxed)) { | |
669 PlatformThread::YieldCurrentThread(); | |
670 continue; // Try again. | |
671 } | |
672 | |
673 // Increment the count, releasing the value written to the array. This | |
674 // could fail if a simultaneous "pop" operation decremented the counter. | |
675 // If that happens, clear the array slot and start over. Do a "strong" | |
676 // exchange to avoid spurious retries that can occur with a "weak" one. | |
677 int expected = count; // Updated by compare/exchange. | |
678 if (!available_memories_count_.compare_exchange_strong( | |
679 expected, count + 1, std::memory_order_release, | |
680 std::memory_order_relaxed)) { | |
681 available_memories_[count].store(0, std::memory_order_relaxed); | |
682 continue; | |
683 } | |
684 | |
685 // Count was successfully incremented to reflect the newly added value. | |
686 break; | |
687 } | |
688 } else { | |
689 // The memory was allocated from the process heap. This shouldn't happen | |
690 // because the persistent memory segment should be big enough for all | |
691 // thread stacks but it's better to support falling back to allocation | |
692 // from the heap rather than crash. Everything will work as normal but | |
693 // the data won't be persisted. | |
694 delete[] reinterpret_cast<char*>(mem_base); | |
695 } | |
696 } | |
697 | |
698 // static | |
699 void GlobalActivityTracker::OnTLSDestroy(void* value) { | |
700 delete reinterpret_cast<ManagedActivityTracker*>(value); | |
701 } | |
702 | |
703 | |
704 ScopedActivity::ScopedActivity(const tracked_objects::Location& location, | |
705 uint8_t action, | |
706 uint32_t id, | |
707 int32_t info) | |
708 : GlobalActivityTracker::ScopedThreadActivity( | |
709 location.program_counter(), | |
710 static_cast<ThreadActivityTracker::ActivityType>( | |
711 ThreadActivityTracker::ACT_GENERIC | action), | |
712 ThreadActivityTracker::ActivityData::ForGeneric(id, info), | |
713 /*lock_allowed=*/true), | |
714 id_(id) { | |
715 // The action must not affect the category bits of the activity type. | |
716 DCHECK_EQ(0, action & ThreadActivityTracker::ACT_CATEGORY_MASK); | |
717 } | |
718 | |
719 void ScopedActivity::ChangeAction(uint8_t action) { | |
720 DCHECK_EQ(0, action & ThreadActivityTracker::ACT_CATEGORY_MASK); | |
721 ChangeTypeAndData(static_cast<ThreadActivityTracker::ActivityType>( | |
722 ThreadActivityTracker::ACT_GENERIC | action), | |
723 ThreadActivityTracker::kNullActivityData); | |
724 } | |
725 | |
726 void ScopedActivity::ChangeInfo(int32_t info) { | |
727 ChangeTypeAndData(ThreadActivityTracker::ACT_NULL, | |
728 ThreadActivityTracker::ActivityData::ForGeneric(id_, info)); | |
729 } | |
730 | |
731 void ScopedActivity::ChangeActionAndInfo(uint8_t action, int32_t info) { | |
732 DCHECK_EQ(0, action & ThreadActivityTracker::ACT_CATEGORY_MASK); | |
733 ChangeTypeAndData(static_cast<ThreadActivityTracker::ActivityType>( | |
734 ThreadActivityTracker::ACT_GENERIC | action), | |
735 ThreadActivityTracker::ActivityData::ForGeneric(id_, info)); | |
736 } | |
737 | |
738 ScopedTaskRunActivity::ScopedTaskRunActivity(const base::PendingTask& task) | |
739 : GlobalActivityTracker::ScopedThreadActivity( | |
740 task.posted_from.program_counter(), | |
741 ThreadActivityTracker::ACT_TASK_RUN, | |
742 ThreadActivityTracker::ActivityData::ForTask(task.sequence_num), | |
743 /*lock_allowed=*/true) {} | |
744 | |
745 ScopedLockAcquireActivity::ScopedLockAcquireActivity( | |
746 const base::internal::LockImpl* lock) | |
747 : GlobalActivityTracker::ScopedThreadActivity( | |
748 nullptr, | |
749 ThreadActivityTracker::ACT_LOCK_ACQUIRE, | |
750 ThreadActivityTracker::ActivityData::ForLock(lock), | |
751 /*lock_allowed=*/false) {} | |
752 | |
753 ScopedEventWaitActivity::ScopedEventWaitActivity( | |
754 const base::WaitableEvent* event) | |
755 : GlobalActivityTracker::ScopedThreadActivity( | |
756 nullptr, | |
757 ThreadActivityTracker::ACT_EVENT_WAIT, | |
758 ThreadActivityTracker::ActivityData::ForEvent(event), | |
759 /*lock_allowed=*/true) {} | |
760 | |
761 ScopedThreadJoinActivity::ScopedThreadJoinActivity( | |
762 const base::PlatformThreadHandle* thread) | |
763 : GlobalActivityTracker::ScopedThreadActivity( | |
764 nullptr, | |
765 ThreadActivityTracker::ACT_THREAD_JOIN, | |
766 ThreadActivityTracker::ActivityData::ForThread(*thread), | |
767 /*lock_allowed=*/true) {} | |
768 | |
769 #if !defined(OS_NACL) && !defined(OS_IOS) | |
770 ScopedProcessWaitActivity::ScopedProcessWaitActivity( | |
771 const base::Process* process) | |
772 : GlobalActivityTracker::ScopedThreadActivity( | |
773 nullptr, | |
774 ThreadActivityTracker::ACT_PROCESS_WAIT, | |
775 ThreadActivityTracker::ActivityData::ForProcess(process->Pid()), | |
776 /*lock_allowed=*/true) {} | |
777 #endif | |
778 | |
779 } // namespace debug | |
780 } // namespace base | |
OLD | NEW |