blob: a088ee201bac95b754e36dff68bfe17f219134e4 [file] [log] [blame]
[email protected]a502bbe72011-01-07 18:06:451// Copyright (c) 2011 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_
[email protected]32b76ef2010-07-26 23:08:247#pragma once
initial.commitd7cae122008-07-26 21:49:388
initial.commitd7cae122008-07-26 21:49:389#include <map>
[email protected]8aa1e6e2011-12-14 01:36:4810#include <set>
[email protected]84baeca2011-10-24 18:55:1611#include <stack>
initial.commitd7cae122008-07-26 21:49:3812#include <string>
[email protected]8aa1e6e2011-12-14 01:36:4813#include <utility>
initial.commitd7cae122008-07-26 21:49:3814#include <vector>
15
[email protected]0bea7252011-08-05 15:34:0016#include "base/base_export.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]dbe5d2072011-11-08 17:09:2120#include "base/profiler/tracked_time.h"
[email protected]c62dd9d2011-09-21 18:05:4121#include "base/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]b2a9bbd2011-10-31 22:36:2124#include "base/tracking_info.h"
[email protected]84baeca2011-10-24 18:55:1625#include "base/values.h"
initial.commitd7cae122008-07-26 21:49:3826
[email protected]75b79202009-12-30 07:31:4527// TrackedObjects provides a database of stats about objects (generally Tasks)
28// that are tracked. Tracking means their birth, death, duration, birth thread,
29// death thread, and birth place are recorded. This data is carefully spread
30// across a series of objects so that the counts and times can be rapidly
31// updated without (usually) having to lock the data, and hence there is usually
32// very little contention caused by the tracking. The data can be viewed via
[email protected]dda97682011-11-14 05:24:0733// the about:profiler URL, with a variety of sorting and filtering choices.
[email protected]75b79202009-12-30 07:31:4534//
[email protected]ea319e42010-11-08 21:47:2435// These classes serve as the basis of a profiler of sorts for the Tasks system.
36// As a result, design decisions were made to maximize speed, by minimizing
37// recurring allocation/deallocation, lock contention and data copying. In the
38// "stable" state, which is reached relatively quickly, there is no separate
39// marginal allocation cost associated with construction or destruction of
40// tracked objects, no locks are generally employed, and probably the largest
41// computational cost is associated with obtaining start and stop times for
[email protected]84b57952011-10-15 23:52:4542// instances as they are created and destroyed.
[email protected]75b79202009-12-30 07:31:4543//
44// The following describes the lifecycle of tracking an instance.
45//
46// First off, when the instance is created, the FROM_HERE macro is expanded
47// to specify the birth place (file, line, function) where the instance was
48// created. That data is used to create a transient Location instance
49// encapsulating the above triple of information. The strings (like __FILE__)
50// are passed around by reference, with the assumption that they are static, and
51// will never go away. This ensures that the strings can be dealt with as atoms
52// with great efficiency (i.e., copying of strings is never needed, and
53// comparisons for equality can be based on pointer comparisons).
54//
55// Next, a Births instance is created for use ONLY on the thread where this
56// instance was created. That Births instance records (in a base class
57// BirthOnThread) references to the static data provided in a Location instance,
58// as well as a pointer specifying the thread on which the birth takes place.
59// Hence there is at most one Births instance for each Location on each thread.
60// The derived Births class contains slots for recording statistics about all
61// instances born at the same location. Statistics currently include only the
62// count of instances constructed.
[email protected]84b57952011-10-15 23:52:4563//
[email protected]75b79202009-12-30 07:31:4564// Since the base class BirthOnThread contains only constant data, it can be
65// freely accessed by any thread at any time (i.e., only the statistic needs to
[email protected]84b57952011-10-15 23:52:4566// be handled carefully, and stats are updated exclusively on the birth thread).
[email protected]75b79202009-12-30 07:31:4567//
[email protected]c62dd9d2011-09-21 18:05:4168// For Tasks, having now either constructed or found the Births instance
69// described above, a pointer to the Births instance is then recorded into the
70// PendingTask structure in MessageLoop. This fact alone is very useful in
[email protected]75b79202009-12-30 07:31:4571// debugging, when there is a question of where an instance came from. In
[email protected]c62dd9d2011-09-21 18:05:4172// addition, the birth time is also recorded and used to later evaluate the
73// lifetime duration of the whole Task. As a result of the above embedding, we
74// can find out a Task's location of birth, and thread of birth, without using
75// any locks, as all that data is constant across the life of the process.
76//
[email protected]84b57952011-10-15 23:52:4577// The above work *could* also be done for any other object as well by calling
[email protected]b2a9bbd2011-10-31 22:36:2178// TallyABirthIfActive() and TallyRunOnNamedThreadIfTracking() as appropriate.
[email protected]75b79202009-12-30 07:31:4579//
80// The amount of memory used in the above data structures depends on how many
81// threads there are, and how many Locations of construction there are.
82// Fortunately, we don't use memory that is the product of those two counts, but
83// rather we only need one Births instance for each thread that constructs an
[email protected]c62dd9d2011-09-21 18:05:4184// instance at a Location. In many cases, instances are only created on one
85// thread, so the memory utilization is actually fairly restrained.
[email protected]75b79202009-12-30 07:31:4586//
87// Lastly, when an instance is deleted, the final tallies of statistics are
[email protected]c7dbf302011-11-08 07:57:0588// carefully accumulated. That tallying writes into slots (members) in a
[email protected]75b79202009-12-30 07:31:4589// collection of DeathData instances. For each birth place Location that is
90// destroyed on a thread, there is a DeathData instance to record the additional
[email protected]84b57952011-10-15 23:52:4591// death count, as well as accumulate the run-time and queue-time durations for
92// the instance as it is destroyed (dies). By maintaining a single place to
93// aggregate this running sum *only* for the given thread, we avoid the need to
94// lock such DeathData instances. (i.e., these accumulated stats in a DeathData
95// instance are exclusively updated by the singular owning thread).
[email protected]75b79202009-12-30 07:31:4596//
97// With the above lifecycle description complete, the major remaining detail is
98// explaining how each thread maintains a list of DeathData instances, and of
99// Births instances, and is able to avoid additional (redundant/unnecessary)
100// allocations.
101//
102// Each thread maintains a list of data items specific to that thread in a
103// ThreadData instance (for that specific thread only). The two critical items
104// are lists of DeathData and Births instances. These lists are maintained in
105// STL maps, which are indexed by Location. As noted earlier, we can compare
106// locations very efficiently as we consider the underlying data (file,
107// function, line) to be atoms, and hence pointer comparison is used rather than
108// (slow) string comparisons.
109//
110// To provide a mechanism for iterating over all "known threads," which means
111// threads that have recorded a birth or a death, we create a singly linked list
112// of ThreadData instances. Each such instance maintains a pointer to the next
[email protected]84baeca2011-10-24 18:55:16113// one. A static member of ThreadData provides a pointer to the first item on
114// this global list, and access via that all_thread_data_list_head_ item
115// requires the use of the list_lock_.
[email protected]75b79202009-12-30 07:31:45116// When new ThreadData instances is added to the global list, it is pre-pended,
117// which ensures that any prior acquisition of the list is valid (i.e., the
118// holder can iterate over it without fear of it changing, or the necessity of
119// using an additional lock. Iterations are actually pretty rare (used
120// primarilly for cleanup, or snapshotting data for display), so this lock has
121// very little global performance impact.
122//
123// The above description tries to define the high performance (run time)
124// portions of these classes. After gathering statistics, calls instigated
[email protected]dda97682011-11-14 05:24:07125// by visiting about:profiler will assemble and aggregate data for display. The
[email protected]75b79202009-12-30 07:31:45126// following data structures are used for producing such displays. They are
127// not performance critical, and their only major constraint is that they should
128// be able to run concurrently with ongoing augmentation of the birth and death
129// data.
130//
[email protected]c7dbf302011-11-08 07:57:05131// For a given birth location, information about births is spread across data
[email protected]75b79202009-12-30 07:31:45132// structures that are asynchronously changing on various threads. For display
133// purposes, we need to construct Snapshot instances for each combination of
134// birth thread, death thread, and location, along with the count of such
135// lifetimes. We gather such data into a Snapshot instances, so that such
136// instances can be sorted and aggregated (and remain frozen during our
137// processing). Snapshot instances use pointers to constant portions of the
138// birth and death datastructures, but have local (frozen) copies of the actual
139// statistics (birth count, durations, etc. etc.).
140//
[email protected]84b57952011-10-15 23:52:45141// A DataCollector is a container object that holds a set of Snapshots. The
142// statistics in a snapshot are gathered asynhcronously relative to their
[email protected]26cdeb962011-11-20 04:17:07143// ongoing updates. It is possible, though highly unlikely, that stats could be
144// incorrectly recorded by this process (all data is held in 32 bit ints, but we
145// are not atomically collecting all data, so we could have count that does not,
146// for example, match with the number of durations we accumulated). The
[email protected]c7dbf302011-11-08 07:57:05147// advantage to having fast (non-atomic) updates of the data outweighs the
148// minimal risk of a singular corrupt statistic snapshot (only the snapshot
149// could be corrupt, not the underlying and ongoing statistic). In constrast,
150// pointer data that is accessed during snapshotting is completely invariant,
151// and hence is perfectly acquired (i.e., no potential corruption, and no risk
152// of a bad memory reference).
[email protected]75b79202009-12-30 07:31:45153//
[email protected]c7dbf302011-11-08 07:57:05154// After an array of Snapshots instances are collected into a DataCollector,
155// they need to be prepared for displaying our output. We currently implement a
[email protected]26cdeb962011-11-20 04:17:07156// serialization into a Value hierarchy, which is automatically translated to
157// JSON when supplied to rendering Java Scirpt.
[email protected]75b79202009-12-30 07:31:45158//
[email protected]26cdeb962011-11-20 04:17:07159// TODO(jar): We can implement a Snapshot system that *tries* to grab the
160// snapshots on the source threads *when* they have MessageLoops available
161// (worker threads don't have message loops generally, and hence gathering from
162// them will continue to be asynchronous). We had an implementation of this in
163// the past, but the difficulty is dealing with message loops being terminated.
164// We can *try* to spam the available threads via some message loop proxy to
165// achieve this feat, and it *might* be valuable when we are colecting data for
166// upload via UMA (where correctness of data may be more significant than for a
167// single screen of about:profiler).
168//
[email protected]26cdeb962011-11-20 04:17:07169// TODO(jar): We should support (optionally) the recording of parent-child
170// relationships for tasks. This should be done by detecting what tasks are
171// Born during the running of a parent task. The resulting data can be used by
172// a smarter profiler to aggregate the cost of a series of child tasks into
173// the ancestor task. It can also be used to illuminate what child or parent is
174// related to each task.
175//
176// TODO(jar): We need to store DataCollections, and provide facilities for
177// taking the difference between two gathered DataCollections. For now, we're
178// just adding a hack that Reset()s to zero all counts and stats. This is also
[email protected]c7dbf302011-11-08 07:57:05179// done in a slighly thread-unsafe fashion, as the resetting is done
[email protected]eab79c382011-11-06 19:14:48180// asynchronously relative to ongoing updates (but all data is 32 bit in size).
181// For basic profiling, this will work "most of the time," and should be
[email protected]75b79202009-12-30 07:31:45182// sufficient... but storing away DataCollections is the "right way" to do this.
[email protected]eab79c382011-11-06 19:14:48183// We'll accomplish this via JavaScript storage of snapshots, and then we'll
[email protected]26cdeb962011-11-20 04:17:07184// remove the Reset() methods. We may also need a short-term-max value in
185// DeathData that is reset (as synchronously as possible) during each snapshot.
186// This will facilitate displaying a max value for each snapshot period.
initial.commitd7cae122008-07-26 21:49:38187
[email protected]c62dd9d2011-09-21 18:05:41188class MessageLoop;
[email protected]75b79202009-12-30 07:31:45189
initial.commitd7cae122008-07-26 21:49:38190namespace tracked_objects {
191
192//------------------------------------------------------------------------------
193// For a specific thread, and a specific birth place, the collection of all
194// death info (with tallies for each death thread, to prevent access conflicts).
195class ThreadData;
[email protected]0bea7252011-08-05 15:34:00196class BASE_EXPORT BirthOnThread {
initial.commitd7cae122008-07-26 21:49:38197 public:
[email protected]84baeca2011-10-24 18:55:16198 BirthOnThread(const Location& location, const ThreadData& current);
initial.commitd7cae122008-07-26 21:49:38199
[email protected]b6b2b892011-12-04 07:19:10200 const Location location() const;
201 const ThreadData* birth_thread() const;
initial.commitd7cae122008-07-26 21:49:38202
[email protected]8aa1e6e2011-12-14 01:36:48203 // Insert our state (location, and thread name) into the dictionary.
204 // Use the supplied |prefix| in front of "thread_name" and "location"
205 // respectively when defining keys.
206 void ToValue(const std::string& prefix,
207 base::DictionaryValue* dictionary) const;
208
initial.commitd7cae122008-07-26 21:49:38209 private:
[email protected]84b57952011-10-15 23:52:45210 // File/lineno of birth. This defines the essence of the task, as the context
initial.commitd7cae122008-07-26 21:49:38211 // of the birth (construction) often tell what the item is for. This field
212 // is const, and hence safe to access from any thread.
213 const Location location_;
214
215 // The thread that records births into this object. Only this thread is
[email protected]84baeca2011-10-24 18:55:16216 // allowed to update birth_count_ (which changes over time).
217 const ThreadData* const birth_thread_;
initial.commitd7cae122008-07-26 21:49:38218
[email protected]022614ef92008-12-30 20:50:01219 DISALLOW_COPY_AND_ASSIGN(BirthOnThread);
initial.commitd7cae122008-07-26 21:49:38220};
221
222//------------------------------------------------------------------------------
223// A class for accumulating counts of births (without bothering with a map<>).
224
[email protected]0bea7252011-08-05 15:34:00225class BASE_EXPORT Births: public BirthOnThread {
initial.commitd7cae122008-07-26 21:49:38226 public:
[email protected]84baeca2011-10-24 18:55:16227 Births(const Location& location, const ThreadData& current);
initial.commitd7cae122008-07-26 21:49:38228
[email protected]b6b2b892011-12-04 07:19:10229 int birth_count() const;
initial.commitd7cae122008-07-26 21:49:38230
231 // When we have a birth we update the count for this BirhPLace.
[email protected]b6b2b892011-12-04 07:19:10232 void RecordBirth();
initial.commitd7cae122008-07-26 21:49:38233
234 // When a birthplace is changed (updated), we need to decrement the counter
235 // for the old instance.
[email protected]b6b2b892011-12-04 07:19:10236 void ForgetBirth();
initial.commitd7cae122008-07-26 21:49:38237
[email protected]75b79202009-12-30 07:31:45238 // Hack to quickly reset all counts to zero.
[email protected]b6b2b892011-12-04 07:19:10239 void Clear();
[email protected]75b79202009-12-30 07:31:45240
initial.commitd7cae122008-07-26 21:49:38241 private:
242 // The number of births on this thread for our location_.
243 int birth_count_;
244
[email protected]022614ef92008-12-30 20:50:01245 DISALLOW_COPY_AND_ASSIGN(Births);
initial.commitd7cae122008-07-26 21:49:38246};
247
248//------------------------------------------------------------------------------
[email protected]b2a9bbd2011-10-31 22:36:21249// Basic info summarizing multiple destructions of a tracked object with a
250// single birthplace (fixed Location). Used both on specific threads, and also
initial.commitd7cae122008-07-26 21:49:38251// in snapshots when integrating assembled data.
252
[email protected]0bea7252011-08-05 15:34:00253class BASE_EXPORT DeathData {
initial.commitd7cae122008-07-26 21:49:38254 public:
255 // Default initializer.
[email protected]b6b2b892011-12-04 07:19:10256 DeathData();
initial.commitd7cae122008-07-26 21:49:38257
258 // When deaths have not yet taken place, and we gather data from all the
259 // threads, we create DeathData stats that tally the number of births without
[email protected]b6b2b892011-12-04 07:19:10260 // a corresponding death.
261 explicit DeathData(int count);
initial.commitd7cae122008-07-26 21:49:38262
[email protected]84b57952011-10-15 23:52:45263 // Update stats for a task destruction (death) that had a Run() time of
264 // |duration|, and has had a queueing delay of |queue_duration|.
[email protected]b6b2b892011-12-04 07:19:10265 void RecordDeath(const DurationInt queue_duration,
266 const DurationInt run_duration,
267 int random_number);
initial.commitd7cae122008-07-26 21:49:38268
[email protected]b6b2b892011-12-04 07:19:10269 // Metrics accessors, used only in tests.
270 int count() const;
271 DurationInt run_duration_sum() const;
272 DurationInt run_duration_max() const;
273 DurationInt run_duration_sample() const;
274 DurationInt queue_duration_sum() const;
275 DurationInt queue_duration_max() const;
276 DurationInt queue_duration_sample() const;
initial.commitd7cae122008-07-26 21:49:38277
[email protected]b2a9bbd2011-10-31 22:36:21278 // Construct a DictionaryValue instance containing all our stats. The caller
[email protected]84baeca2011-10-24 18:55:16279 // assumes ownership of the returned instance.
280 base::DictionaryValue* ToValue() const;
initial.commitd7cae122008-07-26 21:49:38281
[email protected]b6b2b892011-12-04 07:19:10282 // Reset the max values to zero.
283 void ResetMax();
284
[email protected]84b57952011-10-15 23:52:45285 // Reset all tallies to zero. This is used as a hack on realtime data.
initial.commitd7cae122008-07-26 21:49:38286 void Clear();
287
288 private:
[email protected]7ceb44482011-12-09 03:41:04289 // Members are ordered from most regularly read and updated, to least
290 // frequently used. This might help a bit with cache lines.
291 // Number of runs seen (divisor for calculating averages).
[email protected]b6b2b892011-12-04 07:19:10292 int count_;
[email protected]7ceb44482011-12-09 03:41:04293 // Basic tallies, used to compute averages.
[email protected]b6b2b892011-12-04 07:19:10294 DurationInt run_duration_sum_;
[email protected]b6b2b892011-12-04 07:19:10295 DurationInt queue_duration_sum_;
[email protected]7ceb44482011-12-09 03:41:04296 // Max values, used by local visualization routines. These are often read,
297 // but rarely updated.
298 DurationInt run_duration_max_;
[email protected]b6b2b892011-12-04 07:19:10299 DurationInt queue_duration_max_;
[email protected]7ceb44482011-12-09 03:41:04300 // Samples, used by by crowd sourcing gatherers. These are almost never read,
301 // and rarely updated.
302 DurationInt run_duration_sample_;
[email protected]b6b2b892011-12-04 07:19:10303 DurationInt queue_duration_sample_;
initial.commitd7cae122008-07-26 21:49:38304};
305
306//------------------------------------------------------------------------------
307// A temporary collection of data that can be sorted and summarized. It is
308// gathered (carefully) from many threads. Instances are held in arrays and
309// processed, filtered, and rendered.
310// The source of this data was collected on many threads, and is asynchronously
311// changing. The data in this instance is not asynchronously changing.
312
[email protected]0bea7252011-08-05 15:34:00313class BASE_EXPORT Snapshot {
initial.commitd7cae122008-07-26 21:49:38314 public:
315 // When snapshotting a full life cycle set (birth-to-death), use this:
[email protected]8aa1e6e2011-12-14 01:36:48316 Snapshot(const BirthOnThread& birth_on_thread,
317 const ThreadData& death_thread,
initial.commitd7cae122008-07-26 21:49:38318 const DeathData& death_data);
319
320 // When snapshotting a birth, with no death yet, use this:
321 Snapshot(const BirthOnThread& birth_on_thread, int count);
322
[email protected]b6b2b892011-12-04 07:19:10323 // Accessor, that provides default value when there is no death thread.
initial.commitd7cae122008-07-26 21:49:38324 const std::string DeathThreadName() const;
325
[email protected]84baeca2011-10-24 18:55:16326 // Construct a DictionaryValue instance containing all our data recursively.
327 // The caller assumes ownership of the memory in the returned instance.
328 base::DictionaryValue* ToValue() const;
initial.commitd7cae122008-07-26 21:49:38329
initial.commitd7cae122008-07-26 21:49:38330 private:
331 const BirthOnThread* birth_; // Includes Location and birth_thread.
332 const ThreadData* death_thread_;
333 DeathData death_data_;
334};
[email protected]84b57952011-10-15 23:52:45335
initial.commitd7cae122008-07-26 21:49:38336//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38337// For each thread, we have a ThreadData that stores all tracking info generated
338// on this thread. This prevents the need for locking as data accumulates.
[email protected]b2a9bbd2011-10-31 22:36:21339// We use ThreadLocalStorage to quickly identfy the current ThreadData context.
340// We also have a linked list of ThreadData instances, and that list is used to
341// harvest data from all existing instances.
initial.commitd7cae122008-07-26 21:49:38342
[email protected]0bea7252011-08-05 15:34:00343class BASE_EXPORT ThreadData {
initial.commitd7cae122008-07-26 21:49:38344 public:
[email protected]b2a9bbd2011-10-31 22:36:21345 // Current allowable states of the tracking system. The states can vary
346 // between ACTIVE and DEACTIVATED, but can never go back to UNINITIALIZED.
347 enum Status {
[email protected]8aa1e6e2011-12-14 01:36:48348 UNINITIALIZED, // PRistine, link-time state before running.
349 DORMANT_DURING_TESTS, // Only used during testing.
350 DEACTIVATED, // No longer recording profling.
351 PROFILING_ACTIVE, // Recording profiles (no parent-child links).
352 PROFILING_CHILDREN_ACTIVE, // Fully active, recording parent-child links.
[email protected]b2a9bbd2011-10-31 22:36:21353 };
354
initial.commitd7cae122008-07-26 21:49:38355 typedef std::map<Location, Births*> BirthMap;
356 typedef std::map<const Births*, DeathData> DeathMap;
[email protected]8aa1e6e2011-12-14 01:36:48357 typedef std::pair<const Births*, const Births*> ParentChildPair;
358 typedef std::set<ParentChildPair> ParentChildSet;
359 typedef std::stack<const Births*> ParentStack;
initial.commitd7cae122008-07-26 21:49:38360
[email protected]84b57952011-10-15 23:52:45361 // Initialize the current thread context with a new instance of ThreadData.
[email protected]b2a9bbd2011-10-31 22:36:21362 // This is used by all threads that have names, and should be explicitly
363 // set *before* any births on the threads have taken place. It is generally
364 // only used by the message loop, which has a well defined thread name.
[email protected]84b57952011-10-15 23:52:45365 static void InitializeThreadContext(const std::string& suggested_name);
initial.commitd7cae122008-07-26 21:49:38366
367 // Using Thread Local Store, find the current instance for collecting data.
368 // If an instance does not exist, construct one (and remember it for use on
369 // this thread.
[email protected]84baeca2011-10-24 18:55:16370 // This may return NULL if the system is disabled for any reason.
[email protected]84b57952011-10-15 23:52:45371 static ThreadData* Get();
initial.commitd7cae122008-07-26 21:49:38372
[email protected]b2a9bbd2011-10-31 22:36:21373 // Constructs a DictionaryValue instance containing all recursive results in
374 // our process. The caller assumes ownership of the memory in the returned
[email protected]b6b2b892011-12-04 07:19:10375 // instance. During the scavenging, if |reset_max| is true, then the
376 // DeathData instances max-values are reset to zero during this scan.
377 static base::DictionaryValue* ToValue(bool reset_max);
[email protected]b2a9bbd2011-10-31 22:36:21378
379 // Finds (or creates) a place to count births from the given location in this
[email protected]84baeca2011-10-24 18:55:16380 // thread, and increment that tally.
[email protected]180c85e2011-07-26 18:25:16381 // TallyABirthIfActive will returns NULL if the birth cannot be tallied.
382 static Births* TallyABirthIfActive(const Location& location);
[email protected]84b57952011-10-15 23:52:45383
[email protected]b2a9bbd2011-10-31 22:36:21384 // Records the end of a timed run of an object. The |completed_task| contains
385 // a pointer to a Births, the time_posted, and a delayed_start_time if any.
386 // The |start_of_run| indicates when we started to perform the run of the
387 // task. The delayed_start_time is non-null for tasks that were posted as
388 // delayed tasks, and it indicates when the task should have run (i.e., when
389 // it should have posted out of the timer queue, and into the work queue.
390 // The |end_of_run| was just obtained by a call to Now() (just after the task
391 // finished). It is provided as an argument to help with testing.
392 static void TallyRunOnNamedThreadIfTracking(
393 const base::TrackingInfo& completed_task,
394 const TrackedTime& start_of_run,
395 const TrackedTime& end_of_run);
396
[email protected]6b26b96012011-10-28 21:41:50397 // Record the end of a timed run of an object. The |birth| is the record for
[email protected]b2a9bbd2011-10-31 22:36:21398 // the instance, the |time_posted| records that instant, which is presumed to
399 // be when the task was posted into a queue to run on a worker thread.
400 // The |start_of_run| is when the worker thread started to perform the run of
401 // the task.
[email protected]84baeca2011-10-24 18:55:16402 // The |end_of_run| was just obtained by a call to Now() (just after the task
403 // finished).
[email protected]b2a9bbd2011-10-31 22:36:21404 static void TallyRunOnWorkerThreadIfTracking(
405 const Births* birth,
406 const TrackedTime& time_posted,
407 const TrackedTime& start_of_run,
408 const TrackedTime& end_of_run);
initial.commitd7cae122008-07-26 21:49:38409
[email protected]dbe5d2072011-11-08 17:09:21410 // Record the end of execution in region, generally corresponding to a scope
411 // being exited.
412 static void TallyRunInAScopedRegionIfTracking(
413 const Births* birth,
414 const TrackedTime& start_of_run,
415 const TrackedTime& end_of_run);
416
[email protected]b6b2b892011-12-04 07:19:10417 const std::string thread_name() const;
initial.commitd7cae122008-07-26 21:49:38418
[email protected]b6b2b892011-12-04 07:19:10419 // Snapshot (under a lock) copies of the maps in each ThreadData instance. For
[email protected]8aa1e6e2011-12-14 01:36:48420 // each set of maps (BirthMap, DeathMap, and ParentChildSet) call the Append()
421 // method of the |target| DataCollector. If |reset_max| is true, then the max
422 // values in each DeathData instance should be reset during the scan.
[email protected]b6b2b892011-12-04 07:19:10423 static void SendAllMaps(bool reset_max, class DataCollector* target);
initial.commitd7cae122008-07-26 21:49:38424
[email protected]75b79202009-12-30 07:31:45425 // Hack: asynchronously clear all birth counts and death tallies data values
426 // in all ThreadData instances. The numerical (zeroing) part is done without
427 // use of a locks or atomics exchanges, and may (for int64 values) produce
428 // bogus counts VERY rarely.
429 static void ResetAllThreadData();
430
[email protected]b2a9bbd2011-10-31 22:36:21431 // Initializes all statics if needed (this initialization call should be made
432 // while we are single threaded). Returns false if unable to initialize.
433 static bool Initialize();
434
[email protected]8aa1e6e2011-12-14 01:36:48435 // Sets internal status_.
436 // If |status| is false, then status_ is set to DEACTIVATED.
437 // If |status| is true, then status_ is set to, PROFILING_ACTIVE, or
438 // PROFILING_CHILDREN_ACTIVE.
[email protected]b2a9bbd2011-10-31 22:36:21439 // If tracking is not compiled in, this function will return false.
[email protected]8aa1e6e2011-12-14 01:36:48440 // If parent-child tracking is not compiled in, then an attempt to set the
441 // status to PROFILING_CHILDREN_ACTIVE will only result in a status of
442 // PROFILING_ACTIVE (i.e., it can't be set to a higher level than what is
443 // compiled into the binary, and parent-child tracking at the
444 // PROFILING_CHILDREN_ACTIVE level might not be compiled in).
[email protected]b2a9bbd2011-10-31 22:36:21445 static bool InitializeAndSetTrackingStatus(bool status);
[email protected]8aa1e6e2011-12-14 01:36:48446
447 // Indicate if any sort of profiling is being done (i.e., we are more than
448 // DEACTIVATED).
[email protected]b2a9bbd2011-10-31 22:36:21449 static bool tracking_status();
initial.commitd7cae122008-07-26 21:49:38450
[email protected]8aa1e6e2011-12-14 01:36:48451 // For testing only, indicate if the status of parent-child tracking is turned
452 // on. This is currently a compiled option, atop tracking_status().
453 static bool tracking_parent_child_status();
454
[email protected]dda97682011-11-14 05:24:07455 // Special versions of Now() for getting times at start and end of a tracked
456 // run. They are super fast when tracking is disabled, and have some internal
457 // side effects when we are tracking, so that we can deduce the amount of time
458 // accumulated outside of execution of tracked runs.
[email protected]8aa1e6e2011-12-14 01:36:48459 // The task that will be tracked is passed in as |parent| so that parent-child
460 // relationships can be (optionally) calculated.
461 static TrackedTime NowForStartOfRun(const Births* parent);
[email protected]dda97682011-11-14 05:24:07462 static TrackedTime NowForEndOfRun();
463
[email protected]84b57952011-10-15 23:52:45464 // Provide a time function that does nothing (runs fast) when we don't have
465 // the profiler enabled. It will generally be optimized away when it is
466 // ifdef'ed to be small enough (allowing the profiler to be "compiled out" of
467 // the code).
[email protected]b2a9bbd2011-10-31 22:36:21468 static TrackedTime Now();
initial.commitd7cae122008-07-26 21:49:38469
[email protected]9a88c902011-11-24 00:00:31470 // This function can be called at process termination to validate that thread
471 // cleanup routines have been called for at least some number of named
472 // threads.
473 static void EnsureCleanupWasCalled(int major_threads_shutdown_count);
474
initial.commitd7cae122008-07-26 21:49:38475 private:
[email protected]eab79c382011-11-06 19:14:48476 // Allow only tests to call ShutdownSingleThreadedCleanup. We NEVER call it
477 // in production code.
[email protected]b6b2b892011-12-04 07:19:10478 // TODO(jar): Make this a friend in DEBUG only, so that the optimizer has a
479 // better change of optimizing (inlining? etc.) private methods (knowing that
480 // there will be no need for an external entry point).
[email protected]eab79c382011-11-06 19:14:48481 friend class TrackedObjectsTest;
[email protected]b6b2b892011-12-04 07:19:10482 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, MinimalStartupShutdown);
483 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, TinyStartupShutdown);
[email protected]8aa1e6e2011-12-14 01:36:48484 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, ParentChildTest);
[email protected]eab79c382011-11-06 19:14:48485
[email protected]84baeca2011-10-24 18:55:16486 // Worker thread construction creates a name since there is none.
[email protected]26cdeb962011-11-20 04:17:07487 explicit ThreadData(int thread_number);
[email protected]445029fb2011-11-18 17:03:33488
[email protected]84baeca2011-10-24 18:55:16489 // Message loop based construction should provide a name.
490 explicit ThreadData(const std::string& suggested_name);
491
492 ~ThreadData();
493
494 // Push this instance to the head of all_thread_data_list_head_, linking it to
495 // the previous head. This is performed after each construction, and leaves
496 // the instance permanently on that list.
497 void PushToHeadOfList();
498
[email protected]b6b2b892011-12-04 07:19:10499 // (Thread safe) Get start of list of all ThreadData instances using the lock.
500 static ThreadData* first();
501
502 // Iterate through the null terminated list of ThreadData instances.
503 ThreadData* next() const;
504
505
[email protected]84baeca2011-10-24 18:55:16506 // In this thread's data, record a new birth.
507 Births* TallyABirth(const Location& location);
508
509 // Find a place to record a death on this thread.
510 void TallyADeath(const Births& birth,
[email protected]c25db182011-11-11 22:40:27511 DurationInt queue_duration,
512 DurationInt duration);
[email protected]84baeca2011-10-24 18:55:16513
[email protected]b6b2b892011-12-04 07:19:10514 // Using our lock, make a copy of the specified maps. This call may be made
515 // on non-local threads, which necessitate the use of the lock to prevent
516 // the map(s) from being reallocaed while they are copied. If |reset_max| is
517 // true, then, just after we copy the DeathMap, we will set the max values to
518 // zero in the active DeathMap (not the snapshot).
519 void SnapshotMaps(bool reset_max,
520 BirthMap* birth_map,
[email protected]8aa1e6e2011-12-14 01:36:48521 DeathMap* death_map,
522 ParentChildSet* parent_child_set);
[email protected]b6b2b892011-12-04 07:19:10523
[email protected]84baeca2011-10-24 18:55:16524 // Using our lock to protect the iteration, Clear all birth and death data.
525 void Reset();
526
527 // This method is called by the TLS system when a thread terminates.
528 // The argument may be NULL if this thread has never tracked a birth or death.
529 static void OnThreadTermination(void* thread_data);
530
531 // This method should be called when a worker thread terminates, so that we
532 // can save all the thread data into a cache of reusable ThreadData instances.
[email protected]26cdeb962011-11-20 04:17:07533 void OnThreadTerminationCleanup();
[email protected]84baeca2011-10-24 18:55:16534
[email protected]eab79c382011-11-06 19:14:48535 // Cleans up data structures, and returns statics to near pristine (mostly
536 // uninitialized) state. If there is any chance that other threads are still
537 // using the data structures, then the |leak| argument should be passed in as
538 // true, and the data structures (birth maps, death maps, ThreadData
539 // insntances, etc.) will be leaked and not deleted. If you have joined all
540 // threads since the time that InitializeAndSetTrackingStatus() was called,
541 // then you can pass in a |leak| value of false, and this function will
542 // delete recursively all data structures, starting with the list of
543 // ThreadData instances.
544 static void ShutdownSingleThreadedCleanup(bool leak);
545
initial.commitd7cae122008-07-26 21:49:38546 // We use thread local store to identify which ThreadData to interact with.
[email protected]1357c322010-12-30 22:18:56547 static base::ThreadLocalStorage::Slot tls_index_;
initial.commitd7cae122008-07-26 21:49:38548
[email protected]26cdeb962011-11-20 04:17:07549 // List of ThreadData instances for use with worker threads. When a worker
550 // thread is done (terminated), we push it onto this llist. When a new worker
551 // thread is created, we first try to re-use a ThreadData instance from the
552 // list, and if none are available, construct a new one.
553 // This is only accessed while list_lock_ is held.
554 static ThreadData* first_retired_worker_;
555
initial.commitd7cae122008-07-26 21:49:38556 // Link to the most recently created instance (starts a null terminated list).
[email protected]dda97682011-11-14 05:24:07557 // The list is traversed by about:profiler when it needs to snapshot data.
[email protected]b2a9bbd2011-10-31 22:36:21558 // This is only accessed while list_lock_ is held.
[email protected]84baeca2011-10-24 18:55:16559 static ThreadData* all_thread_data_list_head_;
[email protected]9a88c902011-11-24 00:00:31560
561 // The next available worker thread number. This should only be accessed when
562 // the list_lock_ is held.
563 static int worker_thread_data_creation_count_;
564
565 // The number of times TLS has called us back to cleanup a ThreadData
566 // instance. This is only accessed while list_lock_ is held.
567 static int cleanup_count_;
568
[email protected]b2a9bbd2011-10-31 22:36:21569 // Incarnation sequence number, indicating how many times (during unittests)
570 // we've either transitioned out of UNINITIALIZED, or into that state. This
571 // value is only accessed while the list_lock_ is held.
572 static int incarnation_counter_;
[email protected]9a88c902011-11-24 00:00:31573
[email protected]84baeca2011-10-24 18:55:16574 // Protection for access to all_thread_data_list_head_, and to
[email protected]b2a9bbd2011-10-31 22:36:21575 // unregistered_thread_data_pool_. This lock is leaked at shutdown.
[email protected]77169a62011-11-14 20:36:46576 // The lock is very infrequently used, so we can afford to just make a lazy
577 // instance and be safe.
578 static base::LazyInstance<base::Lock,
[email protected]9a88c902011-11-24 00:00:31579 base::LeakyLazyInstanceTraits<base::Lock> > list_lock_;
[email protected]b2a9bbd2011-10-31 22:36:21580
[email protected]84b57952011-10-15 23:52:45581 // We set status_ to SHUTDOWN when we shut down the tracking service.
initial.commitd7cae122008-07-26 21:49:38582 static Status status_;
583
584 // Link to next instance (null terminated list). Used to globally track all
585 // registered instances (corresponds to all registered threads where we keep
586 // data).
587 ThreadData* next_;
588
[email protected]26cdeb962011-11-20 04:17:07589 // Pointer to another ThreadData instance for a Worker-Thread that has been
590 // retired (its thread was terminated). This value is non-NULL only for a
591 // retired ThreadData associated with a Worker-Thread.
592 ThreadData* next_retired_worker_;
593
[email protected]84b57952011-10-15 23:52:45594 // The name of the thread that is being recorded. If this thread has no
595 // message_loop, then this is a worker thread, with a sequence number postfix.
596 std::string thread_name_;
initial.commitd7cae122008-07-26 21:49:38597
[email protected]84baeca2011-10-24 18:55:16598 // Indicate if this is a worker thread, and the ThreadData contexts should be
599 // stored in the unregistered_thread_data_pool_ when not in use.
[email protected]445029fb2011-11-18 17:03:33600 // Value is zero when it is not a worker thread. Value is a positive integer
601 // corresponding to the created thread name if it is a worker thread.
[email protected]26cdeb962011-11-20 04:17:07602 int worker_thread_number_;
[email protected]84baeca2011-10-24 18:55:16603
initial.commitd7cae122008-07-26 21:49:38604 // A map used on each thread to keep track of Births on this thread.
605 // This map should only be accessed on the thread it was constructed on.
606 // When a snapshot is needed, this structure can be locked in place for the
607 // duration of the snapshotting activity.
608 BirthMap birth_map_;
609
610 // Similar to birth_map_, this records informations about death of tracked
611 // instances (i.e., when a tracked instance was destroyed on this thread).
[email protected]75b79202009-12-30 07:31:45612 // It is locked before changing, and hence other threads may access it by
613 // locking before reading it.
initial.commitd7cae122008-07-26 21:49:38614 DeathMap death_map_;
615
[email protected]8aa1e6e2011-12-14 01:36:48616 // A set of parents that created children tasks on this thread. Each pair
617 // corresponds to potentially non-local Births (location and thread), and a
618 // local Births (that took place on this thread).
619 ParentChildSet parent_child_set_;
620
[email protected]75b79202009-12-30 07:31:45621 // Lock to protect *some* access to BirthMap and DeathMap. The maps are
622 // regularly read and written on this thread, but may only be read from other
623 // threads. To support this, we acquire this lock if we are writing from this
624 // thread, or reading from another thread. For reading from this thread we
625 // don't need a lock, as there is no potential for a conflict since the
626 // writing is only done from this thread.
[email protected]9a88c902011-11-24 00:00:31627 mutable base::Lock map_lock_;
initial.commitd7cae122008-07-26 21:49:38628
[email protected]8aa1e6e2011-12-14 01:36:48629 // The stack of parents that are currently being profiled. This includes only
630 // tasks that have started a timer recently via NowForStartOfRun(), but not
631 // yet concluded with a NowForEndOfRun(). Usually this stack is one deep, but
632 // if a scoped region is profiled, or <sigh> a task runs a nested-message
633 // loop, then the stack can grow larger. Note that we don't try to deduct
634 // time in nested porfiles, as our current timer is based on wall-clock time,
635 // and not CPU time (and we're hopeful that nested timing won't be a
636 // significant additional cost).
637 ParentStack parent_stack_;
638
[email protected]b6b2b892011-12-04 07:19:10639 // A random number that we used to select decide which sample to keep as a
640 // representative sample in each DeathData instance. We can't start off with
641 // much randomness (because we can't call RandInt() on all our threads), so
642 // we stir in more and more as we go.
643 int32 random_number_;
644
[email protected]8aa1e6e2011-12-14 01:36:48645 // Record of what the incarnation_counter_ was when this instance was created.
646 // If the incarnation_counter_ has changed, then we avoid pushing into the
647 // pool (this is only critical in tests which go through multiple
648 // incarnations).
649 int incarnation_count_for_pool_;
650
[email protected]022614ef92008-12-30 20:50:01651 DISALLOW_COPY_AND_ASSIGN(ThreadData);
initial.commitd7cae122008-07-26 21:49:38652};
653
[email protected]022614ef92008-12-30 20:50:01654//------------------------------------------------------------------------------
[email protected]b6b2b892011-12-04 07:19:10655// DataCollector is a container class for Snapshot and BirthOnThread count
656// items.
657
658class BASE_EXPORT DataCollector {
659 public:
660 typedef std::vector<Snapshot> Collection;
661
662 // Construct with a list of how many threads should contribute. This helps us
663 // determine (in the async case) when we are done with all contributions.
664 DataCollector();
665 ~DataCollector();
666
667 // Adds all stats from the indicated thread into our arrays. Accepts copies
668 // of the birth_map and death_map, so that the data will not change during the
669 // iterations and processing.
670 void Append(const ThreadData &thread_data,
[email protected]8aa1e6e2011-12-14 01:36:48671 const ThreadData::BirthMap& birth_map,
672 const ThreadData::DeathMap& death_map,
673 const ThreadData::ParentChildSet& parent_child_set);
[email protected]b6b2b892011-12-04 07:19:10674
675 // After the accumulation phase, the following accessor is used to process the
676 // data (i.e., sort it, filter it, etc.).
677 Collection* collection();
678
679 // Adds entries for all the remaining living objects (objects that have
680 // tallied a birth, but have not yet tallied a matching death, and hence must
681 // be either running, queued up, or being held in limbo for future posting).
682 // This should be called after all known ThreadData instances have been
683 // processed using Append().
684 void AddListOfLivingObjects();
685
[email protected]8aa1e6e2011-12-14 01:36:48686 // Generates a ListValue representation of the vector of snapshots, and
687 // inserts the results into |dictionary|.
688 void ToValue(base::DictionaryValue* dictionary) const;
[email protected]b6b2b892011-12-04 07:19:10689
690 private:
691 typedef std::map<const BirthOnThread*, int> BirthCount;
692
693 // The array that we collect data into.
694 Collection collection_;
695
696 // The total number of births recorded at each location for which we have not
697 // seen a death count. This map changes as we do Append() calls, and is later
698 // used by AddListOfLivingObjects() to gather up unaccounted for births.
699 BirthCount global_birth_count_;
700
[email protected]8aa1e6e2011-12-14 01:36:48701 // The complete list of parent-child relationships among tasks.
702 ThreadData::ParentChildSet parent_child_set_;
703
[email protected]b6b2b892011-12-04 07:19:10704 DISALLOW_COPY_AND_ASSIGN(DataCollector);
705};
706
707//------------------------------------------------------------------------------
[email protected]022614ef92008-12-30 20:50:01708// Provide simple way to to start global tracking, and to tear down tracking
[email protected]84baeca2011-10-24 18:55:16709// when done. The design has evolved to *not* do any teardown (and just leak
710// all allocated data structures). As a result, we don't have any code in this
711// destructor, and perhaps this whole class should go away.
[email protected]862aa2f02009-12-31 07:26:16712
[email protected]0bea7252011-08-05 15:34:00713class BASE_EXPORT AutoTracking {
[email protected]022614ef92008-12-30 20:50:01714 public:
[email protected]862aa2f02009-12-31 07:26:16715 AutoTracking() {
[email protected]b2a9bbd2011-10-31 22:36:21716 ThreadData::Initialize();
[email protected]862aa2f02009-12-31 07:26:16717 }
[email protected]022614ef92008-12-30 20:50:01718
719 ~AutoTracking() {
[email protected]b2a9bbd2011-10-31 22:36:21720 // TODO(jar): Consider emitting a CSV dump of the data at this point. This
721 // should be called after the message loops have all terminated (or at least
722 // the main message loop is gone), so there is little chance for additional
723 // tasks to be Run.
[email protected]022614ef92008-12-30 20:50:01724 }
725
726 private:
[email protected]862aa2f02009-12-31 07:26:16727
[email protected]022614ef92008-12-30 20:50:01728 DISALLOW_COPY_AND_ASSIGN(AutoTracking);
729};
730
initial.commitd7cae122008-07-26 21:49:38731} // namespace tracked_objects
732
733#endif // BASE_TRACKED_OBJECTS_H_