Add a stat to the smoothness benchmark for avg number of missing tiles.
[chromium-blink-merge.git] / base / tracked_objects.cc
blobf5dc82dff2005828a3b96a3da53be261f8f3fb70
1 // Copyright (c) 2012 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.
5 #include "base/tracked_objects.h"
7 #include <math.h>
8 #include <stdlib.h>
10 #include "base/format_macros.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/process_util.h"
13 #include "base/profiler/alternate_timer.h"
14 #include "base/stringprintf.h"
15 #include "base/third_party/valgrind/memcheck.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "base/port.h"
19 using base::TimeDelta;
21 namespace tracked_objects {
23 namespace {
24 // Flag to compile out almost all of the task tracking code.
25 const bool kTrackAllTaskObjects = true;
27 // TODO(jar): Evaluate the perf impact of enabling this. If the perf impact is
28 // negligible, enable by default.
29 // Flag to compile out parent-child link recording.
30 const bool kTrackParentChildLinks = false;
32 // When ThreadData is first initialized, should we start in an ACTIVE state to
33 // record all of the startup-time tasks, or should we start up DEACTIVATED, so
34 // that we only record after parsing the command line flag --enable-tracking.
35 // Note that the flag may force either state, so this really controls only the
36 // period of time up until that flag is parsed. If there is no flag seen, then
37 // this state may prevail for much or all of the process lifetime.
38 const ThreadData::Status kInitialStartupState =
39 ThreadData::PROFILING_CHILDREN_ACTIVE;
41 // Control whether an alternate time source (Now() function) is supported by
42 // the ThreadData class. This compile time flag should be set to true if we
43 // want other modules (such as a memory allocator, or a thread-specific CPU time
44 // clock) to be able to provide a thread-specific Now() function. Without this
45 // compile-time flag, the code will only support the wall-clock time. This flag
46 // can be flipped to efficiently disable this path (if there is a performance
47 // problem with its presence).
48 static const bool kAllowAlternateTimeSourceHandling = true;
50 } // namespace
52 //------------------------------------------------------------------------------
53 // DeathData tallies durations when a death takes place.
55 DeathData::DeathData() {
56 Clear();
59 DeathData::DeathData(int count) {
60 Clear();
61 count_ = count;
64 // TODO(jar): I need to see if this macro to optimize branching is worth using.
66 // This macro has no branching, so it is surely fast, and is equivalent to:
67 // if (assign_it)
68 // target = source;
69 // We use a macro rather than a template to force this to inline.
70 // Related code for calculating max is discussed on the web.
71 #define CONDITIONAL_ASSIGN(assign_it, target, source) \
72 ((target) ^= ((target) ^ (source)) & -static_cast<int32>(assign_it))
74 void DeathData::RecordDeath(const int32 queue_duration,
75 const int32 run_duration,
76 int32 random_number) {
77 ++count_;
78 queue_duration_sum_ += queue_duration;
79 run_duration_sum_ += run_duration;
81 if (queue_duration_max_ < queue_duration)
82 queue_duration_max_ = queue_duration;
83 if (run_duration_max_ < run_duration)
84 run_duration_max_ = run_duration;
86 // Take a uniformly distributed sample over all durations ever supplied.
87 // The probability that we (instead) use this new sample is 1/count_. This
88 // results in a completely uniform selection of the sample (at least when we
89 // don't clamp count_... but that should be inconsequentially likely).
90 // We ignore the fact that we correlated our selection of a sample to the run
91 // and queue times (i.e., we used them to generate random_number).
92 if (count_ <= 0) { // Handle wrapping of count_, such as in bug 138961.
93 CHECK_GE(count_ - 1, 0); // Detect memory corruption.
94 // We'll just clamp at INT_MAX, but we should note this in the UI as such.
95 count_ = INT_MAX;
97 if (0 == (random_number % count_)) {
98 queue_duration_sample_ = queue_duration;
99 run_duration_sample_ = run_duration;
103 int DeathData::count() const { return count_; }
105 int32 DeathData::run_duration_sum() const { return run_duration_sum_; }
107 int32 DeathData::run_duration_max() const { return run_duration_max_; }
109 int32 DeathData::run_duration_sample() const {
110 return run_duration_sample_;
113 int32 DeathData::queue_duration_sum() const {
114 return queue_duration_sum_;
117 int32 DeathData::queue_duration_max() const {
118 return queue_duration_max_;
121 int32 DeathData::queue_duration_sample() const {
122 return queue_duration_sample_;
125 void DeathData::ResetMax() {
126 run_duration_max_ = 0;
127 queue_duration_max_ = 0;
130 void DeathData::Clear() {
131 count_ = 0;
132 run_duration_sum_ = 0;
133 run_duration_max_ = 0;
134 run_duration_sample_ = 0;
135 queue_duration_sum_ = 0;
136 queue_duration_max_ = 0;
137 queue_duration_sample_ = 0;
140 //------------------------------------------------------------------------------
141 DeathDataSnapshot::DeathDataSnapshot()
142 : count(-1),
143 run_duration_sum(-1),
144 run_duration_max(-1),
145 run_duration_sample(-1),
146 queue_duration_sum(-1),
147 queue_duration_max(-1),
148 queue_duration_sample(-1) {
151 DeathDataSnapshot::DeathDataSnapshot(
152 const tracked_objects::DeathData& death_data)
153 : count(death_data.count()),
154 run_duration_sum(death_data.run_duration_sum()),
155 run_duration_max(death_data.run_duration_max()),
156 run_duration_sample(death_data.run_duration_sample()),
157 queue_duration_sum(death_data.queue_duration_sum()),
158 queue_duration_max(death_data.queue_duration_max()),
159 queue_duration_sample(death_data.queue_duration_sample()) {
162 DeathDataSnapshot::~DeathDataSnapshot() {
165 //------------------------------------------------------------------------------
166 BirthOnThread::BirthOnThread(const Location& location,
167 const ThreadData& current)
168 : location_(location),
169 birth_thread_(&current) {
172 //------------------------------------------------------------------------------
173 BirthOnThreadSnapshot::BirthOnThreadSnapshot() {
176 BirthOnThreadSnapshot::BirthOnThreadSnapshot(
177 const tracked_objects::BirthOnThread& birth)
178 : location(birth.location()),
179 thread_name(birth.birth_thread()->thread_name()) {
182 BirthOnThreadSnapshot::~BirthOnThreadSnapshot() {
185 //------------------------------------------------------------------------------
186 Births::Births(const Location& location, const ThreadData& current)
187 : BirthOnThread(location, current),
188 birth_count_(1) { }
190 int Births::birth_count() const { return birth_count_; }
192 void Births::RecordBirth() { ++birth_count_; }
194 void Births::ForgetBirth() { --birth_count_; }
196 void Births::Clear() { birth_count_ = 0; }
198 //------------------------------------------------------------------------------
199 // ThreadData maintains the central data for all births and deaths on a single
200 // thread.
202 // TODO(jar): We should pull all these static vars together, into a struct, and
203 // optimize layout so that we benefit from locality of reference during accesses
204 // to them.
206 // static
207 NowFunction* ThreadData::now_function_ = NULL;
209 // A TLS slot which points to the ThreadData instance for the current thread. We
210 // do a fake initialization here (zeroing out data), and then the real in-place
211 // construction happens when we call tls_index_.Initialize().
212 // static
213 base::ThreadLocalStorage::StaticSlot ThreadData::tls_index_ = TLS_INITIALIZER;
215 // static
216 int ThreadData::worker_thread_data_creation_count_ = 0;
218 // static
219 int ThreadData::cleanup_count_ = 0;
221 // static
222 int ThreadData::incarnation_counter_ = 0;
224 // static
225 ThreadData* ThreadData::all_thread_data_list_head_ = NULL;
227 // static
228 ThreadData* ThreadData::first_retired_worker_ = NULL;
230 // static
231 base::LazyInstance<base::Lock>::Leaky
232 ThreadData::list_lock_ = LAZY_INSTANCE_INITIALIZER;
234 // static
235 ThreadData::Status ThreadData::status_ = ThreadData::UNINITIALIZED;
237 ThreadData::ThreadData(const std::string& suggested_name)
238 : next_(NULL),
239 next_retired_worker_(NULL),
240 worker_thread_number_(0),
241 incarnation_count_for_pool_(-1) {
242 DCHECK_GE(suggested_name.size(), 0u);
243 thread_name_ = suggested_name;
244 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
247 ThreadData::ThreadData(int thread_number)
248 : next_(NULL),
249 next_retired_worker_(NULL),
250 worker_thread_number_(thread_number),
251 incarnation_count_for_pool_(-1) {
252 CHECK_GT(thread_number, 0);
253 base::StringAppendF(&thread_name_, "WorkerThread-%d", thread_number);
254 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
257 ThreadData::~ThreadData() {}
259 void ThreadData::PushToHeadOfList() {
260 // Toss in a hint of randomness (atop the uniniitalized value).
261 (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_,
262 sizeof(random_number_));
263 random_number_ += static_cast<int32>(this - static_cast<ThreadData*>(0));
264 random_number_ ^= (Now() - TrackedTime()).InMilliseconds();
266 DCHECK(!next_);
267 base::AutoLock lock(*list_lock_.Pointer());
268 incarnation_count_for_pool_ = incarnation_counter_;
269 next_ = all_thread_data_list_head_;
270 all_thread_data_list_head_ = this;
273 // static
274 ThreadData* ThreadData::first() {
275 base::AutoLock lock(*list_lock_.Pointer());
276 return all_thread_data_list_head_;
279 ThreadData* ThreadData::next() const { return next_; }
281 // static
282 void ThreadData::InitializeThreadContext(const std::string& suggested_name) {
283 if (!Initialize()) // Always initialize if needed.
284 return;
285 ThreadData* current_thread_data =
286 reinterpret_cast<ThreadData*>(tls_index_.Get());
287 if (current_thread_data)
288 return; // Browser tests instigate this.
289 current_thread_data = new ThreadData(suggested_name);
290 tls_index_.Set(current_thread_data);
293 // static
294 ThreadData* ThreadData::Get() {
295 if (!tls_index_.initialized())
296 return NULL; // For unittests only.
297 ThreadData* registered = reinterpret_cast<ThreadData*>(tls_index_.Get());
298 if (registered)
299 return registered;
301 // We must be a worker thread, since we didn't pre-register.
302 ThreadData* worker_thread_data = NULL;
303 int worker_thread_number = 0;
305 base::AutoLock lock(*list_lock_.Pointer());
306 if (first_retired_worker_) {
307 worker_thread_data = first_retired_worker_;
308 first_retired_worker_ = first_retired_worker_->next_retired_worker_;
309 worker_thread_data->next_retired_worker_ = NULL;
310 } else {
311 worker_thread_number = ++worker_thread_data_creation_count_;
315 // If we can't find a previously used instance, then we have to create one.
316 if (!worker_thread_data) {
317 DCHECK_GT(worker_thread_number, 0);
318 worker_thread_data = new ThreadData(worker_thread_number);
320 DCHECK_GT(worker_thread_data->worker_thread_number_, 0);
322 tls_index_.Set(worker_thread_data);
323 return worker_thread_data;
326 // static
327 void ThreadData::OnThreadTermination(void* thread_data) {
328 DCHECK(thread_data); // TLS should *never* call us with a NULL.
329 // We must NOT do any allocations during this callback. There is a chance
330 // that the allocator is no longer active on this thread.
331 if (!kTrackAllTaskObjects)
332 return; // Not compiled in.
333 reinterpret_cast<ThreadData*>(thread_data)->OnThreadTerminationCleanup();
336 void ThreadData::OnThreadTerminationCleanup() {
337 // The list_lock_ was created when we registered the callback, so it won't be
338 // allocated here despite the lazy reference.
339 base::AutoLock lock(*list_lock_.Pointer());
340 if (incarnation_counter_ != incarnation_count_for_pool_)
341 return; // ThreadData was constructed in an earlier unit test.
342 ++cleanup_count_;
343 // Only worker threads need to be retired and reused.
344 if (!worker_thread_number_) {
345 return;
347 // We must NOT do any allocations during this callback.
348 // Using the simple linked lists avoids all allocations.
349 DCHECK_EQ(this->next_retired_worker_, reinterpret_cast<ThreadData*>(NULL));
350 this->next_retired_worker_ = first_retired_worker_;
351 first_retired_worker_ = this;
354 // static
355 void ThreadData::Snapshot(bool reset_max, ProcessDataSnapshot* process_data) {
356 // Add births that have run to completion to |collected_data|.
357 // |birth_counts| tracks the total number of births recorded at each location
358 // for which we have not seen a death count.
359 BirthCountMap birth_counts;
360 ThreadData::SnapshotAllExecutedTasks(reset_max, process_data, &birth_counts);
362 // Add births that are still active -- i.e. objects that have tallied a birth,
363 // but have not yet tallied a matching death, and hence must be either
364 // running, queued up, or being held in limbo for future posting.
365 for (BirthCountMap::const_iterator it = birth_counts.begin();
366 it != birth_counts.end(); ++it) {
367 if (it->second > 0) {
368 process_data->tasks.push_back(
369 TaskSnapshot(*it->first, DeathData(it->second), "Still_Alive"));
374 Births* ThreadData::TallyABirth(const Location& location) {
375 BirthMap::iterator it = birth_map_.find(location);
376 Births* child;
377 if (it != birth_map_.end()) {
378 child = it->second;
379 child->RecordBirth();
380 } else {
381 child = new Births(location, *this); // Leak this.
382 // Lock since the map may get relocated now, and other threads sometimes
383 // snapshot it (but they lock before copying it).
384 base::AutoLock lock(map_lock_);
385 birth_map_[location] = child;
388 if (kTrackParentChildLinks && status_ > PROFILING_ACTIVE &&
389 !parent_stack_.empty()) {
390 const Births* parent = parent_stack_.top();
391 ParentChildPair pair(parent, child);
392 if (parent_child_set_.find(pair) == parent_child_set_.end()) {
393 // Lock since the map may get relocated now, and other threads sometimes
394 // snapshot it (but they lock before copying it).
395 base::AutoLock lock(map_lock_);
396 parent_child_set_.insert(pair);
400 return child;
403 void ThreadData::TallyADeath(const Births& birth,
404 int32 queue_duration,
405 int32 run_duration) {
406 // Stir in some randomness, plus add constant in case durations are zero.
407 const int32 kSomePrimeNumber = 2147483647;
408 random_number_ += queue_duration + run_duration + kSomePrimeNumber;
409 // An address is going to have some randomness to it as well ;-).
410 random_number_ ^= static_cast<int32>(&birth - reinterpret_cast<Births*>(0));
412 // We don't have queue durations without OS timer. OS timer is automatically
413 // used for task-post-timing, so the use of an alternate timer implies all
414 // queue times are invalid.
415 if (kAllowAlternateTimeSourceHandling && now_function_)
416 queue_duration = 0;
418 DeathMap::iterator it = death_map_.find(&birth);
419 DeathData* death_data;
420 if (it != death_map_.end()) {
421 death_data = &it->second;
422 } else {
423 base::AutoLock lock(map_lock_); // Lock as the map may get relocated now.
424 death_data = &death_map_[&birth];
425 } // Release lock ASAP.
426 death_data->RecordDeath(queue_duration, run_duration, random_number_);
428 if (!kTrackParentChildLinks)
429 return;
430 if (!parent_stack_.empty()) { // We might get turned off.
431 DCHECK_EQ(parent_stack_.top(), &birth);
432 parent_stack_.pop();
436 // static
437 Births* ThreadData::TallyABirthIfActive(const Location& location) {
438 if (!kTrackAllTaskObjects)
439 return NULL; // Not compiled in.
441 if (!TrackingStatus())
442 return NULL;
443 ThreadData* current_thread_data = Get();
444 if (!current_thread_data)
445 return NULL;
446 return current_thread_data->TallyABirth(location);
449 // static
450 void ThreadData::TallyRunOnNamedThreadIfTracking(
451 const base::TrackingInfo& completed_task,
452 const TrackedTime& start_of_run,
453 const TrackedTime& end_of_run) {
454 if (!kTrackAllTaskObjects)
455 return; // Not compiled in.
457 // Even if we have been DEACTIVATED, we will process any pending births so
458 // that our data structures (which counted the outstanding births) remain
459 // consistent.
460 const Births* birth = completed_task.birth_tally;
461 if (!birth)
462 return;
463 ThreadData* current_thread_data = Get();
464 if (!current_thread_data)
465 return;
467 // To avoid conflating our stats with the delay duration in a PostDelayedTask,
468 // we identify such tasks, and replace their post_time with the time they
469 // were scheduled (requested?) to emerge from the delayed task queue. This
470 // means that queueing delay for such tasks will show how long they went
471 // unserviced, after they *could* be serviced. This is the same stat as we
472 // have for non-delayed tasks, and we consistently call it queueing delay.
473 TrackedTime effective_post_time = completed_task.delayed_run_time.is_null()
474 ? tracked_objects::TrackedTime(completed_task.time_posted)
475 : tracked_objects::TrackedTime(completed_task.delayed_run_time);
477 // Watch out for a race where status_ is changing, and hence one or both
478 // of start_of_run or end_of_run is zero. In that case, we didn't bother to
479 // get a time value since we "weren't tracking" and we were trying to be
480 // efficient by not calling for a genuine time value. For simplicity, we'll
481 // use a default zero duration when we can't calculate a true value.
482 int32 queue_duration = 0;
483 int32 run_duration = 0;
484 if (!start_of_run.is_null()) {
485 queue_duration = (start_of_run - effective_post_time).InMilliseconds();
486 if (!end_of_run.is_null())
487 run_duration = (end_of_run - start_of_run).InMilliseconds();
489 current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
492 // static
493 void ThreadData::TallyRunOnWorkerThreadIfTracking(
494 const Births* birth,
495 const TrackedTime& time_posted,
496 const TrackedTime& start_of_run,
497 const TrackedTime& end_of_run) {
498 if (!kTrackAllTaskObjects)
499 return; // Not compiled in.
501 // Even if we have been DEACTIVATED, we will process any pending births so
502 // that our data structures (which counted the outstanding births) remain
503 // consistent.
504 if (!birth)
505 return;
507 // TODO(jar): Support the option to coalesce all worker-thread activity under
508 // one ThreadData instance that uses locks to protect *all* access. This will
509 // reduce memory (making it provably bounded), but run incrementally slower
510 // (since we'll use locks on TallyBirth and TallyDeath). The good news is
511 // that the locks on TallyDeath will be *after* the worker thread has run, and
512 // hence nothing will be waiting for the completion (... besides some other
513 // thread that might like to run). Also, the worker threads tasks are
514 // generally longer, and hence the cost of the lock may perchance be amortized
515 // over the long task's lifetime.
516 ThreadData* current_thread_data = Get();
517 if (!current_thread_data)
518 return;
520 int32 queue_duration = 0;
521 int32 run_duration = 0;
522 if (!start_of_run.is_null()) {
523 queue_duration = (start_of_run - time_posted).InMilliseconds();
524 if (!end_of_run.is_null())
525 run_duration = (end_of_run - start_of_run).InMilliseconds();
527 current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
530 // static
531 void ThreadData::TallyRunInAScopedRegionIfTracking(
532 const Births* birth,
533 const TrackedTime& start_of_run,
534 const TrackedTime& end_of_run) {
535 if (!kTrackAllTaskObjects)
536 return; // Not compiled in.
538 // Even if we have been DEACTIVATED, we will process any pending births so
539 // that our data structures (which counted the outstanding births) remain
540 // consistent.
541 if (!birth)
542 return;
544 ThreadData* current_thread_data = Get();
545 if (!current_thread_data)
546 return;
548 int32 queue_duration = 0;
549 int32 run_duration = 0;
550 if (!start_of_run.is_null() && !end_of_run.is_null())
551 run_duration = (end_of_run - start_of_run).InMilliseconds();
552 current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
555 // static
556 void ThreadData::SnapshotAllExecutedTasks(bool reset_max,
557 ProcessDataSnapshot* process_data,
558 BirthCountMap* birth_counts) {
559 if (!kTrackAllTaskObjects)
560 return; // Not compiled in.
562 // Get an unchanging copy of a ThreadData list.
563 ThreadData* my_list = ThreadData::first();
565 // Gather data serially.
566 // This hackish approach *can* get some slighly corrupt tallies, as we are
567 // grabbing values without the protection of a lock, but it has the advantage
568 // of working even with threads that don't have message loops. If a user
569 // sees any strangeness, they can always just run their stats gathering a
570 // second time.
571 for (ThreadData* thread_data = my_list;
572 thread_data;
573 thread_data = thread_data->next()) {
574 thread_data->SnapshotExecutedTasks(reset_max, process_data, birth_counts);
578 void ThreadData::SnapshotExecutedTasks(bool reset_max,
579 ProcessDataSnapshot* process_data,
580 BirthCountMap* birth_counts) {
581 // Get copy of data, so that the data will not change during the iterations
582 // and processing.
583 ThreadData::BirthMap birth_map;
584 ThreadData::DeathMap death_map;
585 ThreadData::ParentChildSet parent_child_set;
586 SnapshotMaps(reset_max, &birth_map, &death_map, &parent_child_set);
588 for (ThreadData::DeathMap::const_iterator it = death_map.begin();
589 it != death_map.end(); ++it) {
590 process_data->tasks.push_back(
591 TaskSnapshot(*it->first, it->second, thread_name()));
592 (*birth_counts)[it->first] -= it->first->birth_count();
595 for (ThreadData::BirthMap::const_iterator it = birth_map.begin();
596 it != birth_map.end(); ++it) {
597 (*birth_counts)[it->second] += it->second->birth_count();
600 if (!kTrackParentChildLinks)
601 return;
603 for (ThreadData::ParentChildSet::const_iterator it = parent_child_set.begin();
604 it != parent_child_set.end(); ++it) {
605 process_data->descendants.push_back(ParentChildPairSnapshot(*it));
609 // This may be called from another thread.
610 void ThreadData::SnapshotMaps(bool reset_max,
611 BirthMap* birth_map,
612 DeathMap* death_map,
613 ParentChildSet* parent_child_set) {
614 base::AutoLock lock(map_lock_);
615 for (BirthMap::const_iterator it = birth_map_.begin();
616 it != birth_map_.end(); ++it)
617 (*birth_map)[it->first] = it->second;
618 for (DeathMap::iterator it = death_map_.begin();
619 it != death_map_.end(); ++it) {
620 (*death_map)[it->first] = it->second;
621 if (reset_max)
622 it->second.ResetMax();
625 if (!kTrackParentChildLinks)
626 return;
628 for (ParentChildSet::iterator it = parent_child_set_.begin();
629 it != parent_child_set_.end(); ++it)
630 parent_child_set->insert(*it);
633 // static
634 void ThreadData::ResetAllThreadData() {
635 ThreadData* my_list = first();
637 for (ThreadData* thread_data = my_list;
638 thread_data;
639 thread_data = thread_data->next())
640 thread_data->Reset();
643 void ThreadData::Reset() {
644 base::AutoLock lock(map_lock_);
645 for (DeathMap::iterator it = death_map_.begin();
646 it != death_map_.end(); ++it)
647 it->second.Clear();
648 for (BirthMap::iterator it = birth_map_.begin();
649 it != birth_map_.end(); ++it)
650 it->second->Clear();
653 static void OptionallyInitializeAlternateTimer() {
654 NowFunction* alternate_time_source = GetAlternateTimeSource();
655 if (alternate_time_source)
656 ThreadData::SetAlternateTimeSource(alternate_time_source);
659 bool ThreadData::Initialize() {
660 if (!kTrackAllTaskObjects)
661 return false; // Not compiled in.
662 if (status_ >= DEACTIVATED)
663 return true; // Someone else did the initialization.
664 // Due to racy lazy initialization in tests, we'll need to recheck status_
665 // after we acquire the lock.
667 // Ensure that we don't double initialize tls. We are called when single
668 // threaded in the product, but some tests may be racy and lazy about our
669 // initialization.
670 base::AutoLock lock(*list_lock_.Pointer());
671 if (status_ >= DEACTIVATED)
672 return true; // Someone raced in here and beat us.
674 // Put an alternate timer in place if the environment calls for it, such as
675 // for tracking TCMalloc allocations. This insertion is idempotent, so we
676 // don't mind if there is a race, and we'd prefer not to be in a lock while
677 // doing this work.
678 if (kAllowAlternateTimeSourceHandling)
679 OptionallyInitializeAlternateTimer();
681 // Perform the "real" TLS initialization now, and leave it intact through
682 // process termination.
683 if (!tls_index_.initialized()) { // Testing may have initialized this.
684 DCHECK_EQ(status_, UNINITIALIZED);
685 tls_index_.Initialize(&ThreadData::OnThreadTermination);
686 if (!tls_index_.initialized())
687 return false;
688 } else {
689 // TLS was initialzed for us earlier.
690 DCHECK_EQ(status_, DORMANT_DURING_TESTS);
693 // Incarnation counter is only significant to testing, as it otherwise will
694 // never again change in this process.
695 ++incarnation_counter_;
697 // The lock is not critical for setting status_, but it doesn't hurt. It also
698 // ensures that if we have a racy initialization, that we'll bail as soon as
699 // we get the lock earlier in this method.
700 status_ = kInitialStartupState;
701 if (!kTrackParentChildLinks &&
702 kInitialStartupState == PROFILING_CHILDREN_ACTIVE)
703 status_ = PROFILING_ACTIVE;
704 DCHECK(status_ != UNINITIALIZED);
705 return true;
708 // static
709 bool ThreadData::InitializeAndSetTrackingStatus(Status status) {
710 DCHECK_GE(status, DEACTIVATED);
711 DCHECK_LE(status, PROFILING_CHILDREN_ACTIVE);
713 if (!Initialize()) // No-op if already initialized.
714 return false; // Not compiled in.
716 if (!kTrackParentChildLinks && status > DEACTIVATED)
717 status = PROFILING_ACTIVE;
718 status_ = status;
719 return true;
722 // static
723 ThreadData::Status ThreadData::status() {
724 return status_;
727 // static
728 bool ThreadData::TrackingStatus() {
729 return status_ > DEACTIVATED;
732 // static
733 bool ThreadData::TrackingParentChildStatus() {
734 return status_ >= PROFILING_CHILDREN_ACTIVE;
737 // static
738 TrackedTime ThreadData::NowForStartOfRun(const Births* parent) {
739 if (kTrackParentChildLinks && parent && status_ > PROFILING_ACTIVE) {
740 ThreadData* current_thread_data = Get();
741 if (current_thread_data)
742 current_thread_data->parent_stack_.push(parent);
744 return Now();
747 // static
748 TrackedTime ThreadData::NowForEndOfRun() {
749 return Now();
752 // static
753 void ThreadData::SetAlternateTimeSource(NowFunction* now_function) {
754 DCHECK(now_function);
755 if (kAllowAlternateTimeSourceHandling)
756 now_function_ = now_function;
759 // static
760 TrackedTime ThreadData::Now() {
761 if (kAllowAlternateTimeSourceHandling && now_function_)
762 return TrackedTime::FromMilliseconds((*now_function_)());
763 if (kTrackAllTaskObjects && TrackingStatus())
764 return TrackedTime::Now();
765 return TrackedTime(); // Super fast when disabled, or not compiled.
768 // static
769 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count) {
770 base::AutoLock lock(*list_lock_.Pointer());
771 if (worker_thread_data_creation_count_ == 0)
772 return; // We haven't really run much, and couldn't have leaked.
773 // Verify that we've at least shutdown/cleanup the major namesd threads. The
774 // caller should tell us how many thread shutdowns should have taken place by
775 // now.
776 return; // TODO(jar): until this is working on XP, don't run the real test.
777 CHECK_GT(cleanup_count_, major_threads_shutdown_count);
780 // static
781 void ThreadData::ShutdownSingleThreadedCleanup(bool leak) {
782 // This is only called from test code, where we need to cleanup so that
783 // additional tests can be run.
784 // We must be single threaded... but be careful anyway.
785 if (!InitializeAndSetTrackingStatus(DEACTIVATED))
786 return;
787 ThreadData* thread_data_list;
789 base::AutoLock lock(*list_lock_.Pointer());
790 thread_data_list = all_thread_data_list_head_;
791 all_thread_data_list_head_ = NULL;
792 ++incarnation_counter_;
793 // To be clean, break apart the retired worker list (though we leak them).
794 while (first_retired_worker_) {
795 ThreadData* worker = first_retired_worker_;
796 CHECK_GT(worker->worker_thread_number_, 0);
797 first_retired_worker_ = worker->next_retired_worker_;
798 worker->next_retired_worker_ = NULL;
802 // Put most global static back in pristine shape.
803 worker_thread_data_creation_count_ = 0;
804 cleanup_count_ = 0;
805 tls_index_.Set(NULL);
806 status_ = DORMANT_DURING_TESTS; // Almost UNINITIALIZED.
808 // To avoid any chance of racing in unit tests, which is the only place we
809 // call this function, we may sometimes leak all the data structures we
810 // recovered, as they may still be in use on threads from prior tests!
811 if (leak)
812 return;
814 // When we want to cleanup (on a single thread), here is what we do.
816 // Do actual recursive delete in all ThreadData instances.
817 while (thread_data_list) {
818 ThreadData* next_thread_data = thread_data_list;
819 thread_data_list = thread_data_list->next();
821 for (BirthMap::iterator it = next_thread_data->birth_map_.begin();
822 next_thread_data->birth_map_.end() != it; ++it)
823 delete it->second; // Delete the Birth Records.
824 delete next_thread_data; // Includes all Death Records.
828 //------------------------------------------------------------------------------
829 TaskSnapshot::TaskSnapshot() {
832 TaskSnapshot::TaskSnapshot(const BirthOnThread& birth,
833 const DeathData& death_data,
834 const std::string& death_thread_name)
835 : birth(birth),
836 death_data(death_data),
837 death_thread_name(death_thread_name) {
840 TaskSnapshot::~TaskSnapshot() {
843 //------------------------------------------------------------------------------
844 // ParentChildPairSnapshot
846 ParentChildPairSnapshot::ParentChildPairSnapshot() {
849 ParentChildPairSnapshot::ParentChildPairSnapshot(
850 const ThreadData::ParentChildPair& parent_child)
851 : parent(*parent_child.first),
852 child(*parent_child.second) {
855 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
858 //------------------------------------------------------------------------------
859 // ProcessDataSnapshot
861 ProcessDataSnapshot::ProcessDataSnapshot()
862 #if !defined(OS_NACL)
863 : process_id(base::GetCurrentProcId()) {
864 #else
865 : process_id(0) {
866 #endif
869 ProcessDataSnapshot::~ProcessDataSnapshot() {
872 } // namespace tracked_objects