Close data pipes when TCP network connection goes down.
[chromium-blink-merge.git] / base / tracked_objects.cc
blob5359d892116577750cacff82a8522322c0b0b04b
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 <limits.h>
8 #include <stdlib.h>
10 #include "base/atomicops.h"
11 #include "base/base_switches.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/debug/leak_annotations.h"
15 #include "base/logging.h"
16 #include "base/process/process_handle.h"
17 #include "base/profiler/alternate_timer.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/third_party/valgrind/memcheck.h"
20 #include "base/tracking_info.h"
22 using base::TimeDelta;
24 namespace base {
25 class TimeDelta;
28 namespace tracked_objects {
30 namespace {
31 // Flag to compile out almost all of the task tracking code.
32 const bool kTrackAllTaskObjects = true;
34 // TODO(jar): Evaluate the perf impact of enabling this. If the perf impact is
35 // negligible, enable by default.
36 // Flag to compile out parent-child link recording.
37 const bool kTrackParentChildLinks = false;
39 // When ThreadData is first initialized, should we start in an ACTIVE state to
40 // record all of the startup-time tasks, or should we start up DEACTIVATED, so
41 // that we only record after parsing the command line flag --enable-tracking.
42 // Note that the flag may force either state, so this really controls only the
43 // period of time up until that flag is parsed. If there is no flag seen, then
44 // this state may prevail for much or all of the process lifetime.
45 const ThreadData::Status kInitialStartupState =
46 ThreadData::PROFILING_CHILDREN_ACTIVE;
48 // Control whether an alternate time source (Now() function) is supported by
49 // the ThreadData class. This compile time flag should be set to true if we
50 // want other modules (such as a memory allocator, or a thread-specific CPU time
51 // clock) to be able to provide a thread-specific Now() function. Without this
52 // compile-time flag, the code will only support the wall-clock time. This flag
53 // can be flipped to efficiently disable this path (if there is a performance
54 // problem with its presence).
55 static const bool kAllowAlternateTimeSourceHandling = true;
57 // Possible states of the profiler timing enabledness.
58 enum {
59 UNDEFINED_TIMING,
60 ENABLED_TIMING,
61 DISABLED_TIMING,
64 // State of the profiler timing enabledness.
65 base::subtle::Atomic32 g_profiler_timing_enabled = UNDEFINED_TIMING;
67 // Returns whether profiler timing is enabled. The default is true, but this may
68 // be overridden by a command-line flag. Some platforms may programmatically set
69 // this command-line flag to the "off" value if it's not specified.
70 // This in turn can be overridden by explicitly calling
71 // ThreadData::EnableProfilerTiming, say, based on a field trial.
72 inline bool IsProfilerTimingEnabled() {
73 // Reading |g_profiler_timing_enabled| is done without barrier because
74 // multiple initialization is not an issue while the barrier can be relatively
75 // costly given that this method is sometimes called in a tight loop.
76 base::subtle::Atomic32 current_timing_enabled =
77 base::subtle::NoBarrier_Load(&g_profiler_timing_enabled);
78 if (current_timing_enabled == UNDEFINED_TIMING) {
79 if (!base::CommandLine::InitializedForCurrentProcess())
80 return true;
81 current_timing_enabled =
82 (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
83 switches::kProfilerTiming) ==
84 switches::kProfilerTimingDisabledValue)
85 ? DISABLED_TIMING
86 : ENABLED_TIMING;
87 base::subtle::NoBarrier_Store(&g_profiler_timing_enabled,
88 current_timing_enabled);
90 return current_timing_enabled == ENABLED_TIMING;
93 } // namespace
95 //------------------------------------------------------------------------------
96 // DeathData tallies durations when a death takes place.
98 DeathData::DeathData() {
99 Clear();
102 DeathData::DeathData(int count) {
103 Clear();
104 count_ = count;
107 // TODO(jar): I need to see if this macro to optimize branching is worth using.
109 // This macro has no branching, so it is surely fast, and is equivalent to:
110 // if (assign_it)
111 // target = source;
112 // We use a macro rather than a template to force this to inline.
113 // Related code for calculating max is discussed on the web.
114 #define CONDITIONAL_ASSIGN(assign_it, target, source) \
115 ((target) ^= ((target) ^ (source)) & -static_cast<int32>(assign_it))
117 void DeathData::RecordDeath(const int32 queue_duration,
118 const int32 run_duration,
119 const uint32 random_number) {
120 // We'll just clamp at INT_MAX, but we should note this in the UI as such.
121 if (count_ < INT_MAX)
122 ++count_;
123 queue_duration_sum_ += queue_duration;
124 run_duration_sum_ += run_duration;
126 if (queue_duration_max_ < queue_duration)
127 queue_duration_max_ = queue_duration;
128 if (run_duration_max_ < run_duration)
129 run_duration_max_ = run_duration;
131 // Take a uniformly distributed sample over all durations ever supplied.
132 // The probability that we (instead) use this new sample is 1/count_. This
133 // results in a completely uniform selection of the sample (at least when we
134 // don't clamp count_... but that should be inconsequentially likely).
135 // We ignore the fact that we correlated our selection of a sample to the run
136 // and queue times (i.e., we used them to generate random_number).
137 CHECK_GT(count_, 0);
138 if (0 == (random_number % count_)) {
139 queue_duration_sample_ = queue_duration;
140 run_duration_sample_ = run_duration;
144 int DeathData::count() const { return count_; }
146 int32 DeathData::run_duration_sum() const { return run_duration_sum_; }
148 int32 DeathData::run_duration_max() const { return run_duration_max_; }
150 int32 DeathData::run_duration_sample() const {
151 return run_duration_sample_;
154 int32 DeathData::queue_duration_sum() const {
155 return queue_duration_sum_;
158 int32 DeathData::queue_duration_max() const {
159 return queue_duration_max_;
162 int32 DeathData::queue_duration_sample() const {
163 return queue_duration_sample_;
166 void DeathData::Clear() {
167 count_ = 0;
168 run_duration_sum_ = 0;
169 run_duration_max_ = 0;
170 run_duration_sample_ = 0;
171 queue_duration_sum_ = 0;
172 queue_duration_max_ = 0;
173 queue_duration_sample_ = 0;
176 //------------------------------------------------------------------------------
177 DeathDataSnapshot::DeathDataSnapshot()
178 : count(-1),
179 run_duration_sum(-1),
180 run_duration_max(-1),
181 run_duration_sample(-1),
182 queue_duration_sum(-1),
183 queue_duration_max(-1),
184 queue_duration_sample(-1) {
187 DeathDataSnapshot::DeathDataSnapshot(
188 const tracked_objects::DeathData& death_data)
189 : count(death_data.count()),
190 run_duration_sum(death_data.run_duration_sum()),
191 run_duration_max(death_data.run_duration_max()),
192 run_duration_sample(death_data.run_duration_sample()),
193 queue_duration_sum(death_data.queue_duration_sum()),
194 queue_duration_max(death_data.queue_duration_max()),
195 queue_duration_sample(death_data.queue_duration_sample()) {
198 DeathDataSnapshot::~DeathDataSnapshot() {
201 //------------------------------------------------------------------------------
202 BirthOnThread::BirthOnThread(const Location& location,
203 const ThreadData& current)
204 : location_(location),
205 birth_thread_(&current) {
208 //------------------------------------------------------------------------------
209 BirthOnThreadSnapshot::BirthOnThreadSnapshot() {
212 BirthOnThreadSnapshot::BirthOnThreadSnapshot(
213 const tracked_objects::BirthOnThread& birth)
214 : location(birth.location()),
215 thread_name(birth.birth_thread()->thread_name()) {
218 BirthOnThreadSnapshot::~BirthOnThreadSnapshot() {
221 //------------------------------------------------------------------------------
222 Births::Births(const Location& location, const ThreadData& current)
223 : BirthOnThread(location, current),
224 birth_count_(1) { }
226 int Births::birth_count() const { return birth_count_; }
228 void Births::RecordBirth() { ++birth_count_; }
230 //------------------------------------------------------------------------------
231 // ThreadData maintains the central data for all births and deaths on a single
232 // thread.
234 // TODO(jar): We should pull all these static vars together, into a struct, and
235 // optimize layout so that we benefit from locality of reference during accesses
236 // to them.
238 // static
239 NowFunction* ThreadData::now_function_ = NULL;
241 // static
242 bool ThreadData::now_function_is_time_ = false;
244 // A TLS slot which points to the ThreadData instance for the current thread. We
245 // do a fake initialization here (zeroing out data), and then the real in-place
246 // construction happens when we call tls_index_.Initialize().
247 // static
248 base::ThreadLocalStorage::StaticSlot ThreadData::tls_index_ = TLS_INITIALIZER;
250 // static
251 int ThreadData::worker_thread_data_creation_count_ = 0;
253 // static
254 int ThreadData::cleanup_count_ = 0;
256 // static
257 int ThreadData::incarnation_counter_ = 0;
259 // static
260 ThreadData* ThreadData::all_thread_data_list_head_ = NULL;
262 // static
263 ThreadData* ThreadData::first_retired_worker_ = NULL;
265 // static
266 base::LazyInstance<base::Lock>::Leaky
267 ThreadData::list_lock_ = LAZY_INSTANCE_INITIALIZER;
269 // static
270 ThreadData::Status ThreadData::status_ = ThreadData::UNINITIALIZED;
272 ThreadData::ThreadData(const std::string& suggested_name)
273 : next_(NULL),
274 next_retired_worker_(NULL),
275 worker_thread_number_(0),
276 incarnation_count_for_pool_(-1),
277 current_stopwatch_(NULL) {
278 DCHECK_GE(suggested_name.size(), 0u);
279 thread_name_ = suggested_name;
280 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
283 ThreadData::ThreadData(int thread_number)
284 : next_(NULL),
285 next_retired_worker_(NULL),
286 worker_thread_number_(thread_number),
287 incarnation_count_for_pool_(-1),
288 current_stopwatch_(NULL) {
289 CHECK_GT(thread_number, 0);
290 base::StringAppendF(&thread_name_, "WorkerThread-%d", thread_number);
291 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
294 ThreadData::~ThreadData() {}
296 void ThreadData::PushToHeadOfList() {
297 // Toss in a hint of randomness (atop the uniniitalized value).
298 (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_,
299 sizeof(random_number_));
300 MSAN_UNPOISON(&random_number_, sizeof(random_number_));
301 random_number_ += static_cast<uint32>(this - static_cast<ThreadData*>(0));
302 random_number_ ^= (Now() - TrackedTime()).InMilliseconds();
304 DCHECK(!next_);
305 base::AutoLock lock(*list_lock_.Pointer());
306 incarnation_count_for_pool_ = incarnation_counter_;
307 next_ = all_thread_data_list_head_;
308 all_thread_data_list_head_ = this;
311 // static
312 ThreadData* ThreadData::first() {
313 base::AutoLock lock(*list_lock_.Pointer());
314 return all_thread_data_list_head_;
317 ThreadData* ThreadData::next() const { return next_; }
319 // static
320 void ThreadData::InitializeThreadContext(const std::string& suggested_name) {
321 if (!Initialize()) // Always initialize if needed.
322 return;
323 ThreadData* current_thread_data =
324 reinterpret_cast<ThreadData*>(tls_index_.Get());
325 if (current_thread_data)
326 return; // Browser tests instigate this.
327 current_thread_data = new ThreadData(suggested_name);
328 tls_index_.Set(current_thread_data);
331 // static
332 ThreadData* ThreadData::Get() {
333 if (!tls_index_.initialized())
334 return NULL; // For unittests only.
335 ThreadData* registered = reinterpret_cast<ThreadData*>(tls_index_.Get());
336 if (registered)
337 return registered;
339 // We must be a worker thread, since we didn't pre-register.
340 ThreadData* worker_thread_data = NULL;
341 int worker_thread_number = 0;
343 base::AutoLock lock(*list_lock_.Pointer());
344 if (first_retired_worker_) {
345 worker_thread_data = first_retired_worker_;
346 first_retired_worker_ = first_retired_worker_->next_retired_worker_;
347 worker_thread_data->next_retired_worker_ = NULL;
348 } else {
349 worker_thread_number = ++worker_thread_data_creation_count_;
353 // If we can't find a previously used instance, then we have to create one.
354 if (!worker_thread_data) {
355 DCHECK_GT(worker_thread_number, 0);
356 worker_thread_data = new ThreadData(worker_thread_number);
358 DCHECK_GT(worker_thread_data->worker_thread_number_, 0);
360 tls_index_.Set(worker_thread_data);
361 return worker_thread_data;
364 // static
365 void ThreadData::OnThreadTermination(void* thread_data) {
366 DCHECK(thread_data); // TLS should *never* call us with a NULL.
367 // We must NOT do any allocations during this callback. There is a chance
368 // that the allocator is no longer active on this thread.
369 if (!kTrackAllTaskObjects)
370 return; // Not compiled in.
371 reinterpret_cast<ThreadData*>(thread_data)->OnThreadTerminationCleanup();
374 void ThreadData::OnThreadTerminationCleanup() {
375 // The list_lock_ was created when we registered the callback, so it won't be
376 // allocated here despite the lazy reference.
377 base::AutoLock lock(*list_lock_.Pointer());
378 if (incarnation_counter_ != incarnation_count_for_pool_)
379 return; // ThreadData was constructed in an earlier unit test.
380 ++cleanup_count_;
381 // Only worker threads need to be retired and reused.
382 if (!worker_thread_number_) {
383 return;
385 // We must NOT do any allocations during this callback.
386 // Using the simple linked lists avoids all allocations.
387 DCHECK_EQ(this->next_retired_worker_, reinterpret_cast<ThreadData*>(NULL));
388 this->next_retired_worker_ = first_retired_worker_;
389 first_retired_worker_ = this;
392 // static
393 void ThreadData::Snapshot(ProcessDataSnapshot* process_data) {
394 // Add births that have run to completion to |collected_data|.
395 // |birth_counts| tracks the total number of births recorded at each location
396 // for which we have not seen a death count.
397 BirthCountMap birth_counts;
398 ThreadData::SnapshotAllExecutedTasks(process_data, &birth_counts);
400 // Add births that are still active -- i.e. objects that have tallied a birth,
401 // but have not yet tallied a matching death, and hence must be either
402 // running, queued up, or being held in limbo for future posting.
403 for (BirthCountMap::const_iterator it = birth_counts.begin();
404 it != birth_counts.end(); ++it) {
405 if (it->second > 0) {
406 process_data->tasks.push_back(
407 TaskSnapshot(*it->first, DeathData(it->second), "Still_Alive"));
412 Births* ThreadData::TallyABirth(const Location& location) {
413 BirthMap::iterator it = birth_map_.find(location);
414 Births* child;
415 if (it != birth_map_.end()) {
416 child = it->second;
417 child->RecordBirth();
418 } else {
419 child = new Births(location, *this); // Leak this.
420 // Lock since the map may get relocated now, and other threads sometimes
421 // snapshot it (but they lock before copying it).
422 base::AutoLock lock(map_lock_);
423 birth_map_[location] = child;
426 if (kTrackParentChildLinks && status_ > PROFILING_ACTIVE &&
427 !parent_stack_.empty()) {
428 const Births* parent = parent_stack_.top();
429 ParentChildPair pair(parent, child);
430 if (parent_child_set_.find(pair) == parent_child_set_.end()) {
431 // Lock since the map may get relocated now, and other threads sometimes
432 // snapshot it (but they lock before copying it).
433 base::AutoLock lock(map_lock_);
434 parent_child_set_.insert(pair);
438 return child;
441 void ThreadData::TallyADeath(const Births& birth,
442 int32 queue_duration,
443 const TaskStopwatch& stopwatch) {
444 int32 run_duration = stopwatch.RunDurationMs();
446 // Stir in some randomness, plus add constant in case durations are zero.
447 const uint32 kSomePrimeNumber = 2147483647;
448 random_number_ += queue_duration + run_duration + kSomePrimeNumber;
449 // An address is going to have some randomness to it as well ;-).
450 random_number_ ^= static_cast<uint32>(&birth - reinterpret_cast<Births*>(0));
452 // We don't have queue durations without OS timer. OS timer is automatically
453 // used for task-post-timing, so the use of an alternate timer implies all
454 // queue times are invalid, unless it was explicitly said that we can trust
455 // the alternate timer.
456 if (kAllowAlternateTimeSourceHandling &&
457 now_function_ &&
458 !now_function_is_time_) {
459 queue_duration = 0;
462 DeathMap::iterator it = death_map_.find(&birth);
463 DeathData* death_data;
464 if (it != death_map_.end()) {
465 death_data = &it->second;
466 } else {
467 base::AutoLock lock(map_lock_); // Lock as the map may get relocated now.
468 death_data = &death_map_[&birth];
469 } // Release lock ASAP.
470 death_data->RecordDeath(queue_duration, run_duration, random_number_);
472 if (!kTrackParentChildLinks)
473 return;
474 if (!parent_stack_.empty()) { // We might get turned off.
475 DCHECK_EQ(parent_stack_.top(), &birth);
476 parent_stack_.pop();
480 // static
481 Births* ThreadData::TallyABirthIfActive(const Location& location) {
482 if (!kTrackAllTaskObjects)
483 return NULL; // Not compiled in.
485 if (!TrackingStatus())
486 return NULL;
487 ThreadData* current_thread_data = Get();
488 if (!current_thread_data)
489 return NULL;
490 return current_thread_data->TallyABirth(location);
493 // static
494 void ThreadData::TallyRunOnNamedThreadIfTracking(
495 const base::TrackingInfo& completed_task,
496 const TaskStopwatch& stopwatch) {
497 if (!kTrackAllTaskObjects)
498 return; // Not compiled in.
500 // Even if we have been DEACTIVATED, we will process any pending births so
501 // that our data structures (which counted the outstanding births) remain
502 // consistent.
503 const Births* birth = completed_task.birth_tally;
504 if (!birth)
505 return;
506 ThreadData* current_thread_data = stopwatch.GetThreadData();
507 if (!current_thread_data)
508 return;
510 // Watch out for a race where status_ is changing, and hence one or both
511 // of start_of_run or end_of_run is zero. In that case, we didn't bother to
512 // get a time value since we "weren't tracking" and we were trying to be
513 // efficient by not calling for a genuine time value. For simplicity, we'll
514 // use a default zero duration when we can't calculate a true value.
515 TrackedTime start_of_run = stopwatch.StartTime();
516 int32 queue_duration = 0;
517 if (!start_of_run.is_null()) {
518 queue_duration = (start_of_run - completed_task.EffectiveTimePosted())
519 .InMilliseconds();
521 current_thread_data->TallyADeath(*birth, queue_duration, stopwatch);
524 // static
525 void ThreadData::TallyRunOnWorkerThreadIfTracking(
526 const Births* birth,
527 const TrackedTime& time_posted,
528 const TaskStopwatch& stopwatch) {
529 if (!kTrackAllTaskObjects)
530 return; // Not compiled in.
532 // Even if we have been DEACTIVATED, we will process any pending births so
533 // that our data structures (which counted the outstanding births) remain
534 // consistent.
535 if (!birth)
536 return;
538 // TODO(jar): Support the option to coalesce all worker-thread activity under
539 // one ThreadData instance that uses locks to protect *all* access. This will
540 // reduce memory (making it provably bounded), but run incrementally slower
541 // (since we'll use locks on TallyABirth and TallyADeath). The good news is
542 // that the locks on TallyADeath will be *after* the worker thread has run,
543 // and hence nothing will be waiting for the completion (... besides some
544 // other thread that might like to run). Also, the worker threads tasks are
545 // generally longer, and hence the cost of the lock may perchance be amortized
546 // over the long task's lifetime.
547 ThreadData* current_thread_data = stopwatch.GetThreadData();
548 if (!current_thread_data)
549 return;
551 TrackedTime start_of_run = stopwatch.StartTime();
552 int32 queue_duration = 0;
553 if (!start_of_run.is_null()) {
554 queue_duration = (start_of_run - time_posted).InMilliseconds();
556 current_thread_data->TallyADeath(*birth, queue_duration, stopwatch);
559 // static
560 void ThreadData::TallyRunInAScopedRegionIfTracking(
561 const Births* birth,
562 const TaskStopwatch& stopwatch) {
563 if (!kTrackAllTaskObjects)
564 return; // Not compiled in.
566 // Even if we have been DEACTIVATED, we will process any pending births so
567 // that our data structures (which counted the outstanding births) remain
568 // consistent.
569 if (!birth)
570 return;
572 ThreadData* current_thread_data = stopwatch.GetThreadData();
573 if (!current_thread_data)
574 return;
576 int32 queue_duration = 0;
577 current_thread_data->TallyADeath(*birth, queue_duration, stopwatch);
580 // static
581 void ThreadData::SnapshotAllExecutedTasks(ProcessDataSnapshot* process_data,
582 BirthCountMap* birth_counts) {
583 if (!kTrackAllTaskObjects)
584 return; // Not compiled in.
586 // Get an unchanging copy of a ThreadData list.
587 ThreadData* my_list = ThreadData::first();
589 // Gather data serially.
590 // This hackish approach *can* get some slighly corrupt tallies, as we are
591 // grabbing values without the protection of a lock, but it has the advantage
592 // of working even with threads that don't have message loops. If a user
593 // sees any strangeness, they can always just run their stats gathering a
594 // second time.
595 for (ThreadData* thread_data = my_list;
596 thread_data;
597 thread_data = thread_data->next()) {
598 thread_data->SnapshotExecutedTasks(process_data, birth_counts);
602 void ThreadData::SnapshotExecutedTasks(ProcessDataSnapshot* process_data,
603 BirthCountMap* birth_counts) {
604 // Get copy of data, so that the data will not change during the iterations
605 // and processing.
606 ThreadData::BirthMap birth_map;
607 ThreadData::DeathMap death_map;
608 ThreadData::ParentChildSet parent_child_set;
609 SnapshotMaps(&birth_map, &death_map, &parent_child_set);
611 for (ThreadData::DeathMap::const_iterator it = death_map.begin();
612 it != death_map.end(); ++it) {
613 process_data->tasks.push_back(
614 TaskSnapshot(*it->first, it->second, thread_name()));
615 (*birth_counts)[it->first] -= it->first->birth_count();
618 for (ThreadData::BirthMap::const_iterator it = birth_map.begin();
619 it != birth_map.end(); ++it) {
620 (*birth_counts)[it->second] += it->second->birth_count();
623 if (!kTrackParentChildLinks)
624 return;
626 for (ThreadData::ParentChildSet::const_iterator it = parent_child_set.begin();
627 it != parent_child_set.end(); ++it) {
628 process_data->descendants.push_back(ParentChildPairSnapshot(*it));
632 // This may be called from another thread.
633 void ThreadData::SnapshotMaps(BirthMap* birth_map,
634 DeathMap* death_map,
635 ParentChildSet* parent_child_set) {
636 base::AutoLock lock(map_lock_);
637 for (BirthMap::const_iterator it = birth_map_.begin();
638 it != birth_map_.end(); ++it)
639 (*birth_map)[it->first] = it->second;
640 for (DeathMap::iterator it = death_map_.begin();
641 it != death_map_.end(); ++it) {
642 (*death_map)[it->first] = it->second;
645 if (!kTrackParentChildLinks)
646 return;
648 for (ParentChildSet::iterator it = parent_child_set_.begin();
649 it != parent_child_set_.end(); ++it)
650 parent_child_set->insert(*it);
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 void ThreadData::PrepareForStartOfRun(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);
746 // static
747 void ThreadData::SetAlternateTimeSource(NowFunction* now_function) {
748 DCHECK(now_function);
749 if (kAllowAlternateTimeSourceHandling)
750 now_function_ = now_function;
753 // static
754 void ThreadData::EnableProfilerTiming() {
755 base::subtle::NoBarrier_Store(&g_profiler_timing_enabled, ENABLED_TIMING);
758 // static
759 TrackedTime ThreadData::Now() {
760 if (kAllowAlternateTimeSourceHandling && now_function_)
761 return TrackedTime::FromMilliseconds((*now_function_)());
762 if (kTrackAllTaskObjects && IsProfilerTimingEnabled() && TrackingStatus())
763 return TrackedTime::Now();
764 return TrackedTime(); // Super fast when disabled, or not compiled.
767 // static
768 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count) {
769 base::AutoLock lock(*list_lock_.Pointer());
770 if (worker_thread_data_creation_count_ == 0)
771 return; // We haven't really run much, and couldn't have leaked.
773 // TODO(jar): until this is working on XP, don't run the real test.
774 #if 0
775 // Verify that we've at least shutdown/cleanup the major namesd threads. The
776 // caller should tell us how many thread shutdowns should have taken place by
777 // now.
778 CHECK_GT(cleanup_count_, major_threads_shutdown_count);
779 #endif
782 // static
783 void ThreadData::ShutdownSingleThreadedCleanup(bool leak) {
784 // This is only called from test code, where we need to cleanup so that
785 // additional tests can be run.
786 // We must be single threaded... but be careful anyway.
787 if (!InitializeAndSetTrackingStatus(DEACTIVATED))
788 return;
789 ThreadData* thread_data_list;
791 base::AutoLock lock(*list_lock_.Pointer());
792 thread_data_list = all_thread_data_list_head_;
793 all_thread_data_list_head_ = NULL;
794 ++incarnation_counter_;
795 // To be clean, break apart the retired worker list (though we leak them).
796 while (first_retired_worker_) {
797 ThreadData* worker = first_retired_worker_;
798 CHECK_GT(worker->worker_thread_number_, 0);
799 first_retired_worker_ = worker->next_retired_worker_;
800 worker->next_retired_worker_ = NULL;
804 // Put most global static back in pristine shape.
805 worker_thread_data_creation_count_ = 0;
806 cleanup_count_ = 0;
807 tls_index_.Set(NULL);
808 status_ = DORMANT_DURING_TESTS; // Almost UNINITIALIZED.
810 // To avoid any chance of racing in unit tests, which is the only place we
811 // call this function, we may sometimes leak all the data structures we
812 // recovered, as they may still be in use on threads from prior tests!
813 if (leak) {
814 ThreadData* thread_data = thread_data_list;
815 while (thread_data) {
816 ANNOTATE_LEAKING_OBJECT_PTR(thread_data);
817 thread_data = thread_data->next();
819 return;
822 // When we want to cleanup (on a single thread), here is what we do.
824 // Do actual recursive delete in all ThreadData instances.
825 while (thread_data_list) {
826 ThreadData* next_thread_data = thread_data_list;
827 thread_data_list = thread_data_list->next();
829 for (BirthMap::iterator it = next_thread_data->birth_map_.begin();
830 next_thread_data->birth_map_.end() != it; ++it)
831 delete it->second; // Delete the Birth Records.
832 delete next_thread_data; // Includes all Death Records.
836 //------------------------------------------------------------------------------
837 TaskStopwatch::TaskStopwatch()
838 : wallclock_duration_ms_(0),
839 current_thread_data_(NULL),
840 excluded_duration_ms_(0),
841 parent_(NULL) {
842 #if DCHECK_IS_ON()
843 state_ = CREATED;
844 child_ = NULL;
845 #endif
848 TaskStopwatch::~TaskStopwatch() {
849 #if DCHECK_IS_ON()
850 DCHECK(state_ != RUNNING);
851 DCHECK(child_ == NULL);
852 #endif
855 void TaskStopwatch::Start() {
856 #if DCHECK_IS_ON()
857 DCHECK(state_ == CREATED);
858 state_ = RUNNING;
859 #endif
861 start_time_ = ThreadData::Now();
863 current_thread_data_ = ThreadData::Get();
864 if (!current_thread_data_)
865 return;
867 parent_ = current_thread_data_->current_stopwatch_;
868 #if DCHECK_IS_ON()
869 if (parent_) {
870 DCHECK(parent_->state_ == RUNNING);
871 DCHECK(parent_->child_ == NULL);
872 parent_->child_ = this;
874 #endif
875 current_thread_data_->current_stopwatch_ = this;
878 void TaskStopwatch::Stop() {
879 const TrackedTime end_time = ThreadData::Now();
880 #if DCHECK_IS_ON()
881 DCHECK(state_ == RUNNING);
882 state_ = STOPPED;
883 DCHECK(child_ == NULL);
884 #endif
886 if (!start_time_.is_null() && !end_time.is_null()) {
887 wallclock_duration_ms_ = (end_time - start_time_).InMilliseconds();
890 if (!current_thread_data_)
891 return;
893 DCHECK(current_thread_data_->current_stopwatch_ == this);
894 current_thread_data_->current_stopwatch_ = parent_;
895 if (!parent_)
896 return;
898 #if DCHECK_IS_ON()
899 DCHECK(parent_->state_ == RUNNING);
900 DCHECK(parent_->child_ == this);
901 parent_->child_ = NULL;
902 #endif
903 parent_->excluded_duration_ms_ += wallclock_duration_ms_;
904 parent_ = NULL;
907 TrackedTime TaskStopwatch::StartTime() const {
908 #if DCHECK_IS_ON()
909 DCHECK(state_ != CREATED);
910 #endif
912 return start_time_;
915 int32 TaskStopwatch::RunDurationMs() const {
916 #if DCHECK_IS_ON()
917 DCHECK(state_ == STOPPED);
918 #endif
920 return wallclock_duration_ms_ - excluded_duration_ms_;
923 ThreadData* TaskStopwatch::GetThreadData() const {
924 #if DCHECK_IS_ON()
925 DCHECK(state_ != CREATED);
926 #endif
928 return current_thread_data_;
931 //------------------------------------------------------------------------------
932 TaskSnapshot::TaskSnapshot() {
935 TaskSnapshot::TaskSnapshot(const BirthOnThread& birth,
936 const DeathData& death_data,
937 const std::string& death_thread_name)
938 : birth(birth),
939 death_data(death_data),
940 death_thread_name(death_thread_name) {
943 TaskSnapshot::~TaskSnapshot() {
946 //------------------------------------------------------------------------------
947 // ParentChildPairSnapshot
949 ParentChildPairSnapshot::ParentChildPairSnapshot() {
952 ParentChildPairSnapshot::ParentChildPairSnapshot(
953 const ThreadData::ParentChildPair& parent_child)
954 : parent(*parent_child.first),
955 child(*parent_child.second) {
958 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
961 //------------------------------------------------------------------------------
962 // ProcessDataSnapshot
964 ProcessDataSnapshot::ProcessDataSnapshot()
965 #if !defined(OS_NACL)
966 : process_id(base::GetCurrentProcId()) {
967 #else
968 : process_id(0) {
969 #endif
972 ProcessDataSnapshot::~ProcessDataSnapshot() {
975 } // namespace tracked_objects