1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/metrics/stats_table.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/memory/shared_memory.h"
10 #include "base/process/process_handle.h"
11 #include "base/strings/string_piece.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/platform_thread.h"
15 #include "base/threading/thread_local_storage.h"
18 #include "base/posix/global_descriptors.h"
20 #include "ipc/ipc_descriptors.h"
25 // The StatsTable uses a shared memory segment that is laid out as follows
27 // +-------------------------------------------+
28 // | Version | Size | MaxCounters | MaxThreads |
29 // +-------------------------------------------+
30 // | Thread names table |
31 // +-------------------------------------------+
32 // | Thread TID table |
33 // +-------------------------------------------+
34 // | Thread PID table |
35 // +-------------------------------------------+
36 // | Counter names table |
37 // +-------------------------------------------+
39 // +-------------------------------------------+
41 // The data layout is a grid, where the columns are the thread_ids and the
42 // rows are the counter_ids.
44 // If the first character of the thread_name is '\0', then that column is
46 // If the first character of the counter_name is '\0', then that row is
50 // This class is designed to be both multi-thread and multi-process safe.
51 // Aside from initialization, this is done by partitioning the data which
52 // each thread uses so that no locking is required. However, to allocate
53 // the rows and columns of the table to particular threads, locking is
56 // At the shared-memory level, we have a lock. This lock protects the
57 // shared-memory table only, and is used when we create new counters (e.g.
58 // use rows) or when we register new threads (e.g. use columns). Reading
59 // data from the table does not require any locking at the shared memory
62 // Each process which accesses the table will create a StatsTable object.
63 // The StatsTable maintains a hash table of the existing counters in the
64 // table for faster lookup. Since the hash table is process specific,
65 // each process maintains its own cache. We avoid complexity here by never
66 // de-allocating from the hash table. (Counters are dynamically added,
67 // but not dynamically removed).
69 // In order for external viewers to be able to read our shared memory,
70 // we all need to use the same size ints.
71 COMPILE_ASSERT(sizeof(int)==4, expect_4_byte_ints
);
75 // An internal version in case we ever change the format of this
76 // file, and so that we can identify our table.
77 const int kTableVersion
= 0x13131313;
79 // The name for un-named counters and threads in the table.
80 const char kUnknownName
[] = "<unknown>";
82 // Calculates delta to align an offset to the size of an int
83 inline int AlignOffset(int offset
) {
84 return (sizeof(int) - (offset
% sizeof(int))) % sizeof(int);
87 inline int AlignedSize(int size
) {
88 return size
+ AlignOffset(size
);
93 // The StatsTable::Internal maintains convenience pointers into the
94 // shared memory segment. Use this class to keep the data structure
95 // clean and accessible.
96 class StatsTable::Internal
{
98 // Various header information contained in the memory mapped segment.
106 // Construct a new Internal based on expected size parameters, or
107 // return NULL on failure.
108 static Internal
* New(const std::string
& name
,
113 SharedMemory
* shared_memory() { return shared_memory_
.get(); }
115 // Accessors for our header pointers
116 TableHeader
* table_header() const { return table_header_
; }
117 int version() const { return table_header_
->version
; }
118 int size() const { return table_header_
->size
; }
119 int max_counters() const { return table_header_
->max_counters
; }
120 int max_threads() const { return table_header_
->max_threads
; }
122 // Accessors for our tables
123 char* thread_name(int slot_id
) const {
124 return &thread_names_table_
[
125 (slot_id
-1) * (StatsTable::kMaxThreadNameLength
)];
127 PlatformThreadId
* thread_tid(int slot_id
) const {
128 return &(thread_tid_table_
[slot_id
-1]);
130 int* thread_pid(int slot_id
) const {
131 return &(thread_pid_table_
[slot_id
-1]);
133 char* counter_name(int counter_id
) const {
134 return &counter_names_table_
[
135 (counter_id
-1) * (StatsTable::kMaxCounterNameLength
)];
137 int* row(int counter_id
) const {
138 return &data_table_
[(counter_id
-1) * max_threads()];
142 // Constructor is private because you should use New() instead.
143 explicit Internal(SharedMemory
* shared_memory
)
144 : shared_memory_(shared_memory
),
146 thread_names_table_(NULL
),
147 thread_tid_table_(NULL
),
148 thread_pid_table_(NULL
),
149 counter_names_table_(NULL
),
153 // Create or open the SharedMemory used by the stats table.
154 static SharedMemory
* CreateSharedMemory(const std::string
& name
,
157 // Initializes the table on first access. Sets header values
158 // appropriately and zeroes all counters.
159 void InitializeTable(void* memory
, int size
, int max_counters
,
162 // Initializes our in-memory pointers into a pre-created StatsTable.
163 void ComputeMappedPointers(void* memory
);
165 scoped_ptr
<SharedMemory
> shared_memory_
;
166 TableHeader
* table_header_
;
167 char* thread_names_table_
;
168 PlatformThreadId
* thread_tid_table_
;
169 int* thread_pid_table_
;
170 char* counter_names_table_
;
173 DISALLOW_COPY_AND_ASSIGN(Internal
);
177 StatsTable::Internal
* StatsTable::Internal::New(const std::string
& name
,
181 scoped_ptr
<SharedMemory
> shared_memory(CreateSharedMemory(name
, size
));
182 if (!shared_memory
.get())
184 if (!shared_memory
->Map(size
))
186 void* memory
= shared_memory
->memory();
188 scoped_ptr
<Internal
> internal(new Internal(shared_memory
.release()));
189 TableHeader
* header
= static_cast<TableHeader
*>(memory
);
191 // If the version does not match, then assume the table needs
192 // to be initialized.
193 if (header
->version
!= kTableVersion
)
194 internal
->InitializeTable(memory
, size
, max_counters
, max_threads
);
196 // We have a valid table, so compute our pointers.
197 internal
->ComputeMappedPointers(memory
);
199 return internal
.release();
203 SharedMemory
* StatsTable::Internal::CreateSharedMemory(const std::string
& name
,
205 #if defined(OS_POSIX)
206 GlobalDescriptors
* global_descriptors
= GlobalDescriptors::GetInstance();
207 if (global_descriptors
->MaybeGet(kStatsTableSharedMemFd
) != -1) {
208 // Open the shared memory file descriptor passed by the browser process.
209 FileDescriptor
file_descriptor(
210 global_descriptors
->Get(kStatsTableSharedMemFd
), false);
211 return new SharedMemory(file_descriptor
, false);
213 // Otherwise we need to create it.
214 scoped_ptr
<SharedMemory
> shared_memory(new SharedMemory());
215 if (!shared_memory
->CreateAnonymous(size
))
217 return shared_memory
.release();
218 #elif defined(OS_WIN)
219 scoped_ptr
<SharedMemory
> shared_memory(new SharedMemory());
220 if (!shared_memory
->CreateNamed(name
, true, size
))
222 return shared_memory
.release();
226 void StatsTable::Internal::InitializeTable(void* memory
, int size
,
230 memset(memory
, 0, size
);
232 // Initialize the header.
233 TableHeader
* header
= static_cast<TableHeader
*>(memory
);
234 header
->version
= kTableVersion
;
236 header
->max_counters
= max_counters
;
237 header
->max_threads
= max_threads
;
240 void StatsTable::Internal::ComputeMappedPointers(void* memory
) {
241 char* data
= static_cast<char*>(memory
);
244 table_header_
= reinterpret_cast<TableHeader
*>(data
);
245 offset
+= sizeof(*table_header_
);
246 offset
+= AlignOffset(offset
);
248 // Verify we're looking at a valid StatsTable.
249 DCHECK_EQ(table_header_
->version
, kTableVersion
);
251 thread_names_table_
= reinterpret_cast<char*>(data
+ offset
);
252 offset
+= sizeof(char) *
253 max_threads() * StatsTable::kMaxThreadNameLength
;
254 offset
+= AlignOffset(offset
);
256 thread_tid_table_
= reinterpret_cast<PlatformThreadId
*>(data
+ offset
);
257 offset
+= sizeof(int) * max_threads();
258 offset
+= AlignOffset(offset
);
260 thread_pid_table_
= reinterpret_cast<int*>(data
+ offset
);
261 offset
+= sizeof(int) * max_threads();
262 offset
+= AlignOffset(offset
);
264 counter_names_table_
= reinterpret_cast<char*>(data
+ offset
);
265 offset
+= sizeof(char) *
266 max_counters() * StatsTable::kMaxCounterNameLength
;
267 offset
+= AlignOffset(offset
);
269 data_table_
= reinterpret_cast<int*>(data
+ offset
);
270 offset
+= sizeof(int) * max_threads() * max_counters();
272 DCHECK_EQ(offset
, size());
275 // TLSData carries the data stored in the TLS slots for the
276 // StatsTable. This is used so that we can properly cleanup when the
277 // thread exits and return the table slot.
279 // Each thread that calls RegisterThread in the StatsTable will have
280 // a TLSData stored in its TLS.
281 struct StatsTable::TLSData
{
286 // We keep a singleton table which can be easily accessed.
287 StatsTable
* global_table
= NULL
;
289 StatsTable::StatsTable(const std::string
& name
, int max_threads
,
292 tls_index_(SlotReturnFunction
) {
294 AlignedSize(sizeof(Internal::TableHeader
)) +
295 AlignedSize((max_counters
* sizeof(char) * kMaxCounterNameLength
)) +
296 AlignedSize((max_threads
* sizeof(char) * kMaxThreadNameLength
)) +
297 AlignedSize(max_threads
* sizeof(int)) +
298 AlignedSize(max_threads
* sizeof(int)) +
299 AlignedSize((sizeof(int) * (max_counters
* max_threads
)));
301 internal_
= Internal::New(name
, table_size
, max_threads
, max_counters
);
304 DPLOG(ERROR
) << "StatsTable did not initialize";
307 StatsTable::~StatsTable() {
308 // Before we tear down our copy of the table, be sure to
309 // unregister our thread.
312 // Return ThreadLocalStorage. At this point, if any registered threads
313 // still exist, they cannot Unregister.
316 // Cleanup our shared memory.
319 // If we are the global table, unregister ourselves.
320 if (global_table
== this)
324 StatsTable
* StatsTable::current() {
328 void StatsTable::set_current(StatsTable
* value
) {
329 global_table
= value
;
332 int StatsTable::GetSlot() const {
333 TLSData
* data
= GetTLSData();
339 int StatsTable::RegisterThread(const std::string
& name
) {
344 // Registering a thread requires that we lock the shared memory
345 // so that two threads don't grab the same slot. Fortunately,
346 // thread creation shouldn't happen in inner loops.
348 SharedMemoryAutoLock
lock(internal_
->shared_memory());
349 slot
= FindEmptyThread();
354 // We have space, so consume a column in the table.
355 std::string thread_name
= name
;
357 thread_name
= kUnknownName
;
358 strlcpy(internal_
->thread_name(slot
), thread_name
.c_str(),
359 kMaxThreadNameLength
);
360 *(internal_
->thread_tid(slot
)) = PlatformThread::CurrentId();
361 *(internal_
->thread_pid(slot
)) = GetCurrentProcId();
364 // Set our thread local storage.
365 TLSData
* data
= new TLSData
;
368 tls_index_
.Set(data
);
372 int StatsTable::CountThreadsRegistered() const {
376 // Loop through the shared memory and count the threads that are active.
377 // We intentionally do not lock the table during the operation.
379 for (int index
= 1; index
<= internal_
->max_threads(); index
++) {
380 char* name
= internal_
->thread_name(index
);
387 int StatsTable::FindCounter(const std::string
& name
) {
388 // Note: the API returns counters numbered from 1..N, although
389 // internally, the array is 0..N-1. This is so that we can return
390 // zero as "not found".
394 // Create a scope for our auto-lock.
396 AutoLock
scoped_lock(counters_lock_
);
398 // Attempt to find the counter.
399 CountersMap::const_iterator iter
;
400 iter
= counters_
.find(name
);
401 if (iter
!= counters_
.end())
405 // Counter does not exist, so add it.
406 return AddCounter(name
);
409 int* StatsTable::GetLocation(int counter_id
, int slot_id
) const {
412 if (slot_id
> internal_
->max_threads())
415 int* row
= internal_
->row(counter_id
);
416 return &(row
[slot_id
-1]);
419 const char* StatsTable::GetRowName(int index
) const {
423 return internal_
->counter_name(index
);
426 int StatsTable::GetRowValue(int index
) const {
427 return GetRowValue(index
, 0);
430 int StatsTable::GetRowValue(int index
, int pid
) const {
435 int* row
= internal_
->row(index
);
436 for (int slot_id
= 1; slot_id
<= internal_
->max_threads(); slot_id
++) {
437 if (pid
== 0 || *internal_
->thread_pid(slot_id
) == pid
)
438 rv
+= row
[slot_id
-1];
443 int StatsTable::GetCounterValue(const std::string
& name
) {
444 return GetCounterValue(name
, 0);
447 int StatsTable::GetCounterValue(const std::string
& name
, int pid
) {
451 int row
= FindCounter(name
);
454 return GetRowValue(row
, pid
);
457 int StatsTable::GetMaxCounters() const {
460 return internal_
->max_counters();
463 int StatsTable::GetMaxThreads() const {
466 return internal_
->max_threads();
469 int* StatsTable::FindLocation(const char* name
) {
470 // Get the static StatsTable
471 StatsTable
*table
= StatsTable::current();
475 // Get the slot for this thread. Try to register
476 // it if none exists.
477 int slot
= table
->GetSlot();
478 if (!slot
&& !(slot
= table
->RegisterThread(std::string())))
481 // Find the counter id for the counter.
482 std::string
str_name(name
);
483 int counter
= table
->FindCounter(str_name
);
485 // Now we can find the location in the table.
486 return table
->GetLocation(counter
, slot
);
489 void StatsTable::UnregisterThread() {
490 UnregisterThread(GetTLSData());
493 void StatsTable::UnregisterThread(TLSData
* data
) {
498 // Mark the slot free by zeroing out the thread name.
499 char* name
= internal_
->thread_name(data
->slot
);
502 // Remove the calling thread's TLS so that it cannot use the slot.
503 tls_index_
.Set(NULL
);
507 void StatsTable::SlotReturnFunction(void* data
) {
508 // This is called by the TLS destructor, which on some platforms has
509 // already cleared the TLS info, so use the tls_data argument
510 // rather than trying to fetch it ourselves.
511 TLSData
* tls_data
= static_cast<TLSData
*>(data
);
513 DCHECK(tls_data
->table
);
514 tls_data
->table
->UnregisterThread(tls_data
);
518 int StatsTable::FindEmptyThread() const {
519 // Note: the API returns slots numbered from 1..N, although
520 // internally, the array is 0..N-1. This is so that we can return
521 // zero as "not found".
523 // The reason for doing this is because the thread 'slot' is stored
524 // in TLS, which is always initialized to zero, not -1. If 0 were
525 // returned as a valid slot number, it would be confused with the
526 // uninitialized state.
531 for (; index
<= internal_
->max_threads(); index
++) {
532 char* name
= internal_
->thread_name(index
);
536 if (index
> internal_
->max_threads())
537 return 0; // The table is full.
541 int StatsTable::FindCounterOrEmptyRow(const std::string
& name
) const {
542 // Note: the API returns slots numbered from 1..N, although
543 // internally, the array is 0..N-1. This is so that we can return
544 // zero as "not found".
546 // There isn't much reason for this other than to be consistent
547 // with the way we track columns for thread slots. (See comments
548 // in FindEmptyThread for why it is done this way).
553 for (int index
= 1; index
<= internal_
->max_counters(); index
++) {
554 char* row_name
= internal_
->counter_name(index
);
555 if (!*row_name
&& !free_slot
)
556 free_slot
= index
; // save that we found a free slot
557 else if (!strncmp(row_name
, name
.c_str(), kMaxCounterNameLength
))
563 int StatsTable::AddCounter(const std::string
& name
) {
569 // To add a counter to the shared memory, we need the
570 // shared memory lock.
571 SharedMemoryAutoLock
lock(internal_
->shared_memory());
573 // We have space, so create a new counter.
574 counter_id
= FindCounterOrEmptyRow(name
);
578 std::string counter_name
= name
;
580 counter_name
= kUnknownName
;
581 strlcpy(internal_
->counter_name(counter_id
), counter_name
.c_str(),
582 kMaxCounterNameLength
);
585 // now add to our in-memory cache
587 AutoLock
lock(counters_lock_
);
588 counters_
[name
] = counter_id
;
593 StatsTable::TLSData
* StatsTable::GetTLSData() const {
595 static_cast<TLSData
*>(tls_index_
.Get());
600 DCHECK_EQ(data
->table
, this);
604 #if defined(OS_POSIX)
605 SharedMemoryHandle
StatsTable::GetSharedMemoryHandle() const {
607 return SharedMemory::NULLHandle();
608 return internal_
->shared_memory()->handle();