blob: eb38df6b8d675d372bb9bce4803d99fed825e856 [file] [log] [blame]
[email protected]9fc44162012-01-23 22:56:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
5#ifndef BASE_TRACKED_OBJECTS_H_
6#define BASE_TRACKED_OBJECTS_H_
7
initial.commitd7cae122008-07-26 21:49:388#include <map>
[email protected]8aa1e6e2011-12-14 01:36:489#include <set>
[email protected]84baeca2011-10-24 18:55:1610#include <stack>
initial.commitd7cae122008-07-26 21:49:3811#include <string>
[email protected]8aa1e6e2011-12-14 01:36:4812#include <utility>
initial.commitd7cae122008-07-26 21:49:3813#include <vector>
14
[email protected]0bea7252011-08-05 15:34:0015#include "base/base_export.h"
[email protected]c014f2b32013-09-03 23:29:1216#include "base/basictypes.h"
[email protected]b6b2b892011-12-04 07:19:1017#include "base/gtest_prod_util.h"
[email protected]77169a62011-11-14 20:36:4618#include "base/lazy_instance.h"
[email protected]c62dd9d2011-09-21 18:05:4119#include "base/location.h"
[email protected]90895d0f2012-02-15 23:05:0120#include "base/profiler/alternate_timer.h"
[email protected]dbe5d2072011-11-08 17:09:2121#include "base/profiler/tracked_time.h"
[email protected]20305ec2011-01-21 04:55:5222#include "base/synchronization/lock.h"
[email protected]1357c322010-12-30 22:18:5623#include "base/threading/thread_local_storage.h"
[email protected]c014f2b32013-09-03 23:29:1224
25namespace base {
26struct TrackingInfo;
27}
initial.commitd7cae122008-07-26 21:49:3828
[email protected]75b79202009-12-30 07:31:4529// TrackedObjects provides a database of stats about objects (generally Tasks)
30// that are tracked. Tracking means their birth, death, duration, birth thread,
31// death thread, and birth place are recorded. This data is carefully spread
32// across a series of objects so that the counts and times can be rapidly
33// updated without (usually) having to lock the data, and hence there is usually
34// very little contention caused by the tracking. The data can be viewed via
[email protected]dda97682011-11-14 05:24:0735// the about:profiler URL, with a variety of sorting and filtering choices.
[email protected]75b79202009-12-30 07:31:4536//
[email protected]ea319e42010-11-08 21:47:2437// These classes serve as the basis of a profiler of sorts for the Tasks system.
38// As a result, design decisions were made to maximize speed, by minimizing
39// recurring allocation/deallocation, lock contention and data copying. In the
40// "stable" state, which is reached relatively quickly, there is no separate
41// marginal allocation cost associated with construction or destruction of
42// tracked objects, no locks are generally employed, and probably the largest
43// computational cost is associated with obtaining start and stop times for
[email protected]84b57952011-10-15 23:52:4544// instances as they are created and destroyed.
[email protected]75b79202009-12-30 07:31:4545//
mithro5eb58502014-11-19 18:55:5846// The following describes the life cycle of tracking an instance.
[email protected]75b79202009-12-30 07:31:4547//
48// First off, when the instance is created, the FROM_HERE macro is expanded
49// to specify the birth place (file, line, function) where the instance was
50// created. That data is used to create a transient Location instance
51// encapsulating the above triple of information. The strings (like __FILE__)
52// are passed around by reference, with the assumption that they are static, and
53// will never go away. This ensures that the strings can be dealt with as atoms
54// with great efficiency (i.e., copying of strings is never needed, and
55// comparisons for equality can be based on pointer comparisons).
56//
57// Next, a Births instance is created for use ONLY on the thread where this
58// instance was created. That Births instance records (in a base class
59// BirthOnThread) references to the static data provided in a Location instance,
60// as well as a pointer specifying the thread on which the birth takes place.
61// Hence there is at most one Births instance for each Location on each thread.
62// The derived Births class contains slots for recording statistics about all
63// instances born at the same location. Statistics currently include only the
64// count of instances constructed.
[email protected]84b57952011-10-15 23:52:4565//
[email protected]75b79202009-12-30 07:31:4566// Since the base class BirthOnThread contains only constant data, it can be
67// freely accessed by any thread at any time (i.e., only the statistic needs to
[email protected]84b57952011-10-15 23:52:4568// be handled carefully, and stats are updated exclusively on the birth thread).
[email protected]75b79202009-12-30 07:31:4569//
[email protected]c62dd9d2011-09-21 18:05:4170// For Tasks, having now either constructed or found the Births instance
71// described above, a pointer to the Births instance is then recorded into the
72// PendingTask structure in MessageLoop. This fact alone is very useful in
[email protected]75b79202009-12-30 07:31:4573// debugging, when there is a question of where an instance came from. In
[email protected]c62dd9d2011-09-21 18:05:4174// addition, the birth time is also recorded and used to later evaluate the
75// lifetime duration of the whole Task. As a result of the above embedding, we
76// can find out a Task's location of birth, and thread of birth, without using
77// any locks, as all that data is constant across the life of the process.
78//
[email protected]84b57952011-10-15 23:52:4579// The above work *could* also be done for any other object as well by calling
[email protected]b2a9bbd2011-10-31 22:36:2180// TallyABirthIfActive() and TallyRunOnNamedThreadIfTracking() as appropriate.
[email protected]75b79202009-12-30 07:31:4581//
82// The amount of memory used in the above data structures depends on how many
83// threads there are, and how many Locations of construction there are.
84// Fortunately, we don't use memory that is the product of those two counts, but
85// rather we only need one Births instance for each thread that constructs an
[email protected]c62dd9d2011-09-21 18:05:4186// instance at a Location. In many cases, instances are only created on one
87// thread, so the memory utilization is actually fairly restrained.
[email protected]75b79202009-12-30 07:31:4588//
89// Lastly, when an instance is deleted, the final tallies of statistics are
[email protected]c7dbf302011-11-08 07:57:0590// carefully accumulated. That tallying writes into slots (members) in a
[email protected]75b79202009-12-30 07:31:4591// collection of DeathData instances. For each birth place Location that is
92// destroyed on a thread, there is a DeathData instance to record the additional
[email protected]84b57952011-10-15 23:52:4593// death count, as well as accumulate the run-time and queue-time durations for
94// the instance as it is destroyed (dies). By maintaining a single place to
95// aggregate this running sum *only* for the given thread, we avoid the need to
96// lock such DeathData instances. (i.e., these accumulated stats in a DeathData
97// instance are exclusively updated by the singular owning thread).
[email protected]75b79202009-12-30 07:31:4598//
mithro5eb58502014-11-19 18:55:5899// With the above life cycle description complete, the major remaining detail
100// is explaining how each thread maintains a list of DeathData instances, and
101// of Births instances, and is able to avoid additional (redundant/unnecessary)
[email protected]75b79202009-12-30 07:31:45102// allocations.
103//
104// Each thread maintains a list of data items specific to that thread in a
105// ThreadData instance (for that specific thread only). The two critical items
106// are lists of DeathData and Births instances. These lists are maintained in
107// STL maps, which are indexed by Location. As noted earlier, we can compare
108// locations very efficiently as we consider the underlying data (file,
109// function, line) to be atoms, and hence pointer comparison is used rather than
110// (slow) string comparisons.
111//
112// To provide a mechanism for iterating over all "known threads," which means
113// threads that have recorded a birth or a death, we create a singly linked list
114// of ThreadData instances. Each such instance maintains a pointer to the next
[email protected]84baeca2011-10-24 18:55:16115// one. A static member of ThreadData provides a pointer to the first item on
116// this global list, and access via that all_thread_data_list_head_ item
117// requires the use of the list_lock_.
[email protected]75b79202009-12-30 07:31:45118// When new ThreadData instances is added to the global list, it is pre-pended,
119// which ensures that any prior acquisition of the list is valid (i.e., the
120// holder can iterate over it without fear of it changing, or the necessity of
121// using an additional lock. Iterations are actually pretty rare (used
mithro5eb58502014-11-19 18:55:58122// primarily for cleanup, or snapshotting data for display), so this lock has
[email protected]75b79202009-12-30 07:31:45123// very little global performance impact.
124//
125// The above description tries to define the high performance (run time)
126// portions of these classes. After gathering statistics, calls instigated
[email protected]dda97682011-11-14 05:24:07127// by visiting about:profiler will assemble and aggregate data for display. The
[email protected]75b79202009-12-30 07:31:45128// following data structures are used for producing such displays. They are
129// not performance critical, and their only major constraint is that they should
130// be able to run concurrently with ongoing augmentation of the birth and death
131// data.
132//
[email protected]1cb05db2012-04-13 00:39:26133// This header also exports collection of classes that provide "snapshotted"
134// representations of the core tracked_objects:: classes. These snapshotted
135// representations are designed for safe transmission of the tracked_objects::
136// data across process boundaries. Each consists of:
137// (1) a default constructor, to support the IPC serialization macros,
138// (2) a constructor that extracts data from the type being snapshotted, and
139// (3) the snapshotted data.
140//
[email protected]c7dbf302011-11-08 07:57:05141// For a given birth location, information about births is spread across data
[email protected]1cb05db2012-04-13 00:39:26142// structures that are asynchronously changing on various threads. For
143// serialization and display purposes, we need to construct TaskSnapshot
144// instances for each combination of birth thread, death thread, and location,
145// along with the count of such lifetimes. We gather such data into a
146// TaskSnapshot instances, so that such instances can be sorted and
147// aggregated (and remain frozen during our processing).
[email protected]75b79202009-12-30 07:31:45148//
[email protected]1cb05db2012-04-13 00:39:26149// The ProcessDataSnapshot struct is a serialized representation of the list
150// of ThreadData objects for a process. It holds a set of TaskSnapshots
151// and tracks parent/child relationships for the executed tasks. The statistics
152// in a snapshot are gathered asynhcronously relative to their ongoing updates.
153// It is possible, though highly unlikely, that stats could be incorrectly
154// recorded by this process (all data is held in 32 bit ints, but we are not
155// atomically collecting all data, so we could have count that does not, for
156// example, match with the number of durations we accumulated). The advantage
157// to having fast (non-atomic) updates of the data outweighs the minimal risk of
158// a singular corrupt statistic snapshot (only the snapshot could be corrupt,
mithro5eb58502014-11-19 18:55:58159// not the underlying and ongoing statistic). In contrast, pointer data that
[email protected]1cb05db2012-04-13 00:39:26160// is accessed during snapshotting is completely invariant, and hence is
161// perfectly acquired (i.e., no potential corruption, and no risk of a bad
162// memory reference).
[email protected]75b79202009-12-30 07:31:45163//
[email protected]26cdeb962011-11-20 04:17:07164// TODO(jar): We can implement a Snapshot system that *tries* to grab the
165// snapshots on the source threads *when* they have MessageLoops available
166// (worker threads don't have message loops generally, and hence gathering from
167// them will continue to be asynchronous). We had an implementation of this in
168// the past, but the difficulty is dealing with message loops being terminated.
169// We can *try* to spam the available threads via some message loop proxy to
mithro5eb58502014-11-19 18:55:58170// achieve this feat, and it *might* be valuable when we are collecting data
171// for upload via UMA (where correctness of data may be more significant than
172// for a single screen of about:profiler).
[email protected]26cdeb962011-11-20 04:17:07173//
[email protected]26cdeb962011-11-20 04:17:07174// TODO(jar): We should support (optionally) the recording of parent-child
175// relationships for tasks. This should be done by detecting what tasks are
176// Born during the running of a parent task. The resulting data can be used by
177// a smarter profiler to aggregate the cost of a series of child tasks into
178// the ancestor task. It can also be used to illuminate what child or parent is
179// related to each task.
180//
181// TODO(jar): We need to store DataCollections, and provide facilities for
182// taking the difference between two gathered DataCollections. For now, we're
183// just adding a hack that Reset()s to zero all counts and stats. This is also
mithro5eb58502014-11-19 18:55:58184// done in a slightly thread-unsafe fashion, as the resetting is done
[email protected]eab79c382011-11-06 19:14:48185// asynchronously relative to ongoing updates (but all data is 32 bit in size).
186// For basic profiling, this will work "most of the time," and should be
[email protected]75b79202009-12-30 07:31:45187// sufficient... but storing away DataCollections is the "right way" to do this.
[email protected]eab79c382011-11-06 19:14:48188// We'll accomplish this via JavaScript storage of snapshots, and then we'll
[email protected]26cdeb962011-11-20 04:17:07189// remove the Reset() methods. We may also need a short-term-max value in
190// DeathData that is reset (as synchronously as possible) during each snapshot.
191// This will facilitate displaying a max value for each snapshot period.
initial.commitd7cae122008-07-26 21:49:38192
193namespace tracked_objects {
194
195//------------------------------------------------------------------------------
196// For a specific thread, and a specific birth place, the collection of all
197// death info (with tallies for each death thread, to prevent access conflicts).
198class ThreadData;
[email protected]0bea7252011-08-05 15:34:00199class BASE_EXPORT BirthOnThread {
initial.commitd7cae122008-07-26 21:49:38200 public:
[email protected]84baeca2011-10-24 18:55:16201 BirthOnThread(const Location& location, const ThreadData& current);
initial.commitd7cae122008-07-26 21:49:38202
[email protected]1cb05db2012-04-13 00:39:26203 const Location location() const { return location_; }
204 const ThreadData* birth_thread() const { return birth_thread_; }
[email protected]8aa1e6e2011-12-14 01:36:48205
initial.commitd7cae122008-07-26 21:49:38206 private:
[email protected]84b57952011-10-15 23:52:45207 // File/lineno of birth. This defines the essence of the task, as the context
initial.commitd7cae122008-07-26 21:49:38208 // of the birth (construction) often tell what the item is for. This field
209 // is const, and hence safe to access from any thread.
210 const Location location_;
211
212 // The thread that records births into this object. Only this thread is
[email protected]84baeca2011-10-24 18:55:16213 // allowed to update birth_count_ (which changes over time).
214 const ThreadData* const birth_thread_;
initial.commitd7cae122008-07-26 21:49:38215
[email protected]022614ef92008-12-30 20:50:01216 DISALLOW_COPY_AND_ASSIGN(BirthOnThread);
initial.commitd7cae122008-07-26 21:49:38217};
218
219//------------------------------------------------------------------------------
[email protected]1cb05db2012-04-13 00:39:26220// A "snapshotted" representation of the BirthOnThread class.
221
222struct BASE_EXPORT BirthOnThreadSnapshot {
223 BirthOnThreadSnapshot();
224 explicit BirthOnThreadSnapshot(const BirthOnThread& birth);
225 ~BirthOnThreadSnapshot();
226
227 LocationSnapshot location;
228 std::string thread_name;
229};
230
231//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38232// A class for accumulating counts of births (without bothering with a map<>).
233
[email protected]0bea7252011-08-05 15:34:00234class BASE_EXPORT Births: public BirthOnThread {
initial.commitd7cae122008-07-26 21:49:38235 public:
[email protected]84baeca2011-10-24 18:55:16236 Births(const Location& location, const ThreadData& current);
initial.commitd7cae122008-07-26 21:49:38237
[email protected]b6b2b892011-12-04 07:19:10238 int birth_count() const;
initial.commitd7cae122008-07-26 21:49:38239
[email protected]1cb05db2012-04-13 00:39:26240 // When we have a birth we update the count for this birthplace.
[email protected]b6b2b892011-12-04 07:19:10241 void RecordBirth();
initial.commitd7cae122008-07-26 21:49:38242
243 // When a birthplace is changed (updated), we need to decrement the counter
244 // for the old instance.
[email protected]b6b2b892011-12-04 07:19:10245 void ForgetBirth();
initial.commitd7cae122008-07-26 21:49:38246
[email protected]75b79202009-12-30 07:31:45247 // Hack to quickly reset all counts to zero.
[email protected]b6b2b892011-12-04 07:19:10248 void Clear();
[email protected]75b79202009-12-30 07:31:45249
initial.commitd7cae122008-07-26 21:49:38250 private:
251 // The number of births on this thread for our location_.
252 int birth_count_;
253
[email protected]022614ef92008-12-30 20:50:01254 DISALLOW_COPY_AND_ASSIGN(Births);
initial.commitd7cae122008-07-26 21:49:38255};
256
257//------------------------------------------------------------------------------
[email protected]b2a9bbd2011-10-31 22:36:21258// Basic info summarizing multiple destructions of a tracked object with a
259// single birthplace (fixed Location). Used both on specific threads, and also
initial.commitd7cae122008-07-26 21:49:38260// in snapshots when integrating assembled data.
261
[email protected]0bea7252011-08-05 15:34:00262class BASE_EXPORT DeathData {
initial.commitd7cae122008-07-26 21:49:38263 public:
264 // Default initializer.
[email protected]b6b2b892011-12-04 07:19:10265 DeathData();
initial.commitd7cae122008-07-26 21:49:38266
267 // When deaths have not yet taken place, and we gather data from all the
268 // threads, we create DeathData stats that tally the number of births without
[email protected]b6b2b892011-12-04 07:19:10269 // a corresponding death.
270 explicit DeathData(int count);
initial.commitd7cae122008-07-26 21:49:38271
[email protected]84b57952011-10-15 23:52:45272 // Update stats for a task destruction (death) that had a Run() time of
273 // |duration|, and has had a queueing delay of |queue_duration|.
[email protected]c186e962012-03-24 22:17:18274 void RecordDeath(const int32 queue_duration,
275 const int32 run_duration,
gliderf78125752014-11-12 21:05:33276 const uint32 random_number);
initial.commitd7cae122008-07-26 21:49:38277
[email protected]1cb05db2012-04-13 00:39:26278 // Metrics accessors, used only for serialization and in tests.
[email protected]b6b2b892011-12-04 07:19:10279 int count() const;
[email protected]c186e962012-03-24 22:17:18280 int32 run_duration_sum() const;
281 int32 run_duration_max() const;
282 int32 run_duration_sample() const;
283 int32 queue_duration_sum() const;
284 int32 queue_duration_max() const;
285 int32 queue_duration_sample() const;
initial.commitd7cae122008-07-26 21:49:38286
[email protected]b6b2b892011-12-04 07:19:10287 // Reset the max values to zero.
288 void ResetMax();
289
[email protected]84b57952011-10-15 23:52:45290 // Reset all tallies to zero. This is used as a hack on realtime data.
initial.commitd7cae122008-07-26 21:49:38291 void Clear();
292
293 private:
[email protected]7ceb44482011-12-09 03:41:04294 // Members are ordered from most regularly read and updated, to least
295 // frequently used. This might help a bit with cache lines.
296 // Number of runs seen (divisor for calculating averages).
[email protected]b6b2b892011-12-04 07:19:10297 int count_;
[email protected]7ceb44482011-12-09 03:41:04298 // Basic tallies, used to compute averages.
[email protected]c186e962012-03-24 22:17:18299 int32 run_duration_sum_;
300 int32 queue_duration_sum_;
[email protected]7ceb44482011-12-09 03:41:04301 // Max values, used by local visualization routines. These are often read,
302 // but rarely updated.
[email protected]c186e962012-03-24 22:17:18303 int32 run_duration_max_;
304 int32 queue_duration_max_;
[email protected]1cb05db2012-04-13 00:39:26305 // Samples, used by crowd sourcing gatherers. These are almost never read,
[email protected]7ceb44482011-12-09 03:41:04306 // and rarely updated.
[email protected]c186e962012-03-24 22:17:18307 int32 run_duration_sample_;
308 int32 queue_duration_sample_;
initial.commitd7cae122008-07-26 21:49:38309};
310
311//------------------------------------------------------------------------------
[email protected]1cb05db2012-04-13 00:39:26312// A "snapshotted" representation of the DeathData class.
313
314struct BASE_EXPORT DeathDataSnapshot {
315 DeathDataSnapshot();
316 explicit DeathDataSnapshot(const DeathData& death_data);
317 ~DeathDataSnapshot();
318
319 int count;
320 int32 run_duration_sum;
321 int32 run_duration_max;
322 int32 run_duration_sample;
323 int32 queue_duration_sum;
324 int32 queue_duration_max;
325 int32 queue_duration_sample;
326};
327
328//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38329// A temporary collection of data that can be sorted and summarized. It is
330// gathered (carefully) from many threads. Instances are held in arrays and
331// processed, filtered, and rendered.
332// The source of this data was collected on many threads, and is asynchronously
333// changing. The data in this instance is not asynchronously changing.
334
[email protected]1cb05db2012-04-13 00:39:26335struct BASE_EXPORT TaskSnapshot {
336 TaskSnapshot();
337 TaskSnapshot(const BirthOnThread& birth,
338 const DeathData& death_data,
339 const std::string& death_thread_name);
340 ~TaskSnapshot();
initial.commitd7cae122008-07-26 21:49:38341
[email protected]1cb05db2012-04-13 00:39:26342 BirthOnThreadSnapshot birth;
343 DeathDataSnapshot death_data;
344 std::string death_thread_name;
initial.commitd7cae122008-07-26 21:49:38345};
[email protected]84b57952011-10-15 23:52:45346
initial.commitd7cae122008-07-26 21:49:38347//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38348// For each thread, we have a ThreadData that stores all tracking info generated
349// on this thread. This prevents the need for locking as data accumulates.
[email protected]b2a9bbd2011-10-31 22:36:21350// We use ThreadLocalStorage to quickly identfy the current ThreadData context.
351// We also have a linked list of ThreadData instances, and that list is used to
352// harvest data from all existing instances.
initial.commitd7cae122008-07-26 21:49:38353
[email protected]1cb05db2012-04-13 00:39:26354struct ProcessDataSnapshot;
vadimt12f0f7d2014-09-15 19:19:38355class BASE_EXPORT TaskStopwatch;
356
[email protected]0bea7252011-08-05 15:34:00357class BASE_EXPORT ThreadData {
initial.commitd7cae122008-07-26 21:49:38358 public:
[email protected]b2a9bbd2011-10-31 22:36:21359 // Current allowable states of the tracking system. The states can vary
360 // between ACTIVE and DEACTIVATED, but can never go back to UNINITIALIZED.
361 enum Status {
[email protected]8aa1e6e2011-12-14 01:36:48362 UNINITIALIZED, // PRistine, link-time state before running.
363 DORMANT_DURING_TESTS, // Only used during testing.
mithro5eb58502014-11-19 18:55:58364 DEACTIVATED, // No longer recording profiling.
[email protected]8aa1e6e2011-12-14 01:36:48365 PROFILING_ACTIVE, // Recording profiles (no parent-child links).
366 PROFILING_CHILDREN_ACTIVE, // Fully active, recording parent-child links.
[email protected]c86f4de2014-02-10 19:41:46367 STATUS_LAST = PROFILING_CHILDREN_ACTIVE
[email protected]b2a9bbd2011-10-31 22:36:21368 };
369
initial.commitd7cae122008-07-26 21:49:38370 typedef std::map<Location, Births*> BirthMap;
371 typedef std::map<const Births*, DeathData> DeathMap;
[email protected]8aa1e6e2011-12-14 01:36:48372 typedef std::pair<const Births*, const Births*> ParentChildPair;
373 typedef std::set<ParentChildPair> ParentChildSet;
374 typedef std::stack<const Births*> ParentStack;
initial.commitd7cae122008-07-26 21:49:38375
[email protected]84b57952011-10-15 23:52:45376 // Initialize the current thread context with a new instance of ThreadData.
[email protected]b2a9bbd2011-10-31 22:36:21377 // This is used by all threads that have names, and should be explicitly
378 // set *before* any births on the threads have taken place. It is generally
379 // only used by the message loop, which has a well defined thread name.
[email protected]84b57952011-10-15 23:52:45380 static void InitializeThreadContext(const std::string& suggested_name);
initial.commitd7cae122008-07-26 21:49:38381
382 // Using Thread Local Store, find the current instance for collecting data.
383 // If an instance does not exist, construct one (and remember it for use on
384 // this thread.
[email protected]84baeca2011-10-24 18:55:16385 // This may return NULL if the system is disabled for any reason.
[email protected]84b57952011-10-15 23:52:45386 static ThreadData* Get();
initial.commitd7cae122008-07-26 21:49:38387
[email protected]1cb05db2012-04-13 00:39:26388 // Fills |process_data| with all the recursive results in our process.
389 // During the scavenging, if |reset_max| is true, then the DeathData instances
390 // max-values are reset to zero during this scan.
391 static void Snapshot(bool reset_max, ProcessDataSnapshot* process_data);
[email protected]b2a9bbd2011-10-31 22:36:21392
393 // Finds (or creates) a place to count births from the given location in this
[email protected]84baeca2011-10-24 18:55:16394 // thread, and increment that tally.
[email protected]180c85e2011-07-26 18:25:16395 // TallyABirthIfActive will returns NULL if the birth cannot be tallied.
396 static Births* TallyABirthIfActive(const Location& location);
[email protected]84b57952011-10-15 23:52:45397
[email protected]b2a9bbd2011-10-31 22:36:21398 // Records the end of a timed run of an object. The |completed_task| contains
399 // a pointer to a Births, the time_posted, and a delayed_start_time if any.
400 // The |start_of_run| indicates when we started to perform the run of the
401 // task. The delayed_start_time is non-null for tasks that were posted as
402 // delayed tasks, and it indicates when the task should have run (i.e., when
403 // it should have posted out of the timer queue, and into the work queue.
404 // The |end_of_run| was just obtained by a call to Now() (just after the task
405 // finished). It is provided as an argument to help with testing.
406 static void TallyRunOnNamedThreadIfTracking(
407 const base::TrackingInfo& completed_task,
vadimt12f0f7d2014-09-15 19:19:38408 const TaskStopwatch& stopwatch);
[email protected]b2a9bbd2011-10-31 22:36:21409
[email protected]6b26b96012011-10-28 21:41:50410 // Record the end of a timed run of an object. The |birth| is the record for
[email protected]b2a9bbd2011-10-31 22:36:21411 // the instance, the |time_posted| records that instant, which is presumed to
412 // be when the task was posted into a queue to run on a worker thread.
413 // The |start_of_run| is when the worker thread started to perform the run of
414 // the task.
[email protected]84baeca2011-10-24 18:55:16415 // The |end_of_run| was just obtained by a call to Now() (just after the task
416 // finished).
[email protected]b2a9bbd2011-10-31 22:36:21417 static void TallyRunOnWorkerThreadIfTracking(
418 const Births* birth,
419 const TrackedTime& time_posted,
vadimt12f0f7d2014-09-15 19:19:38420 const TaskStopwatch& stopwatch);
initial.commitd7cae122008-07-26 21:49:38421
[email protected]dbe5d2072011-11-08 17:09:21422 // Record the end of execution in region, generally corresponding to a scope
423 // being exited.
424 static void TallyRunInAScopedRegionIfTracking(
425 const Births* birth,
vadimt12f0f7d2014-09-15 19:19:38426 const TaskStopwatch& stopwatch);
[email protected]dbe5d2072011-11-08 17:09:21427
[email protected]f42482e2012-11-05 06:25:55428 const std::string& thread_name() const { return thread_name_; }
initial.commitd7cae122008-07-26 21:49:38429
[email protected]75b79202009-12-30 07:31:45430 // Hack: asynchronously clear all birth counts and death tallies data values
431 // in all ThreadData instances. The numerical (zeroing) part is done without
432 // use of a locks or atomics exchanges, and may (for int64 values) produce
433 // bogus counts VERY rarely.
434 static void ResetAllThreadData();
435
[email protected]b2a9bbd2011-10-31 22:36:21436 // Initializes all statics if needed (this initialization call should be made
437 // while we are single threaded). Returns false if unable to initialize.
438 static bool Initialize();
439
[email protected]8aa1e6e2011-12-14 01:36:48440 // Sets internal status_.
441 // If |status| is false, then status_ is set to DEACTIVATED.
442 // If |status| is true, then status_ is set to, PROFILING_ACTIVE, or
443 // PROFILING_CHILDREN_ACTIVE.
[email protected]b2a9bbd2011-10-31 22:36:21444 // If tracking is not compiled in, this function will return false.
[email protected]8aa1e6e2011-12-14 01:36:48445 // If parent-child tracking is not compiled in, then an attempt to set the
446 // status to PROFILING_CHILDREN_ACTIVE will only result in a status of
447 // PROFILING_ACTIVE (i.e., it can't be set to a higher level than what is
448 // compiled into the binary, and parent-child tracking at the
449 // PROFILING_CHILDREN_ACTIVE level might not be compiled in).
[email protected]702a12d2012-02-10 19:43:42450 static bool InitializeAndSetTrackingStatus(Status status);
451
452 static Status status();
[email protected]8aa1e6e2011-12-14 01:36:48453
454 // Indicate if any sort of profiling is being done (i.e., we are more than
455 // DEACTIVATED).
[email protected]702a12d2012-02-10 19:43:42456 static bool TrackingStatus();
initial.commitd7cae122008-07-26 21:49:38457
[email protected]8aa1e6e2011-12-14 01:36:48458 // For testing only, indicate if the status of parent-child tracking is turned
[email protected]702a12d2012-02-10 19:43:42459 // on. This is currently a compiled option, atop TrackingStatus().
460 static bool TrackingParentChildStatus();
[email protected]8aa1e6e2011-12-14 01:36:48461
vadimt12f0f7d2014-09-15 19:19:38462 // Marks a start of a tracked run. It's super fast when tracking is disabled,
463 // and has some internal side effects when we are tracking, so that we can
464 // deduce the amount of time accumulated outside of execution of tracked runs.
[email protected]8aa1e6e2011-12-14 01:36:48465 // The task that will be tracked is passed in as |parent| so that parent-child
466 // relationships can be (optionally) calculated.
vadimt12f0f7d2014-09-15 19:19:38467 static void PrepareForStartOfRun(const Births* parent);
[email protected]dda97682011-11-14 05:24:07468
vadimta1568312014-11-06 22:27:43469 // Enables profiler timing.
470 static void EnableProfilerTiming();
471
[email protected]84b57952011-10-15 23:52:45472 // Provide a time function that does nothing (runs fast) when we don't have
473 // the profiler enabled. It will generally be optimized away when it is
474 // ifdef'ed to be small enough (allowing the profiler to be "compiled out" of
475 // the code).
[email protected]b2a9bbd2011-10-31 22:36:21476 static TrackedTime Now();
initial.commitd7cae122008-07-26 21:49:38477
[email protected]90895d0f2012-02-15 23:05:01478 // Use the function |now| to provide current times, instead of calling the
479 // TrackedTime::Now() function. Since this alternate function is being used,
480 // the other time arguments (used for calculating queueing delay) will be
481 // ignored.
482 static void SetAlternateTimeSource(NowFunction* now);
483
[email protected]9a88c902011-11-24 00:00:31484 // This function can be called at process termination to validate that thread
485 // cleanup routines have been called for at least some number of named
486 // threads.
487 static void EnsureCleanupWasCalled(int major_threads_shutdown_count);
488
initial.commitd7cae122008-07-26 21:49:38489 private:
vadimt12f0f7d2014-09-15 19:19:38490 friend class TaskStopwatch;
[email protected]eab79c382011-11-06 19:14:48491 // Allow only tests to call ShutdownSingleThreadedCleanup. We NEVER call it
492 // in production code.
[email protected]b6b2b892011-12-04 07:19:10493 // TODO(jar): Make this a friend in DEBUG only, so that the optimizer has a
494 // better change of optimizing (inlining? etc.) private methods (knowing that
495 // there will be no need for an external entry point).
[email protected]eab79c382011-11-06 19:14:48496 friend class TrackedObjectsTest;
[email protected]b6b2b892011-12-04 07:19:10497 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, MinimalStartupShutdown);
498 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, TinyStartupShutdown);
[email protected]8aa1e6e2011-12-14 01:36:48499 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, ParentChildTest);
[email protected]eab79c382011-11-06 19:14:48500
[email protected]1cb05db2012-04-13 00:39:26501 typedef std::map<const BirthOnThread*, int> BirthCountMap;
502
[email protected]84baeca2011-10-24 18:55:16503 // Worker thread construction creates a name since there is none.
[email protected]26cdeb962011-11-20 04:17:07504 explicit ThreadData(int thread_number);
[email protected]445029fb2011-11-18 17:03:33505
[email protected]84baeca2011-10-24 18:55:16506 // Message loop based construction should provide a name.
507 explicit ThreadData(const std::string& suggested_name);
508
509 ~ThreadData();
510
511 // Push this instance to the head of all_thread_data_list_head_, linking it to
512 // the previous head. This is performed after each construction, and leaves
513 // the instance permanently on that list.
514 void PushToHeadOfList();
515
[email protected]b6b2b892011-12-04 07:19:10516 // (Thread safe) Get start of list of all ThreadData instances using the lock.
517 static ThreadData* first();
518
519 // Iterate through the null terminated list of ThreadData instances.
520 ThreadData* next() const;
521
522
[email protected]84baeca2011-10-24 18:55:16523 // In this thread's data, record a new birth.
524 Births* TallyABirth(const Location& location);
525
526 // Find a place to record a death on this thread.
vadimt12f0f7d2014-09-15 19:19:38527 void TallyADeath(const Births& birth,
528 int32 queue_duration,
529 const TaskStopwatch& stopwatch);
[email protected]84baeca2011-10-24 18:55:16530
[email protected]1cb05db2012-04-13 00:39:26531 // Snapshot (under a lock) the profiled data for the tasks in each ThreadData
532 // instance. Also updates the |birth_counts| tally for each task to keep
533 // track of the number of living instances of the task. If |reset_max| is
534 // true, then the max values in each DeathData instance are reset during the
535 // scan.
536 static void SnapshotAllExecutedTasks(bool reset_max,
537 ProcessDataSnapshot* process_data,
538 BirthCountMap* birth_counts);
539
540 // Snapshots (under a lock) the profiled data for the tasks for this thread
541 // and writes all of the executed tasks' data -- i.e. the data for the tasks
542 // with with entries in the death_map_ -- into |process_data|. Also updates
543 // the |birth_counts| tally for each task to keep track of the number of
544 // living instances of the task -- that is, each task maps to the number of
545 // births for the task that have not yet been balanced by a death. If
546 // |reset_max| is true, then the max values in each DeathData instance are
547 // reset during the scan.
548 void SnapshotExecutedTasks(bool reset_max,
549 ProcessDataSnapshot* process_data,
550 BirthCountMap* birth_counts);
551
[email protected]b6b2b892011-12-04 07:19:10552 // Using our lock, make a copy of the specified maps. This call may be made
553 // on non-local threads, which necessitate the use of the lock to prevent
mithro5eb58502014-11-19 18:55:58554 // the map(s) from being reallocated while they are copied. If |reset_max| is
[email protected]b6b2b892011-12-04 07:19:10555 // true, then, just after we copy the DeathMap, we will set the max values to
556 // zero in the active DeathMap (not the snapshot).
557 void SnapshotMaps(bool reset_max,
558 BirthMap* birth_map,
[email protected]8aa1e6e2011-12-14 01:36:48559 DeathMap* death_map,
560 ParentChildSet* parent_child_set);
[email protected]b6b2b892011-12-04 07:19:10561
[email protected]84baeca2011-10-24 18:55:16562 // Using our lock to protect the iteration, Clear all birth and death data.
563 void Reset();
564
565 // This method is called by the TLS system when a thread terminates.
566 // The argument may be NULL if this thread has never tracked a birth or death.
567 static void OnThreadTermination(void* thread_data);
568
569 // This method should be called when a worker thread terminates, so that we
570 // can save all the thread data into a cache of reusable ThreadData instances.
[email protected]26cdeb962011-11-20 04:17:07571 void OnThreadTerminationCleanup();
[email protected]84baeca2011-10-24 18:55:16572
[email protected]eab79c382011-11-06 19:14:48573 // Cleans up data structures, and returns statics to near pristine (mostly
574 // uninitialized) state. If there is any chance that other threads are still
575 // using the data structures, then the |leak| argument should be passed in as
576 // true, and the data structures (birth maps, death maps, ThreadData
577 // insntances, etc.) will be leaked and not deleted. If you have joined all
578 // threads since the time that InitializeAndSetTrackingStatus() was called,
579 // then you can pass in a |leak| value of false, and this function will
580 // delete recursively all data structures, starting with the list of
581 // ThreadData instances.
582 static void ShutdownSingleThreadedCleanup(bool leak);
583
[email protected]90895d0f2012-02-15 23:05:01584 // When non-null, this specifies an external function that supplies monotone
585 // increasing time functcion.
586 static NowFunction* now_function_;
587
vadimt12f0f7d2014-09-15 19:19:38588 // If true, now_function_ returns values that can be used to calculate queue
589 // time.
590 static bool now_function_is_time_;
591
initial.commitd7cae122008-07-26 21:49:38592 // We use thread local store to identify which ThreadData to interact with.
[email protected]444b8a3c2012-01-30 16:52:09593 static base::ThreadLocalStorage::StaticSlot tls_index_;
initial.commitd7cae122008-07-26 21:49:38594
[email protected]26cdeb962011-11-20 04:17:07595 // List of ThreadData instances for use with worker threads. When a worker
mithro5eb58502014-11-19 18:55:58596 // thread is done (terminated), we push it onto this list. When a new worker
[email protected]26cdeb962011-11-20 04:17:07597 // thread is created, we first try to re-use a ThreadData instance from the
598 // list, and if none are available, construct a new one.
599 // This is only accessed while list_lock_ is held.
600 static ThreadData* first_retired_worker_;
601
initial.commitd7cae122008-07-26 21:49:38602 // Link to the most recently created instance (starts a null terminated list).
[email protected]dda97682011-11-14 05:24:07603 // The list is traversed by about:profiler when it needs to snapshot data.
[email protected]b2a9bbd2011-10-31 22:36:21604 // This is only accessed while list_lock_ is held.
[email protected]84baeca2011-10-24 18:55:16605 static ThreadData* all_thread_data_list_head_;
[email protected]9a88c902011-11-24 00:00:31606
607 // The next available worker thread number. This should only be accessed when
608 // the list_lock_ is held.
609 static int worker_thread_data_creation_count_;
610
611 // The number of times TLS has called us back to cleanup a ThreadData
612 // instance. This is only accessed while list_lock_ is held.
613 static int cleanup_count_;
614
[email protected]b2a9bbd2011-10-31 22:36:21615 // Incarnation sequence number, indicating how many times (during unittests)
616 // we've either transitioned out of UNINITIALIZED, or into that state. This
617 // value is only accessed while the list_lock_ is held.
618 static int incarnation_counter_;
[email protected]9a88c902011-11-24 00:00:31619
[email protected]84baeca2011-10-24 18:55:16620 // Protection for access to all_thread_data_list_head_, and to
[email protected]b2a9bbd2011-10-31 22:36:21621 // unregistered_thread_data_pool_. This lock is leaked at shutdown.
[email protected]77169a62011-11-14 20:36:46622 // The lock is very infrequently used, so we can afford to just make a lazy
623 // instance and be safe.
[email protected]9fc44162012-01-23 22:56:41624 static base::LazyInstance<base::Lock>::Leaky list_lock_;
[email protected]b2a9bbd2011-10-31 22:36:21625
[email protected]84b57952011-10-15 23:52:45626 // We set status_ to SHUTDOWN when we shut down the tracking service.
initial.commitd7cae122008-07-26 21:49:38627 static Status status_;
628
629 // Link to next instance (null terminated list). Used to globally track all
630 // registered instances (corresponds to all registered threads where we keep
631 // data).
632 ThreadData* next_;
633
[email protected]26cdeb962011-11-20 04:17:07634 // Pointer to another ThreadData instance for a Worker-Thread that has been
635 // retired (its thread was terminated). This value is non-NULL only for a
636 // retired ThreadData associated with a Worker-Thread.
637 ThreadData* next_retired_worker_;
638
[email protected]84b57952011-10-15 23:52:45639 // The name of the thread that is being recorded. If this thread has no
640 // message_loop, then this is a worker thread, with a sequence number postfix.
641 std::string thread_name_;
initial.commitd7cae122008-07-26 21:49:38642
[email protected]84baeca2011-10-24 18:55:16643 // Indicate if this is a worker thread, and the ThreadData contexts should be
644 // stored in the unregistered_thread_data_pool_ when not in use.
[email protected]445029fb2011-11-18 17:03:33645 // Value is zero when it is not a worker thread. Value is a positive integer
646 // corresponding to the created thread name if it is a worker thread.
[email protected]26cdeb962011-11-20 04:17:07647 int worker_thread_number_;
[email protected]84baeca2011-10-24 18:55:16648
initial.commitd7cae122008-07-26 21:49:38649 // A map used on each thread to keep track of Births on this thread.
650 // This map should only be accessed on the thread it was constructed on.
651 // When a snapshot is needed, this structure can be locked in place for the
652 // duration of the snapshotting activity.
653 BirthMap birth_map_;
654
655 // Similar to birth_map_, this records informations about death of tracked
656 // instances (i.e., when a tracked instance was destroyed on this thread).
[email protected]75b79202009-12-30 07:31:45657 // It is locked before changing, and hence other threads may access it by
658 // locking before reading it.
initial.commitd7cae122008-07-26 21:49:38659 DeathMap death_map_;
660
[email protected]8aa1e6e2011-12-14 01:36:48661 // A set of parents that created children tasks on this thread. Each pair
662 // corresponds to potentially non-local Births (location and thread), and a
663 // local Births (that took place on this thread).
664 ParentChildSet parent_child_set_;
665
[email protected]75b79202009-12-30 07:31:45666 // Lock to protect *some* access to BirthMap and DeathMap. The maps are
667 // regularly read and written on this thread, but may only be read from other
668 // threads. To support this, we acquire this lock if we are writing from this
669 // thread, or reading from another thread. For reading from this thread we
670 // don't need a lock, as there is no potential for a conflict since the
671 // writing is only done from this thread.
[email protected]9a88c902011-11-24 00:00:31672 mutable base::Lock map_lock_;
initial.commitd7cae122008-07-26 21:49:38673
[email protected]8aa1e6e2011-12-14 01:36:48674 // The stack of parents that are currently being profiled. This includes only
vadimt12f0f7d2014-09-15 19:19:38675 // tasks that have started a timer recently via PrepareForStartOfRun(), but
676 // not yet concluded with a NowForEndOfRun(). Usually this stack is one deep,
677 // but if a scoped region is profiled, or <sigh> a task runs a nested-message
[email protected]8aa1e6e2011-12-14 01:36:48678 // loop, then the stack can grow larger. Note that we don't try to deduct
mithro5eb58502014-11-19 18:55:58679 // time in nested profiles, as our current timer is based on wall-clock time,
[email protected]8aa1e6e2011-12-14 01:36:48680 // and not CPU time (and we're hopeful that nested timing won't be a
681 // significant additional cost).
682 ParentStack parent_stack_;
683
[email protected]b6b2b892011-12-04 07:19:10684 // A random number that we used to select decide which sample to keep as a
685 // representative sample in each DeathData instance. We can't start off with
686 // much randomness (because we can't call RandInt() on all our threads), so
687 // we stir in more and more as we go.
gliderf78125752014-11-12 21:05:33688 uint32 random_number_;
[email protected]b6b2b892011-12-04 07:19:10689
[email protected]8aa1e6e2011-12-14 01:36:48690 // Record of what the incarnation_counter_ was when this instance was created.
691 // If the incarnation_counter_ has changed, then we avoid pushing into the
692 // pool (this is only critical in tests which go through multiple
693 // incarnations).
694 int incarnation_count_for_pool_;
695
vadimt12f0f7d2014-09-15 19:19:38696 // Most recently started (i.e. most nested) stopwatch on the current thread,
697 // if it exists; NULL otherwise.
698 TaskStopwatch* current_stopwatch_;
699
[email protected]022614ef92008-12-30 20:50:01700 DISALLOW_COPY_AND_ASSIGN(ThreadData);
initial.commitd7cae122008-07-26 21:49:38701};
702
[email protected]022614ef92008-12-30 20:50:01703//------------------------------------------------------------------------------
vadimt12f0f7d2014-09-15 19:19:38704// Stopwatch to measure task run time or simply create a time interval that will
705// be subtracted from the current most nested task's run time. Stopwatches
706// coordinate with the stopwatches in which they are nested to avoid
707// double-counting nested tasks run times.
708
709class BASE_EXPORT TaskStopwatch {
710 public:
711 // Starts the stopwatch.
712 TaskStopwatch();
713 ~TaskStopwatch();
714
vadimt20175532014-10-28 20:14:20715 // Starts stopwatch.
716 void Start();
717
vadimt12f0f7d2014-09-15 19:19:38718 // Stops stopwatch.
719 void Stop();
720
721 // Returns the start time.
722 TrackedTime StartTime() const;
723
724 // Task's duration is calculated as the wallclock duration between starting
725 // and stopping this stopwatch, minus the wallclock durations of any other
726 // instances that are immediately nested in this one, started and stopped on
727 // this thread during that period.
728 int32 RunDurationMs() const;
729
730 // Returns tracking info for the current thread.
731 ThreadData* GetThreadData() const;
732
733 private:
734 // Time when the stopwatch was started.
735 TrackedTime start_time_;
736
737 // Wallclock duration of the task.
738 int32 wallclock_duration_ms_;
739
740 // Tracking info for the current thread.
741 ThreadData* current_thread_data_;
742
743 // Sum of wallclock durations of all stopwatches that were directly nested in
744 // this one.
745 int32 excluded_duration_ms_;
746
747 // Stopwatch which was running on our thread when this stopwatch was started.
748 // That preexisting stopwatch must be adjusted to the exclude the wallclock
749 // duration of this stopwatch.
750 TaskStopwatch* parent_;
751
752#if DCHECK_IS_ON
vadimt20175532014-10-28 20:14:20753 // State of the stopwatch. Stopwatch is first constructed in a created state
754 // state, then is optionally started/stopped, then destructed.
755 enum { CREATED, RUNNING, STOPPED } state_;
vadimt12f0f7d2014-09-15 19:19:38756
757 // Currently running stopwatch that is directly nested in this one, if such
758 // stopwatch exists. NULL otherwise.
759 TaskStopwatch* child_;
760#endif
761};
762
763//------------------------------------------------------------------------------
[email protected]1cb05db2012-04-13 00:39:26764// A snapshotted representation of a (parent, child) task pair, for tracking
765// hierarchical profiles.
[email protected]b6b2b892011-12-04 07:19:10766
[email protected]1cb05db2012-04-13 00:39:26767struct BASE_EXPORT ParentChildPairSnapshot {
[email protected]b6b2b892011-12-04 07:19:10768 public:
[email protected]1cb05db2012-04-13 00:39:26769 ParentChildPairSnapshot();
770 explicit ParentChildPairSnapshot(
771 const ThreadData::ParentChildPair& parent_child);
772 ~ParentChildPairSnapshot();
[email protected]b6b2b892011-12-04 07:19:10773
[email protected]1cb05db2012-04-13 00:39:26774 BirthOnThreadSnapshot parent;
775 BirthOnThreadSnapshot child;
776};
[email protected]b6b2b892011-12-04 07:19:10777
[email protected]1cb05db2012-04-13 00:39:26778//------------------------------------------------------------------------------
779// A snapshotted representation of the list of ThreadData objects for a process.
[email protected]b6b2b892011-12-04 07:19:10780
[email protected]1cb05db2012-04-13 00:39:26781struct BASE_EXPORT ProcessDataSnapshot {
782 public:
783 ProcessDataSnapshot();
784 ~ProcessDataSnapshot();
[email protected]b6b2b892011-12-04 07:19:10785
[email protected]1cb05db2012-04-13 00:39:26786 std::vector<TaskSnapshot> tasks;
787 std::vector<ParentChildPairSnapshot> descendants;
788 int process_id;
[email protected]b6b2b892011-12-04 07:19:10789};
790
initial.commitd7cae122008-07-26 21:49:38791} // namespace tracked_objects
792
793#endif // BASE_TRACKED_OBJECTS_H_