Home | History | Annotate | Download | only in metrics
      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.
      4 
      5 #include "base/metrics/stats_table.h"
      6 
      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"
     16 
     17 #if defined(OS_POSIX)
     18 #include "base/posix/global_descriptors.h"
     19 #include "errno.h"
     20 #include "ipc/ipc_descriptors.h"
     21 #endif
     22 
     23 namespace base {
     24 
     25 // The StatsTable uses a shared memory segment that is laid out as follows
     26 //
     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 // +-------------------------------------------+
     40 //
     41 // The data layout is a grid, where the columns are the thread_ids and the
     42 // rows are the counter_ids.
     43 //
     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.
     48 //
     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.
     55 //
     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.
     61 //
     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).
     68 
     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);
     72 
     73 namespace {
     74 
     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;
     78 
     79 // The name for un-named counters and threads in the table.
     80 const char kUnknownName[] = "<unknown>";
     81 
     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);
     85 }
     86 
     87 inline int AlignedSize(int size) {
     88   return size + AlignOffset(size);
     89 }
     90 
     91 }  // namespace
     92 
     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;
    104   };
    105 
    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);
    112 
    113   SharedMemory* shared_memory() { return shared_memory_.get(); }
    114 
    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; }
    121 
    122   // Accessors for our tables
    123   char* thread_name(int slot_id) const {
    124     return &thread_names_table_[
    125       (slot_id-1) * (StatsTable::kMaxThreadNameLength)];
    126   }
    127   PlatformThreadId* thread_tid(int slot_id) const {
    128     return &(thread_tid_table_[slot_id-1]);
    129   }
    130   int* thread_pid(int slot_id) const {
    131     return &(thread_pid_table_[slot_id-1]);
    132   }
    133   char* counter_name(int counter_id) const {
    134     return &counter_names_table_[
    135       (counter_id-1) * (StatsTable::kMaxCounterNameLength)];
    136   }
    137   int* row(int counter_id) const {
    138     return &data_table_[(counter_id-1) * max_threads()];
    139   }
    140 
    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) {
    151   }
    152 
    153   // Create or open the SharedMemory used by the stats table.
    154   static SharedMemory* CreateSharedMemory(const std::string& name,
    155                                           int size);
    156 
    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);
    161 
    162   // Initializes our in-memory pointers into a pre-created StatsTable.
    163   void ComputeMappedPointers(void* memory);
    164 
    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_;
    172 
    173   DISALLOW_COPY_AND_ASSIGN(Internal);
    174 };
    175 
    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();
    187 
    188   scoped_ptr<Internal> internal(new Internal(shared_memory.release()));
    189   TableHeader* header = static_cast<TableHeader*>(memory);
    190 
    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);
    195 
    196   // We have a valid table, so compute our pointers.
    197   internal->ComputeMappedPointers(memory);
    198 
    199   return internal.release();
    200 }
    201 
    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);
    212   }
    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->CreateNamed(name, true, size))
    221     return NULL;
    222   return shared_memory.release();
    223 #endif
    224 }
    225 
    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);
    231 
    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;
    238 }
    239 
    240 void StatsTable::Internal::ComputeMappedPointers(void* memory) {
    241   char* data = static_cast<char*>(memory);
    242   int offset = 0;
    243 
    244   table_header_ = reinterpret_cast<TableHeader*>(data);
    245   offset += sizeof(*table_header_);
    246   offset += AlignOffset(offset);
    247 
    248   // Verify we're looking at a valid StatsTable.
    249   DCHECK_EQ(table_header_->version, kTableVersion);
    250 
    251   thread_names_table_ = reinterpret_cast<char*>(data + offset);
    252   offset += sizeof(char) *
    253             max_threads() * StatsTable::kMaxThreadNameLength;
    254   offset += AlignOffset(offset);
    255 
    256   thread_tid_table_ = reinterpret_cast<PlatformThreadId*>(data + offset);
    257   offset += sizeof(int) * max_threads();
    258   offset += AlignOffset(offset);
    259 
    260   thread_pid_table_ = reinterpret_cast<int*>(data + offset);
    261   offset += sizeof(int) * max_threads();
    262   offset += AlignOffset(offset);
    263 
    264   counter_names_table_ = reinterpret_cast<char*>(data + offset);
    265   offset += sizeof(char) *
    266             max_counters() * StatsTable::kMaxCounterNameLength;
    267   offset += AlignOffset(offset);
    268 
    269   data_table_ = reinterpret_cast<int*>(data + offset);
    270   offset += sizeof(int) * max_threads() * max_counters();
    271 
    272   DCHECK_EQ(offset, size());
    273 }
    274 
    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.
    278 //
    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;
    284 };
    285 
    286 // We keep a singleton table which can be easily accessed.
    287 StatsTable* global_table = NULL;
    288 
    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)));
    300 
    301   internal_ = Internal::New(name, table_size, max_threads, max_counters);
    302 
    303   if (!internal_)
    304     DPLOG(ERROR) << "StatsTable did not initialize";
    305 }
    306 
    307 StatsTable::~StatsTable() {
    308   // Before we tear down our copy of the table, be sure to
    309   // unregister our thread.
    310   UnregisterThread();
    311 
    312   // Return ThreadLocalStorage.  At this point, if any registered threads
    313   // still exist, they cannot Unregister.
    314   tls_index_.Free();
    315 
    316   // Cleanup our shared memory.
    317   delete internal_;
    318 
    319   // If we are the global table, unregister ourselves.
    320   if (global_table == this)
    321     global_table = NULL;
    322 }
    323 
    324 StatsTable* StatsTable::current() {
    325   return global_table;
    326 }
    327 
    328 void StatsTable::set_current(StatsTable* value) {
    329   global_table = value;
    330 }
    331 
    332 int StatsTable::GetSlot() const {
    333   TLSData* data = GetTLSData();
    334   if (!data)
    335     return 0;
    336   return data->slot;
    337 }
    338 
    339 int StatsTable::RegisterThread(const std::string& name) {
    340   int slot = 0;
    341   if (!internal_)
    342     return 0;
    343 
    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   {
    348     SharedMemoryAutoLock lock(internal_->shared_memory());
    349     slot = FindEmptyThread();
    350     if (!slot) {
    351       return 0;
    352     }
    353 
    354     // We have space, so consume a column in the table.
    355     std::string thread_name = name;
    356     if (name.empty())
    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();
    362   }
    363 
    364   // Set our thread local storage.
    365   TLSData* data = new TLSData;
    366   data->table = this;
    367   data->slot = slot;
    368   tls_index_.Set(data);
    369   return slot;
    370 }
    371 
    372 int StatsTable::CountThreadsRegistered() const {
    373   if (!internal_)
    374     return 0;
    375 
    376   // Loop through the shared memory and count the threads that are active.
    377   // We intentionally do not lock the table during the operation.
    378   int count = 0;
    379   for (int index = 1; index <= internal_->max_threads(); index++) {
    380     char* name = internal_->thread_name(index);
    381     if (*name != '\0')
    382       count++;
    383   }
    384   return count;
    385 }
    386 
    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".
    391   if (!internal_)
    392     return 0;
    393 
    394   // Create a scope for our auto-lock.
    395   {
    396     AutoLock scoped_lock(counters_lock_);
    397 
    398     // Attempt to find the counter.
    399     CountersMap::const_iterator iter;
    400     iter = counters_.find(name);
    401     if (iter != counters_.end())
    402       return iter->second;
    403   }
    404 
    405   // Counter does not exist, so add it.
    406   return AddCounter(name);
    407 }
    408 
    409 int* StatsTable::GetLocation(int counter_id, int slot_id) const {
    410   if (!internal_)
    411     return NULL;
    412   if (slot_id > internal_->max_threads())
    413     return NULL;
    414 
    415   int* row = internal_->row(counter_id);
    416   return &(row[slot_id-1]);
    417 }
    418 
    419 const char* StatsTable::GetRowName(int index) const {
    420   if (!internal_)
    421     return NULL;
    422 
    423   return internal_->counter_name(index);
    424 }
    425 
    426 int StatsTable::GetRowValue(int index) const {
    427   return GetRowValue(index, 0);
    428 }
    429 
    430 int StatsTable::GetRowValue(int index, int pid) const {
    431   if (!internal_)
    432     return 0;
    433 
    434   int rv = 0;
    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];
    439   }
    440   return rv;
    441 }
    442 
    443 int StatsTable::GetCounterValue(const std::string& name) {
    444   return GetCounterValue(name, 0);
    445 }
    446 
    447 int StatsTable::GetCounterValue(const std::string& name, int pid) {
    448   if (!internal_)
    449     return 0;
    450 
    451   int row = FindCounter(name);
    452   if (!row)
    453     return 0;
    454   return GetRowValue(row, pid);
    455 }
    456 
    457 int StatsTable::GetMaxCounters() const {
    458   if (!internal_)
    459     return 0;
    460   return internal_->max_counters();
    461 }
    462 
    463 int StatsTable::GetMaxThreads() const {
    464   if (!internal_)
    465     return 0;
    466   return internal_->max_threads();
    467 }
    468 
    469 int* StatsTable::FindLocation(const char* name) {
    470   // Get the static StatsTable
    471   StatsTable *table = StatsTable::current();
    472   if (!table)
    473     return NULL;
    474 
    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())))
    479     return NULL;
    480 
    481   // Find the counter id for the counter.
    482   std::string str_name(name);
    483   int counter = table->FindCounter(str_name);
    484 
    485   // Now we can find the location in the table.
    486   return table->GetLocation(counter, slot);
    487 }
    488 
    489 void StatsTable::UnregisterThread() {
    490   UnregisterThread(GetTLSData());
    491 }
    492 
    493 void StatsTable::UnregisterThread(TLSData* data) {
    494   if (!data)
    495     return;
    496   DCHECK(internal_);
    497 
    498   // Mark the slot free by zeroing out the thread name.
    499   char* name = internal_->thread_name(data->slot);
    500   *name = '\0';
    501 
    502   // Remove the calling thread's TLS so that it cannot use the slot.
    503   tls_index_.Set(NULL);
    504   delete data;
    505 }
    506 
    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);
    512   if (tls_data) {
    513     DCHECK(tls_data->table);
    514     tls_data->table->UnregisterThread(tls_data);
    515   }
    516 }
    517 
    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".
    522   //
    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.
    527   if (!internal_)
    528     return 0;
    529 
    530   int index = 1;
    531   for (; index <= internal_->max_threads(); index++) {
    532     char* name = internal_->thread_name(index);
    533     if (!*name)
    534       break;
    535   }
    536   if (index > internal_->max_threads())
    537     return 0;  // The table is full.
    538   return index;
    539 }
    540 
    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".
    545   //
    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).
    549   if (!internal_)
    550     return 0;
    551 
    552   int free_slot = 0;
    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))
    558       return index;
    559   }
    560   return free_slot;
    561 }
    562 
    563 int StatsTable::AddCounter(const std::string& name) {
    564   if (!internal_)
    565     return 0;
    566 
    567   int counter_id = 0;
    568   {
    569     // To add a counter to the shared memory, we need the
    570     // shared memory lock.
    571     SharedMemoryAutoLock lock(internal_->shared_memory());
    572 
    573     // We have space, so create a new counter.
    574     counter_id = FindCounterOrEmptyRow(name);
    575     if (!counter_id)
    576       return 0;
    577 
    578     std::string counter_name = name;
    579     if (name.empty())
    580       counter_name = kUnknownName;
    581     strlcpy(internal_->counter_name(counter_id), counter_name.c_str(),
    582             kMaxCounterNameLength);
    583   }
    584 
    585   // now add to our in-memory cache
    586   {
    587     AutoLock lock(counters_lock_);
    588     counters_[name] = counter_id;
    589   }
    590   return counter_id;
    591 }
    592 
    593 StatsTable::TLSData* StatsTable::GetTLSData() const {
    594   TLSData* data =
    595     static_cast<TLSData*>(tls_index_.Get());
    596   if (!data)
    597     return NULL;
    598 
    599   DCHECK(data->slot);
    600   DCHECK_EQ(data->table, this);
    601   return data;
    602 }
    603 
    604 #if defined(OS_POSIX)
    605 SharedMemoryHandle StatsTable::GetSharedMemoryHandle() const {
    606   if (!internal_)
    607     return SharedMemory::NULLHandle();
    608   return internal_->shared_memory()->handle();
    609 }
    610 #endif
    611 
    612 }  // namespace base
    613