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"
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
;
28 namespace tracked_objects
{
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.
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())
81 current_timing_enabled
=
82 (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
83 switches::kProfilerTiming
) ==
84 switches::kProfilerTimingDisabledValue
)
87 base::subtle::NoBarrier_Store(&g_profiler_timing_enabled
,
88 current_timing_enabled
);
90 return current_timing_enabled
== ENABLED_TIMING
;
95 //------------------------------------------------------------------------------
96 // DeathData tallies durations when a death takes place.
98 DeathData::DeathData() {
102 DeathData::DeathData(int 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:
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
)
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).
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() {
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()
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_(¤t
) {
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
),
226 int Births::birth_count() const { return birth_count_
; }
228 void Births::RecordBirth() { ++birth_count_
; }
230 void Births::ForgetBirth() { --birth_count_
; }
232 void Births::Clear() { birth_count_
= 0; }
234 //------------------------------------------------------------------------------
235 // ThreadData maintains the central data for all births and deaths on a single
238 // TODO(jar): We should pull all these static vars together, into a struct, and
239 // optimize layout so that we benefit from locality of reference during accesses
243 NowFunction
* ThreadData::now_function_
= NULL
;
246 bool ThreadData::now_function_is_time_
= false;
248 // A TLS slot which points to the ThreadData instance for the current thread. We
249 // do a fake initialization here (zeroing out data), and then the real in-place
250 // construction happens when we call tls_index_.Initialize().
252 base::ThreadLocalStorage::StaticSlot
ThreadData::tls_index_
= TLS_INITIALIZER
;
255 int ThreadData::worker_thread_data_creation_count_
= 0;
258 int ThreadData::cleanup_count_
= 0;
261 int ThreadData::incarnation_counter_
= 0;
264 ThreadData
* ThreadData::all_thread_data_list_head_
= NULL
;
267 ThreadData
* ThreadData::first_retired_worker_
= NULL
;
270 base::LazyInstance
<base::Lock
>::Leaky
271 ThreadData::list_lock_
= LAZY_INSTANCE_INITIALIZER
;
274 ThreadData::Status
ThreadData::status_
= ThreadData::UNINITIALIZED
;
276 ThreadData::ThreadData(const std::string
& suggested_name
)
278 next_retired_worker_(NULL
),
279 worker_thread_number_(0),
280 incarnation_count_for_pool_(-1),
281 current_stopwatch_(NULL
) {
282 DCHECK_GE(suggested_name
.size(), 0u);
283 thread_name_
= suggested_name
;
284 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
287 ThreadData::ThreadData(int thread_number
)
289 next_retired_worker_(NULL
),
290 worker_thread_number_(thread_number
),
291 incarnation_count_for_pool_(-1),
292 current_stopwatch_(NULL
) {
293 CHECK_GT(thread_number
, 0);
294 base::StringAppendF(&thread_name_
, "WorkerThread-%d", thread_number
);
295 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
298 ThreadData::~ThreadData() {}
300 void ThreadData::PushToHeadOfList() {
301 // Toss in a hint of randomness (atop the uniniitalized value).
302 (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_
,
303 sizeof(random_number_
));
304 MSAN_UNPOISON(&random_number_
, sizeof(random_number_
));
305 random_number_
+= static_cast<uint32
>(this - static_cast<ThreadData
*>(0));
306 random_number_
^= (Now() - TrackedTime()).InMilliseconds();
309 base::AutoLock
lock(*list_lock_
.Pointer());
310 incarnation_count_for_pool_
= incarnation_counter_
;
311 next_
= all_thread_data_list_head_
;
312 all_thread_data_list_head_
= this;
316 ThreadData
* ThreadData::first() {
317 base::AutoLock
lock(*list_lock_
.Pointer());
318 return all_thread_data_list_head_
;
321 ThreadData
* ThreadData::next() const { return next_
; }
324 void ThreadData::InitializeThreadContext(const std::string
& suggested_name
) {
325 if (!Initialize()) // Always initialize if needed.
327 ThreadData
* current_thread_data
=
328 reinterpret_cast<ThreadData
*>(tls_index_
.Get());
329 if (current_thread_data
)
330 return; // Browser tests instigate this.
331 current_thread_data
= new ThreadData(suggested_name
);
332 tls_index_
.Set(current_thread_data
);
336 ThreadData
* ThreadData::Get() {
337 if (!tls_index_
.initialized())
338 return NULL
; // For unittests only.
339 ThreadData
* registered
= reinterpret_cast<ThreadData
*>(tls_index_
.Get());
343 // We must be a worker thread, since we didn't pre-register.
344 ThreadData
* worker_thread_data
= NULL
;
345 int worker_thread_number
= 0;
347 base::AutoLock
lock(*list_lock_
.Pointer());
348 if (first_retired_worker_
) {
349 worker_thread_data
= first_retired_worker_
;
350 first_retired_worker_
= first_retired_worker_
->next_retired_worker_
;
351 worker_thread_data
->next_retired_worker_
= NULL
;
353 worker_thread_number
= ++worker_thread_data_creation_count_
;
357 // If we can't find a previously used instance, then we have to create one.
358 if (!worker_thread_data
) {
359 DCHECK_GT(worker_thread_number
, 0);
360 worker_thread_data
= new ThreadData(worker_thread_number
);
362 DCHECK_GT(worker_thread_data
->worker_thread_number_
, 0);
364 tls_index_
.Set(worker_thread_data
);
365 return worker_thread_data
;
369 void ThreadData::OnThreadTermination(void* thread_data
) {
370 DCHECK(thread_data
); // TLS should *never* call us with a NULL.
371 // We must NOT do any allocations during this callback. There is a chance
372 // that the allocator is no longer active on this thread.
373 if (!kTrackAllTaskObjects
)
374 return; // Not compiled in.
375 reinterpret_cast<ThreadData
*>(thread_data
)->OnThreadTerminationCleanup();
378 void ThreadData::OnThreadTerminationCleanup() {
379 // The list_lock_ was created when we registered the callback, so it won't be
380 // allocated here despite the lazy reference.
381 base::AutoLock
lock(*list_lock_
.Pointer());
382 if (incarnation_counter_
!= incarnation_count_for_pool_
)
383 return; // ThreadData was constructed in an earlier unit test.
385 // Only worker threads need to be retired and reused.
386 if (!worker_thread_number_
) {
389 // We must NOT do any allocations during this callback.
390 // Using the simple linked lists avoids all allocations.
391 DCHECK_EQ(this->next_retired_worker_
, reinterpret_cast<ThreadData
*>(NULL
));
392 this->next_retired_worker_
= first_retired_worker_
;
393 first_retired_worker_
= this;
397 void ThreadData::Snapshot(ProcessDataSnapshot
* process_data
) {
398 // Add births that have run to completion to |collected_data|.
399 // |birth_counts| tracks the total number of births recorded at each location
400 // for which we have not seen a death count.
401 BirthCountMap birth_counts
;
402 ThreadData::SnapshotAllExecutedTasks(process_data
, &birth_counts
);
404 // Add births that are still active -- i.e. objects that have tallied a birth,
405 // but have not yet tallied a matching death, and hence must be either
406 // running, queued up, or being held in limbo for future posting.
407 for (BirthCountMap::const_iterator it
= birth_counts
.begin();
408 it
!= birth_counts
.end(); ++it
) {
409 if (it
->second
> 0) {
410 process_data
->tasks
.push_back(
411 TaskSnapshot(*it
->first
, DeathData(it
->second
), "Still_Alive"));
416 Births
* ThreadData::TallyABirth(const Location
& location
) {
417 BirthMap::iterator it
= birth_map_
.find(location
);
419 if (it
!= birth_map_
.end()) {
421 child
->RecordBirth();
423 child
= new Births(location
, *this); // Leak this.
424 // Lock since the map may get relocated now, and other threads sometimes
425 // snapshot it (but they lock before copying it).
426 base::AutoLock
lock(map_lock_
);
427 birth_map_
[location
] = child
;
430 if (kTrackParentChildLinks
&& status_
> PROFILING_ACTIVE
&&
431 !parent_stack_
.empty()) {
432 const Births
* parent
= parent_stack_
.top();
433 ParentChildPair
pair(parent
, child
);
434 if (parent_child_set_
.find(pair
) == parent_child_set_
.end()) {
435 // Lock since the map may get relocated now, and other threads sometimes
436 // snapshot it (but they lock before copying it).
437 base::AutoLock
lock(map_lock_
);
438 parent_child_set_
.insert(pair
);
445 void ThreadData::TallyADeath(const Births
& birth
,
446 int32 queue_duration
,
447 const TaskStopwatch
& stopwatch
) {
448 int32 run_duration
= stopwatch
.RunDurationMs();
450 // Stir in some randomness, plus add constant in case durations are zero.
451 const uint32 kSomePrimeNumber
= 2147483647;
452 random_number_
+= queue_duration
+ run_duration
+ kSomePrimeNumber
;
453 // An address is going to have some randomness to it as well ;-).
454 random_number_
^= static_cast<uint32
>(&birth
- reinterpret_cast<Births
*>(0));
456 // We don't have queue durations without OS timer. OS timer is automatically
457 // used for task-post-timing, so the use of an alternate timer implies all
458 // queue times are invalid, unless it was explicitly said that we can trust
459 // the alternate timer.
460 if (kAllowAlternateTimeSourceHandling
&&
462 !now_function_is_time_
) {
466 DeathMap::iterator it
= death_map_
.find(&birth
);
467 DeathData
* death_data
;
468 if (it
!= death_map_
.end()) {
469 death_data
= &it
->second
;
471 base::AutoLock
lock(map_lock_
); // Lock as the map may get relocated now.
472 death_data
= &death_map_
[&birth
];
473 } // Release lock ASAP.
474 death_data
->RecordDeath(queue_duration
, run_duration
, random_number_
);
476 if (!kTrackParentChildLinks
)
478 if (!parent_stack_
.empty()) { // We might get turned off.
479 DCHECK_EQ(parent_stack_
.top(), &birth
);
485 Births
* ThreadData::TallyABirthIfActive(const Location
& location
) {
486 if (!kTrackAllTaskObjects
)
487 return NULL
; // Not compiled in.
489 if (!TrackingStatus())
491 ThreadData
* current_thread_data
= Get();
492 if (!current_thread_data
)
494 return current_thread_data
->TallyABirth(location
);
498 void ThreadData::TallyRunOnNamedThreadIfTracking(
499 const base::TrackingInfo
& completed_task
,
500 const TaskStopwatch
& stopwatch
) {
501 if (!kTrackAllTaskObjects
)
502 return; // Not compiled in.
504 // Even if we have been DEACTIVATED, we will process any pending births so
505 // that our data structures (which counted the outstanding births) remain
507 const Births
* birth
= completed_task
.birth_tally
;
510 ThreadData
* current_thread_data
= stopwatch
.GetThreadData();
511 if (!current_thread_data
)
514 // Watch out for a race where status_ is changing, and hence one or both
515 // of start_of_run or end_of_run is zero. In that case, we didn't bother to
516 // get a time value since we "weren't tracking" and we were trying to be
517 // efficient by not calling for a genuine time value. For simplicity, we'll
518 // use a default zero duration when we can't calculate a true value.
519 TrackedTime start_of_run
= stopwatch
.StartTime();
520 int32 queue_duration
= 0;
521 if (!start_of_run
.is_null()) {
522 queue_duration
= (start_of_run
- completed_task
.EffectiveTimePosted())
525 current_thread_data
->TallyADeath(*birth
, queue_duration
, stopwatch
);
529 void ThreadData::TallyRunOnWorkerThreadIfTracking(
531 const TrackedTime
& time_posted
,
532 const TaskStopwatch
& stopwatch
) {
533 if (!kTrackAllTaskObjects
)
534 return; // Not compiled in.
536 // Even if we have been DEACTIVATED, we will process any pending births so
537 // that our data structures (which counted the outstanding births) remain
542 // TODO(jar): Support the option to coalesce all worker-thread activity under
543 // one ThreadData instance that uses locks to protect *all* access. This will
544 // reduce memory (making it provably bounded), but run incrementally slower
545 // (since we'll use locks on TallyABirth and TallyADeath). The good news is
546 // that the locks on TallyADeath will be *after* the worker thread has run,
547 // and hence nothing will be waiting for the completion (... besides some
548 // other thread that might like to run). Also, the worker threads tasks are
549 // generally longer, and hence the cost of the lock may perchance be amortized
550 // over the long task's lifetime.
551 ThreadData
* current_thread_data
= stopwatch
.GetThreadData();
552 if (!current_thread_data
)
555 TrackedTime start_of_run
= stopwatch
.StartTime();
556 int32 queue_duration
= 0;
557 if (!start_of_run
.is_null()) {
558 queue_duration
= (start_of_run
- time_posted
).InMilliseconds();
560 current_thread_data
->TallyADeath(*birth
, queue_duration
, stopwatch
);
564 void ThreadData::TallyRunInAScopedRegionIfTracking(
566 const TaskStopwatch
& stopwatch
) {
567 if (!kTrackAllTaskObjects
)
568 return; // Not compiled in.
570 // Even if we have been DEACTIVATED, we will process any pending births so
571 // that our data structures (which counted the outstanding births) remain
576 ThreadData
* current_thread_data
= stopwatch
.GetThreadData();
577 if (!current_thread_data
)
580 int32 queue_duration
= 0;
581 current_thread_data
->TallyADeath(*birth
, queue_duration
, stopwatch
);
585 void ThreadData::SnapshotAllExecutedTasks(ProcessDataSnapshot
* process_data
,
586 BirthCountMap
* birth_counts
) {
587 if (!kTrackAllTaskObjects
)
588 return; // Not compiled in.
590 // Get an unchanging copy of a ThreadData list.
591 ThreadData
* my_list
= ThreadData::first();
593 // Gather data serially.
594 // This hackish approach *can* get some slighly corrupt tallies, as we are
595 // grabbing values without the protection of a lock, but it has the advantage
596 // of working even with threads that don't have message loops. If a user
597 // sees any strangeness, they can always just run their stats gathering a
599 for (ThreadData
* thread_data
= my_list
;
601 thread_data
= thread_data
->next()) {
602 thread_data
->SnapshotExecutedTasks(process_data
, birth_counts
);
606 void ThreadData::SnapshotExecutedTasks(ProcessDataSnapshot
* process_data
,
607 BirthCountMap
* birth_counts
) {
608 // Get copy of data, so that the data will not change during the iterations
610 ThreadData::BirthMap birth_map
;
611 ThreadData::DeathMap death_map
;
612 ThreadData::ParentChildSet parent_child_set
;
613 SnapshotMaps(&birth_map
, &death_map
, &parent_child_set
);
615 for (ThreadData::DeathMap::const_iterator it
= death_map
.begin();
616 it
!= death_map
.end(); ++it
) {
617 process_data
->tasks
.push_back(
618 TaskSnapshot(*it
->first
, it
->second
, thread_name()));
619 (*birth_counts
)[it
->first
] -= it
->first
->birth_count();
622 for (ThreadData::BirthMap::const_iterator it
= birth_map
.begin();
623 it
!= birth_map
.end(); ++it
) {
624 (*birth_counts
)[it
->second
] += it
->second
->birth_count();
627 if (!kTrackParentChildLinks
)
630 for (ThreadData::ParentChildSet::const_iterator it
= parent_child_set
.begin();
631 it
!= parent_child_set
.end(); ++it
) {
632 process_data
->descendants
.push_back(ParentChildPairSnapshot(*it
));
636 // This may be called from another thread.
637 void ThreadData::SnapshotMaps(BirthMap
* birth_map
,
639 ParentChildSet
* parent_child_set
) {
640 base::AutoLock
lock(map_lock_
);
641 for (BirthMap::const_iterator it
= birth_map_
.begin();
642 it
!= birth_map_
.end(); ++it
)
643 (*birth_map
)[it
->first
] = it
->second
;
644 for (DeathMap::iterator it
= death_map_
.begin();
645 it
!= death_map_
.end(); ++it
) {
646 (*death_map
)[it
->first
] = it
->second
;
649 if (!kTrackParentChildLinks
)
652 for (ParentChildSet::iterator it
= parent_child_set_
.begin();
653 it
!= parent_child_set_
.end(); ++it
)
654 parent_child_set
->insert(*it
);
658 void ThreadData::ResetAllThreadData() {
659 ThreadData
* my_list
= first();
661 for (ThreadData
* thread_data
= my_list
;
663 thread_data
= thread_data
->next())
664 thread_data
->Reset();
667 void ThreadData::Reset() {
668 base::AutoLock
lock(map_lock_
);
669 for (DeathMap::iterator it
= death_map_
.begin();
670 it
!= death_map_
.end(); ++it
)
672 for (BirthMap::iterator it
= birth_map_
.begin();
673 it
!= birth_map_
.end(); ++it
)
677 static void OptionallyInitializeAlternateTimer() {
678 NowFunction
* alternate_time_source
= GetAlternateTimeSource();
679 if (alternate_time_source
)
680 ThreadData::SetAlternateTimeSource(alternate_time_source
);
683 bool ThreadData::Initialize() {
684 if (!kTrackAllTaskObjects
)
685 return false; // Not compiled in.
686 if (status_
>= DEACTIVATED
)
687 return true; // Someone else did the initialization.
688 // Due to racy lazy initialization in tests, we'll need to recheck status_
689 // after we acquire the lock.
691 // Ensure that we don't double initialize tls. We are called when single
692 // threaded in the product, but some tests may be racy and lazy about our
694 base::AutoLock
lock(*list_lock_
.Pointer());
695 if (status_
>= DEACTIVATED
)
696 return true; // Someone raced in here and beat us.
698 // Put an alternate timer in place if the environment calls for it, such as
699 // for tracking TCMalloc allocations. This insertion is idempotent, so we
700 // don't mind if there is a race, and we'd prefer not to be in a lock while
702 if (kAllowAlternateTimeSourceHandling
)
703 OptionallyInitializeAlternateTimer();
705 // Perform the "real" TLS initialization now, and leave it intact through
706 // process termination.
707 if (!tls_index_
.initialized()) { // Testing may have initialized this.
708 DCHECK_EQ(status_
, UNINITIALIZED
);
709 tls_index_
.Initialize(&ThreadData::OnThreadTermination
);
710 if (!tls_index_
.initialized())
713 // TLS was initialzed for us earlier.
714 DCHECK_EQ(status_
, DORMANT_DURING_TESTS
);
717 // Incarnation counter is only significant to testing, as it otherwise will
718 // never again change in this process.
719 ++incarnation_counter_
;
721 // The lock is not critical for setting status_, but it doesn't hurt. It also
722 // ensures that if we have a racy initialization, that we'll bail as soon as
723 // we get the lock earlier in this method.
724 status_
= kInitialStartupState
;
725 if (!kTrackParentChildLinks
&&
726 kInitialStartupState
== PROFILING_CHILDREN_ACTIVE
)
727 status_
= PROFILING_ACTIVE
;
728 DCHECK(status_
!= UNINITIALIZED
);
733 bool ThreadData::InitializeAndSetTrackingStatus(Status status
) {
734 DCHECK_GE(status
, DEACTIVATED
);
735 DCHECK_LE(status
, PROFILING_CHILDREN_ACTIVE
);
737 if (!Initialize()) // No-op if already initialized.
738 return false; // Not compiled in.
740 if (!kTrackParentChildLinks
&& status
> DEACTIVATED
)
741 status
= PROFILING_ACTIVE
;
747 ThreadData::Status
ThreadData::status() {
752 bool ThreadData::TrackingStatus() {
753 return status_
> DEACTIVATED
;
757 bool ThreadData::TrackingParentChildStatus() {
758 return status_
>= PROFILING_CHILDREN_ACTIVE
;
762 void ThreadData::PrepareForStartOfRun(const Births
* parent
) {
763 if (kTrackParentChildLinks
&& parent
&& status_
> PROFILING_ACTIVE
) {
764 ThreadData
* current_thread_data
= Get();
765 if (current_thread_data
)
766 current_thread_data
->parent_stack_
.push(parent
);
771 void ThreadData::SetAlternateTimeSource(NowFunction
* now_function
) {
772 DCHECK(now_function
);
773 if (kAllowAlternateTimeSourceHandling
)
774 now_function_
= now_function
;
778 void ThreadData::EnableProfilerTiming() {
779 base::subtle::NoBarrier_Store(&g_profiler_timing_enabled
, ENABLED_TIMING
);
783 TrackedTime
ThreadData::Now() {
784 if (kAllowAlternateTimeSourceHandling
&& now_function_
)
785 return TrackedTime::FromMilliseconds((*now_function_
)());
786 if (kTrackAllTaskObjects
&& IsProfilerTimingEnabled() && TrackingStatus())
787 return TrackedTime::Now();
788 return TrackedTime(); // Super fast when disabled, or not compiled.
792 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count
) {
793 base::AutoLock
lock(*list_lock_
.Pointer());
794 if (worker_thread_data_creation_count_
== 0)
795 return; // We haven't really run much, and couldn't have leaked.
797 // TODO(jar): until this is working on XP, don't run the real test.
799 // Verify that we've at least shutdown/cleanup the major namesd threads. The
800 // caller should tell us how many thread shutdowns should have taken place by
802 CHECK_GT(cleanup_count_
, major_threads_shutdown_count
);
807 void ThreadData::ShutdownSingleThreadedCleanup(bool leak
) {
808 // This is only called from test code, where we need to cleanup so that
809 // additional tests can be run.
810 // We must be single threaded... but be careful anyway.
811 if (!InitializeAndSetTrackingStatus(DEACTIVATED
))
813 ThreadData
* thread_data_list
;
815 base::AutoLock
lock(*list_lock_
.Pointer());
816 thread_data_list
= all_thread_data_list_head_
;
817 all_thread_data_list_head_
= NULL
;
818 ++incarnation_counter_
;
819 // To be clean, break apart the retired worker list (though we leak them).
820 while (first_retired_worker_
) {
821 ThreadData
* worker
= first_retired_worker_
;
822 CHECK_GT(worker
->worker_thread_number_
, 0);
823 first_retired_worker_
= worker
->next_retired_worker_
;
824 worker
->next_retired_worker_
= NULL
;
828 // Put most global static back in pristine shape.
829 worker_thread_data_creation_count_
= 0;
831 tls_index_
.Set(NULL
);
832 status_
= DORMANT_DURING_TESTS
; // Almost UNINITIALIZED.
834 // To avoid any chance of racing in unit tests, which is the only place we
835 // call this function, we may sometimes leak all the data structures we
836 // recovered, as they may still be in use on threads from prior tests!
838 ThreadData
* thread_data
= thread_data_list
;
839 while (thread_data
) {
840 ANNOTATE_LEAKING_OBJECT_PTR(thread_data
);
841 thread_data
= thread_data
->next();
846 // When we want to cleanup (on a single thread), here is what we do.
848 // Do actual recursive delete in all ThreadData instances.
849 while (thread_data_list
) {
850 ThreadData
* next_thread_data
= thread_data_list
;
851 thread_data_list
= thread_data_list
->next();
853 for (BirthMap::iterator it
= next_thread_data
->birth_map_
.begin();
854 next_thread_data
->birth_map_
.end() != it
; ++it
)
855 delete it
->second
; // Delete the Birth Records.
856 delete next_thread_data
; // Includes all Death Records.
860 //------------------------------------------------------------------------------
861 TaskStopwatch::TaskStopwatch()
862 : wallclock_duration_ms_(0),
863 current_thread_data_(NULL
),
864 excluded_duration_ms_(0),
872 TaskStopwatch::~TaskStopwatch() {
874 DCHECK(state_
!= RUNNING
);
875 DCHECK(child_
== NULL
);
879 void TaskStopwatch::Start() {
881 DCHECK(state_
== CREATED
);
885 start_time_
= ThreadData::Now();
887 current_thread_data_
= ThreadData::Get();
888 if (!current_thread_data_
)
891 parent_
= current_thread_data_
->current_stopwatch_
;
894 DCHECK(parent_
->state_
== RUNNING
);
895 DCHECK(parent_
->child_
== NULL
);
896 parent_
->child_
= this;
899 current_thread_data_
->current_stopwatch_
= this;
902 void TaskStopwatch::Stop() {
903 const TrackedTime end_time
= ThreadData::Now();
905 DCHECK(state_
== RUNNING
);
907 DCHECK(child_
== NULL
);
910 if (!start_time_
.is_null() && !end_time
.is_null()) {
911 wallclock_duration_ms_
= (end_time
- start_time_
).InMilliseconds();
914 if (!current_thread_data_
)
917 DCHECK(current_thread_data_
->current_stopwatch_
== this);
918 current_thread_data_
->current_stopwatch_
= parent_
;
923 DCHECK(parent_
->state_
== RUNNING
);
924 DCHECK(parent_
->child_
== this);
925 parent_
->child_
= NULL
;
927 parent_
->excluded_duration_ms_
+= wallclock_duration_ms_
;
931 TrackedTime
TaskStopwatch::StartTime() const {
933 DCHECK(state_
!= CREATED
);
939 int32
TaskStopwatch::RunDurationMs() const {
941 DCHECK(state_
== STOPPED
);
944 return wallclock_duration_ms_
- excluded_duration_ms_
;
947 ThreadData
* TaskStopwatch::GetThreadData() const {
949 DCHECK(state_
!= CREATED
);
952 return current_thread_data_
;
955 //------------------------------------------------------------------------------
956 TaskSnapshot::TaskSnapshot() {
959 TaskSnapshot::TaskSnapshot(const BirthOnThread
& birth
,
960 const DeathData
& death_data
,
961 const std::string
& death_thread_name
)
963 death_data(death_data
),
964 death_thread_name(death_thread_name
) {
967 TaskSnapshot::~TaskSnapshot() {
970 //------------------------------------------------------------------------------
971 // ParentChildPairSnapshot
973 ParentChildPairSnapshot::ParentChildPairSnapshot() {
976 ParentChildPairSnapshot::ParentChildPairSnapshot(
977 const ThreadData::ParentChildPair
& parent_child
)
978 : parent(*parent_child
.first
),
979 child(*parent_child
.second
) {
982 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
985 //------------------------------------------------------------------------------
986 // ProcessDataSnapshot
988 ProcessDataSnapshot::ProcessDataSnapshot()
989 #if !defined(OS_NACL)
990 : process_id(base::GetCurrentProcId()) {
996 ProcessDataSnapshot::~ProcessDataSnapshot() {
999 } // namespace tracked_objects