Replace command buffer FlushSync with WaitForTokenInRange and WaitForGetOffsetInRange
[chromium-blink-merge.git] / base / metrics / stats_table.cc
blobf09e736b92ab9fdbe1a7e22c2ef8c982f5725e8d
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"
17 #if defined(OS_POSIX)
18 #include "base/posix/global_descriptors.h"
19 #include "errno.h"
20 #include "ipc/ipc_descriptors.h"
21 #endif
23 namespace base {
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 // +-------------------------------------------+
38 // | Data |
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
45 // empty.
46 // If the first character of the counter_name is '\0', then that row is
47 // empty.
49 // About Locking:
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
54 // required.
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
60 // level.
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);
73 namespace {
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);
91 } // namespace
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 {
97 public:
98 // Various header information contained in the memory mapped segment.
99 struct TableHeader {
100 int version;
101 int size;
102 int max_counters;
103 int max_threads;
106 // Construct a new Internal based on expected size parameters, or
107 // return NULL on failure.
108 static Internal* New(const std::string& name,
109 int size,
110 int max_threads,
111 int max_counters);
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()];
141 private:
142 // Constructor is private because you should use New() instead.
143 explicit Internal(SharedMemory* shared_memory)
144 : shared_memory_(shared_memory),
145 table_header_(NULL),
146 thread_names_table_(NULL),
147 thread_tid_table_(NULL),
148 thread_pid_table_(NULL),
149 counter_names_table_(NULL),
150 data_table_(NULL) {
153 // Create or open the SharedMemory used by the stats table.
154 static SharedMemory* CreateSharedMemory(const std::string& name,
155 int size);
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,
160 int max_threads);
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_;
171 int* data_table_;
173 DISALLOW_COPY_AND_ASSIGN(Internal);
176 // static
177 StatsTable::Internal* StatsTable::Internal::New(const std::string& name,
178 int size,
179 int max_threads,
180 int max_counters) {
181 scoped_ptr<SharedMemory> shared_memory(CreateSharedMemory(name, size));
182 if (!shared_memory.get())
183 return NULL;
184 if (!shared_memory->Map(size))
185 return NULL;
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();
202 // static
203 SharedMemory* StatsTable::Internal::CreateSharedMemory(const std::string& name,
204 int size) {
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))
216 return NULL;
217 return shared_memory.release();
218 #elif defined(OS_WIN)
219 scoped_ptr<SharedMemory> shared_memory(new SharedMemory());
220 if (!shared_memory->CreateNamedDeprecated(name, true, size))
221 return NULL;
222 return shared_memory.release();
223 #endif
226 void StatsTable::Internal::InitializeTable(void* memory, int size,
227 int max_counters,
228 int max_threads) {
229 // Zero everything.
230 memset(memory, 0, size);
232 // Initialize the header.
233 TableHeader* header = static_cast<TableHeader*>(memory);
234 header->version = kTableVersion;
235 header->size = size;
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);
242 int offset = 0;
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 {
282 StatsTable* table;
283 int slot;
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,
290 int max_counters)
291 : internal_(NULL),
292 tls_index_(SlotReturnFunction) {
293 int table_size =
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);
303 if (!internal_)
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.
310 UnregisterThread();
312 // Return ThreadLocalStorage. At this point, if any registered threads
313 // still exist, they cannot Unregister.
314 tls_index_.Free();
316 // Cleanup our shared memory.
317 delete internal_;
319 // If we are the global table, unregister ourselves.
320 if (global_table == this)
321 global_table = NULL;
324 StatsTable* StatsTable::current() {
325 return global_table;
328 void StatsTable::set_current(StatsTable* value) {
329 global_table = value;
332 int StatsTable::GetSlot() const {
333 TLSData* data = GetTLSData();
334 if (!data)
335 return 0;
336 return data->slot;
339 int StatsTable::RegisterThread(const std::string& name) {
340 int slot = 0;
341 if (!internal_)
342 return 0;
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.
347 // TODO(viettrungluu): crbug.com/345734: Use a different locking mechanism.
349 SharedMemoryAutoLockDeprecated lock(internal_->shared_memory());
350 slot = FindEmptyThread();
351 if (!slot) {
352 return 0;
355 // We have space, so consume a column in the table.
356 std::string thread_name = name;
357 if (name.empty())
358 thread_name = kUnknownName;
359 strlcpy(internal_->thread_name(slot), thread_name.c_str(),
360 kMaxThreadNameLength);
361 *(internal_->thread_tid(slot)) = PlatformThread::CurrentId();
362 *(internal_->thread_pid(slot)) = GetCurrentProcId();
365 // Set our thread local storage.
366 TLSData* data = new TLSData;
367 data->table = this;
368 data->slot = slot;
369 tls_index_.Set(data);
370 return slot;
373 int StatsTable::CountThreadsRegistered() const {
374 if (!internal_)
375 return 0;
377 // Loop through the shared memory and count the threads that are active.
378 // We intentionally do not lock the table during the operation.
379 int count = 0;
380 for (int index = 1; index <= internal_->max_threads(); index++) {
381 char* name = internal_->thread_name(index);
382 if (*name != '\0')
383 count++;
385 return count;
388 int StatsTable::FindCounter(const std::string& name) {
389 // Note: the API returns counters numbered from 1..N, although
390 // internally, the array is 0..N-1. This is so that we can return
391 // zero as "not found".
392 if (!internal_)
393 return 0;
395 // Create a scope for our auto-lock.
397 AutoLock scoped_lock(counters_lock_);
399 // Attempt to find the counter.
400 CountersMap::const_iterator iter;
401 iter = counters_.find(name);
402 if (iter != counters_.end())
403 return iter->second;
406 // Counter does not exist, so add it.
407 return AddCounter(name);
410 int* StatsTable::GetLocation(int counter_id, int slot_id) const {
411 if (!internal_)
412 return NULL;
413 if (slot_id > internal_->max_threads())
414 return NULL;
416 int* row = internal_->row(counter_id);
417 return &(row[slot_id-1]);
420 const char* StatsTable::GetRowName(int index) const {
421 if (!internal_)
422 return NULL;
424 return internal_->counter_name(index);
427 int StatsTable::GetRowValue(int index) const {
428 return GetRowValue(index, 0);
431 int StatsTable::GetRowValue(int index, int pid) const {
432 if (!internal_)
433 return 0;
435 int rv = 0;
436 int* row = internal_->row(index);
437 for (int slot_id = 1; slot_id <= internal_->max_threads(); slot_id++) {
438 if (pid == 0 || *internal_->thread_pid(slot_id) == pid)
439 rv += row[slot_id-1];
441 return rv;
444 int StatsTable::GetCounterValue(const std::string& name) {
445 return GetCounterValue(name, 0);
448 int StatsTable::GetCounterValue(const std::string& name, int pid) {
449 if (!internal_)
450 return 0;
452 int row = FindCounter(name);
453 if (!row)
454 return 0;
455 return GetRowValue(row, pid);
458 int StatsTable::GetMaxCounters() const {
459 if (!internal_)
460 return 0;
461 return internal_->max_counters();
464 int StatsTable::GetMaxThreads() const {
465 if (!internal_)
466 return 0;
467 return internal_->max_threads();
470 int* StatsTable::FindLocation(const char* name) {
471 // Get the static StatsTable
472 StatsTable *table = StatsTable::current();
473 if (!table)
474 return NULL;
476 // Get the slot for this thread. Try to register
477 // it if none exists.
478 int slot = table->GetSlot();
479 if (!slot && !(slot = table->RegisterThread(std::string())))
480 return NULL;
482 // Find the counter id for the counter.
483 std::string str_name(name);
484 int counter = table->FindCounter(str_name);
486 // Now we can find the location in the table.
487 return table->GetLocation(counter, slot);
490 void StatsTable::UnregisterThread() {
491 UnregisterThread(GetTLSData());
494 void StatsTable::UnregisterThread(TLSData* data) {
495 if (!data)
496 return;
497 DCHECK(internal_);
499 // Mark the slot free by zeroing out the thread name.
500 char* name = internal_->thread_name(data->slot);
501 *name = '\0';
503 // Remove the calling thread's TLS so that it cannot use the slot.
504 tls_index_.Set(NULL);
505 delete data;
508 void StatsTable::SlotReturnFunction(void* data) {
509 // This is called by the TLS destructor, which on some platforms has
510 // already cleared the TLS info, so use the tls_data argument
511 // rather than trying to fetch it ourselves.
512 TLSData* tls_data = static_cast<TLSData*>(data);
513 if (tls_data) {
514 DCHECK(tls_data->table);
515 tls_data->table->UnregisterThread(tls_data);
519 int StatsTable::FindEmptyThread() const {
520 // Note: the API returns slots numbered from 1..N, although
521 // internally, the array is 0..N-1. This is so that we can return
522 // zero as "not found".
524 // The reason for doing this is because the thread 'slot' is stored
525 // in TLS, which is always initialized to zero, not -1. If 0 were
526 // returned as a valid slot number, it would be confused with the
527 // uninitialized state.
528 if (!internal_)
529 return 0;
531 int index = 1;
532 for (; index <= internal_->max_threads(); index++) {
533 char* name = internal_->thread_name(index);
534 if (!*name)
535 break;
537 if (index > internal_->max_threads())
538 return 0; // The table is full.
539 return index;
542 int StatsTable::FindCounterOrEmptyRow(const std::string& name) const {
543 // Note: the API returns slots numbered from 1..N, although
544 // internally, the array is 0..N-1. This is so that we can return
545 // zero as "not found".
547 // There isn't much reason for this other than to be consistent
548 // with the way we track columns for thread slots. (See comments
549 // in FindEmptyThread for why it is done this way).
550 if (!internal_)
551 return 0;
553 int free_slot = 0;
554 for (int index = 1; index <= internal_->max_counters(); index++) {
555 char* row_name = internal_->counter_name(index);
556 if (!*row_name && !free_slot)
557 free_slot = index; // save that we found a free slot
558 else if (!strncmp(row_name, name.c_str(), kMaxCounterNameLength))
559 return index;
561 return free_slot;
564 int StatsTable::AddCounter(const std::string& name) {
565 if (!internal_)
566 return 0;
568 int counter_id = 0;
570 // To add a counter to the shared memory, we need the
571 // shared memory lock.
572 SharedMemoryAutoLockDeprecated lock(internal_->shared_memory());
574 // We have space, so create a new counter.
575 counter_id = FindCounterOrEmptyRow(name);
576 if (!counter_id)
577 return 0;
579 std::string counter_name = name;
580 if (name.empty())
581 counter_name = kUnknownName;
582 strlcpy(internal_->counter_name(counter_id), counter_name.c_str(),
583 kMaxCounterNameLength);
586 // now add to our in-memory cache
588 AutoLock lock(counters_lock_);
589 counters_[name] = counter_id;
591 return counter_id;
594 StatsTable::TLSData* StatsTable::GetTLSData() const {
595 TLSData* data =
596 static_cast<TLSData*>(tls_index_.Get());
597 if (!data)
598 return NULL;
600 DCHECK(data->slot);
601 DCHECK_EQ(data->table, this);
602 return data;
605 #if defined(OS_POSIX)
606 SharedMemoryHandle StatsTable::GetSharedMemoryHandle() const {
607 if (!internal_)
608 return SharedMemory::NULLHandle();
609 return internal_->shared_memory()->handle();
611 #endif
613 } // namespace base