1 /*
   2  * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/altHashing.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  30 #include "gc/g1/g1StringDedup.hpp"
  31 #include "gc/g1/g1StringDedupTable.hpp"
  32 #include "gc/shared/gcLocker.hpp"
  33 #include "logging/log.hpp"
  34 #include "memory/padded.inline.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "oops/typeArrayOop.hpp"
  37 #include "runtime/mutexLocker.hpp"
  38 
  39 //
  40 // Freelist in the deduplication table entry cache. Links table
  41 // entries together using their _next fields.
  42 //
  43 class G1StringDedupEntryFreeList : public CHeapObj<mtGC> {
  44 private:
  45   G1StringDedupEntry* _list;
  46   size_t              _length;
  47 
  48 public:
  49   G1StringDedupEntryFreeList() :
  50     _list(NULL),
  51     _length(0) {
  52   }
  53 
  54   void add(G1StringDedupEntry* entry) {
  55     entry->set_next(_list);
  56     _list = entry;
  57     _length++;
  58   }
  59 
  60   G1StringDedupEntry* remove() {
  61     G1StringDedupEntry* entry = _list;
  62     if (entry != NULL) {
  63       _list = entry->next();
  64       _length--;
  65     }
  66     return entry;
  67   }
  68 
  69   size_t length() {
  70     return _length;
  71   }
  72 };
  73 
  74 //
  75 // Cache of deduplication table entries. This cache provides fast allocation and
  76 // reuse of table entries to lower the pressure on the underlying allocator.
  77 // But more importantly, it provides fast/deferred freeing of table entries. This
  78 // is important because freeing of table entries is done during stop-the-world
  79 // phases and it is not uncommon for large number of entries to be freed at once.
  80 // Tables entries that are freed during these phases are placed onto a freelist in
  81 // the cache. The deduplication thread, which executes in a concurrent phase, will
  82 // later reuse or free the underlying memory for these entries.
  83 //
  84 // The cache allows for single-threaded allocations and multi-threaded frees.
  85 // Allocations are synchronized by StringDedupTable_lock as part of a table
  86 // modification.
  87 //
  88 class G1StringDedupEntryCache : public CHeapObj<mtGC> {
  89 private:
  90   // One freelist per GC worker to allow lock less freeing of
  91   // entries while doing a parallel scan of the table. Using
  92   // PaddedEnd to avoid false sharing.
  93   PaddedEnd<G1StringDedupEntryFreeList>* _lists;
  94   size_t                                 _nlists;
  95 
  96 public:
  97   G1StringDedupEntryCache();
  98   ~G1StringDedupEntryCache();
  99 
 100   // Get a table entry from the cache freelist, or allocate a new
 101   // entry if the cache is empty.
 102   G1StringDedupEntry* alloc();
 103 
 104   // Insert a table entry into the cache freelist.
 105   void free(G1StringDedupEntry* entry, uint worker_id);
 106 
 107   // Returns current number of entries in the cache.
 108   size_t size();
 109 
 110   // If the cache has grown above the given max size, trim it down
 111   // and deallocate the memory occupied by trimmed of entries.
 112   void trim(size_t max_size);
 113 };
 114 
 115 G1StringDedupEntryCache::G1StringDedupEntryCache() {
 116   _nlists = ParallelGCThreads;
 117   _lists = PaddedArray<G1StringDedupEntryFreeList, mtGC>::create_unfreeable((uint)_nlists);
 118 }
 119 
 120 G1StringDedupEntryCache::~G1StringDedupEntryCache() {
 121   ShouldNotReachHere();
 122 }
 123 
 124 G1StringDedupEntry* G1StringDedupEntryCache::alloc() {
 125   for (size_t i = 0; i < _nlists; i++) {
 126     G1StringDedupEntry* entry = _lists[i].remove();
 127     if (entry != NULL) {
 128       return entry;
 129     }
 130   }
 131   return new G1StringDedupEntry();
 132 }
 133 
 134 void G1StringDedupEntryCache::free(G1StringDedupEntry* entry, uint worker_id) {
 135   assert(entry->obj() != NULL, "Double free");
 136   assert(worker_id < _nlists, "Invalid worker id");
 137   entry->set_obj(NULL);
 138   entry->set_hash(0);
 139   _lists[worker_id].add(entry);
 140 }
 141 
 142 size_t G1StringDedupEntryCache::size() {
 143   size_t size = 0;
 144   for (size_t i = 0; i < _nlists; i++) {
 145     size += _lists[i].length();
 146   }
 147   return size;
 148 }
 149 
 150 void G1StringDedupEntryCache::trim(size_t max_size) {
 151   size_t cache_size = 0;
 152   for (size_t i = 0; i < _nlists; i++) {
 153     G1StringDedupEntryFreeList* list = &_lists[i];
 154     cache_size += list->length();
 155     while (cache_size > max_size) {
 156       G1StringDedupEntry* entry = list->remove();
 157       assert(entry != NULL, "Should not be null");
 158       cache_size--;
 159       delete entry;
 160     }
 161   }
 162 }
 163 
 164 G1StringDedupTable*      G1StringDedupTable::_table = NULL;
 165 G1StringDedupEntryCache* G1StringDedupTable::_entry_cache = NULL;
 166 
 167 const size_t             G1StringDedupTable::_min_size = (1 << 10);   // 1024
 168 const size_t             G1StringDedupTable::_max_size = (1 << 24);   // 16777216
 169 const double             G1StringDedupTable::_grow_load_factor = 2.0; // Grow table at 200% load
 170 const double             G1StringDedupTable::_shrink_load_factor = _grow_load_factor / 3.0; // Shrink table at 67% load
 171 const double             G1StringDedupTable::_max_cache_factor = 0.1; // Cache a maximum of 10% of the table size
 172 const uintx              G1StringDedupTable::_rehash_multiple = 60;   // Hash bucket has 60 times more collisions than expected
 173 const uintx              G1StringDedupTable::_rehash_threshold = (uintx)(_rehash_multiple * _grow_load_factor);
 174 
 175 uintx                    G1StringDedupTable::_entries_added = 0;
 176 uintx                    G1StringDedupTable::_entries_removed = 0;
 177 uintx                    G1StringDedupTable::_resize_count = 0;
 178 uintx                    G1StringDedupTable::_rehash_count = 0;
 179 
 180 G1StringDedupTable::G1StringDedupTable(size_t size, jint hash_seed) :
 181   _size(size),
 182   _entries(0),
 183   _grow_threshold((uintx)(size * _grow_load_factor)),
 184   _shrink_threshold((uintx)(size * _shrink_load_factor)),
 185   _rehash_needed(false),
 186   _hash_seed(hash_seed) {
 187   assert(is_power_of_2(size), "Table size must be a power of 2");
 188   _buckets = NEW_C_HEAP_ARRAY(G1StringDedupEntry*, _size, mtGC);
 189   memset(_buckets, 0, _size * sizeof(G1StringDedupEntry*));
 190 }
 191 
 192 G1StringDedupTable::~G1StringDedupTable() {
 193   FREE_C_HEAP_ARRAY(G1StringDedupEntry*, _buckets);
 194 }
 195 
 196 void G1StringDedupTable::create() {
 197   assert(_table == NULL, "One string deduplication table allowed");
 198   _entry_cache = new G1StringDedupEntryCache();
 199   _table = new G1StringDedupTable(_min_size);
 200 }
 201 
 202 void G1StringDedupTable::add(typeArrayOop value, unsigned int hash, G1StringDedupEntry** list) {
 203   G1StringDedupEntry* entry = _entry_cache->alloc();
 204   entry->set_obj(value);
 205   entry->set_hash(hash);
 206   entry->set_next(*list);
 207   *list = entry;
 208   _entries++;
 209 }
 210 
 211 void G1StringDedupTable::remove(G1StringDedupEntry** pentry, uint worker_id) {
 212   G1StringDedupEntry* entry = *pentry;
 213   *pentry = entry->next();
 214   _entry_cache->free(entry, worker_id);
 215 }
 216 
 217 void G1StringDedupTable::transfer(G1StringDedupEntry** pentry, G1StringDedupTable* dest) {
 218   G1StringDedupEntry* entry = *pentry;
 219   *pentry = entry->next();
 220   unsigned int hash = entry->hash();
 221   size_t index = dest->hash_to_index(hash);
 222   G1StringDedupEntry** list = dest->bucket(index);
 223   entry->set_next(*list);
 224   *list = entry;
 225 }
 226 
 227 bool G1StringDedupTable::equals(typeArrayOop value1, typeArrayOop value2) {
 228   return (value1 == value2 ||
 229           (value1->length() == value2->length() &&
 230            (!memcmp(value1->base(T_CHAR),
 231                     value2->base(T_CHAR),
 232                     value1->length() * sizeof(jchar)))));
 233 }
 234 
 235 typeArrayOop G1StringDedupTable::lookup(typeArrayOop value, unsigned int hash,
 236                                         G1StringDedupEntry** list, uintx &count) {
 237   for (G1StringDedupEntry* entry = *list; entry != NULL; entry = entry->next()) {
 238     if (entry->hash() == hash) {
 239       typeArrayOop existing_value = entry->obj();
 240       if (equals(value, existing_value)) {
 241         // Match found
 242         return existing_value;
 243       }
 244     }
 245     count++;
 246   }
 247 
 248   // Not found
 249   return NULL;
 250 }
 251 
 252 typeArrayOop G1StringDedupTable::lookup_or_add_inner(typeArrayOop value, unsigned int hash) {
 253   size_t index = hash_to_index(hash);
 254   G1StringDedupEntry** list = bucket(index);
 255   uintx count = 0;
 256 
 257   // Lookup in list
 258   typeArrayOop existing_value = lookup(value, hash, list, count);
 259 
 260   // Check if rehash is needed
 261   if (count > _rehash_threshold) {
 262     _rehash_needed = true;
 263   }
 264 
 265   if (existing_value == NULL) {
 266     // Not found, add new entry
 267     add(value, hash, list);
 268 
 269     // Update statistics
 270     _entries_added++;
 271   }
 272 
 273   return existing_value;
 274 }
 275 
 276 unsigned int G1StringDedupTable::hash_code(typeArrayOop value) {
 277   unsigned int hash;
 278   int length = value->length();
 279   const jchar* data = (jchar*)value->base(T_CHAR);
 280 
 281   if (use_java_hash()) {
 282     hash = java_lang_String::hash_code(data, length);
 283   } else {
 284     hash = AltHashing::murmur3_32(_table->_hash_seed, data, length);
 285   }
 286 
 287   return hash;
 288 }
 289 
 290 void G1StringDedupTable::deduplicate(oop java_string, G1StringDedupStat& stat) {
 291   assert(java_lang_String::is_instance(java_string), "Must be a string");
 292   No_Safepoint_Verifier nsv;
 293 
 294   stat.inc_inspected();
 295 
 296   typeArrayOop value = java_lang_String::value(java_string);
 297   if (value == NULL) {
 298     // String has no value
 299     stat.inc_skipped();
 300     return;
 301   }
 302 
 303   unsigned int hash = 0;
 304 
 305   if (use_java_hash()) {
 306     // Get hash code from cache
 307     hash = java_lang_String::hash(java_string);
 308   }
 309 
 310   if (hash == 0) {
 311     // Compute hash
 312     hash = hash_code(value);
 313     stat.inc_hashed();
 314 
 315     if (use_java_hash() && hash != 0) {
 316       // Store hash code in cache
 317       java_lang_String::set_hash(java_string, hash);
 318     }
 319   }
 320 
 321   typeArrayOop existing_value = lookup_or_add(value, hash);
 322   if (existing_value == value) {
 323     // Same value, already known
 324     stat.inc_known();
 325     return;
 326   }
 327 
 328   // Get size of value array
 329   uintx size_in_bytes = value->size() * HeapWordSize;
 330   stat.inc_new(size_in_bytes);
 331 
 332   if (existing_value != NULL) {
 333     // Enqueue the reference to make sure it is kept alive. Concurrent mark might
 334     // otherwise declare it dead if there are no other strong references to this object.
 335     G1SATBCardTableModRefBS::enqueue(existing_value);
 336 
 337     // Existing value found, deduplicate string
 338     java_lang_String::set_value(java_string, existing_value);
 339 
 340     if (G1CollectedHeap::heap()->is_in_young(value)) {
 341       stat.inc_deduped_young(size_in_bytes);
 342     } else {
 343       stat.inc_deduped_old(size_in_bytes);
 344     }
 345   }
 346 }
 347 
 348 G1StringDedupTable* G1StringDedupTable::prepare_resize() {
 349   size_t size = _table->_size;
 350 
 351   // Check if the hashtable needs to be resized
 352   if (_table->_entries > _table->_grow_threshold) {
 353     // Grow table, double the size
 354     size *= 2;
 355     if (size > _max_size) {
 356       // Too big, don't resize
 357       return NULL;
 358     }
 359   } else if (_table->_entries < _table->_shrink_threshold) {
 360     // Shrink table, half the size
 361     size /= 2;
 362     if (size < _min_size) {
 363       // Too small, don't resize
 364       return NULL;
 365     }
 366   } else if (StringDeduplicationResizeALot) {
 367     // Force grow
 368     size *= 2;
 369     if (size > _max_size) {
 370       // Too big, force shrink instead
 371       size /= 4;
 372     }
 373   } else {
 374     // Resize not needed
 375     return NULL;
 376   }
 377 
 378   // Update statistics
 379   _resize_count++;
 380 
 381   // Allocate the new table. The new table will be populated by workers
 382   // calling unlink_or_oops_do() and finally installed by finish_resize().
 383   return new G1StringDedupTable(size, _table->_hash_seed);
 384 }
 385 
 386 void G1StringDedupTable::finish_resize(G1StringDedupTable* resized_table) {
 387   assert(resized_table != NULL, "Invalid table");
 388 
 389   resized_table->_entries = _table->_entries;
 390 
 391   // Free old table
 392   delete _table;
 393 
 394   // Install new table
 395   _table = resized_table;
 396 }
 397 
 398 void G1StringDedupTable::unlink_or_oops_do(G1StringDedupUnlinkOrOopsDoClosure* cl, uint worker_id) {
 399   // The table is divided into partitions to allow lock-less parallel processing by
 400   // multiple worker threads. A worker thread first claims a partition, which ensures
 401   // exclusive access to that part of the table, then continues to process it. To allow
 402   // shrinking of the table in parallel we also need to make sure that the same worker
 403   // thread processes all partitions where entries will hash to the same destination
 404   // partition. Since the table size is always a power of two and we always shrink by
 405   // dividing the table in half, we know that for a given partition there is only one
 406   // other partition whoes entries will hash to the same destination partition. That
 407   // other partition is always the sibling partition in the second half of the table.
 408   // For example, if the table is divided into 8 partitions, the sibling of partition 0
 409   // is partition 4, the sibling of partition 1 is partition 5, etc.
 410   size_t table_half = _table->_size / 2;
 411 
 412   // Let each partition be one page worth of buckets
 413   size_t partition_size = MIN2(table_half, os::vm_page_size() / sizeof(G1StringDedupEntry*));
 414   assert(table_half % partition_size == 0, "Invalid partition size");
 415 
 416   // Number of entries removed during the scan
 417   uintx removed = 0;
 418 
 419   for (;;) {
 420     // Grab next partition to scan
 421     size_t partition_begin = cl->claim_table_partition(partition_size);
 422     size_t partition_end = partition_begin + partition_size;
 423     if (partition_begin >= table_half) {
 424       // End of table
 425       break;
 426     }
 427 
 428     // Scan the partition followed by the sibling partition in the second half of the table
 429     removed += unlink_or_oops_do(cl, partition_begin, partition_end, worker_id);
 430     removed += unlink_or_oops_do(cl, table_half + partition_begin, table_half + partition_end, worker_id);
 431   }
 432 
 433   // Delayed update avoid contention on the table lock
 434   if (removed > 0) {
 435     MutexLockerEx ml(StringDedupTable_lock, Mutex::_no_safepoint_check_flag);
 436     _table->_entries -= removed;
 437     _entries_removed += removed;
 438   }
 439 }
 440 
 441 uintx G1StringDedupTable::unlink_or_oops_do(G1StringDedupUnlinkOrOopsDoClosure* cl,
 442                                             size_t partition_begin,
 443                                             size_t partition_end,
 444                                             uint worker_id) {
 445   uintx removed = 0;
 446   for (size_t bucket = partition_begin; bucket < partition_end; bucket++) {
 447     G1StringDedupEntry** entry = _table->bucket(bucket);
 448     while (*entry != NULL) {
 449       oop* p = (oop*)(*entry)->obj_addr();
 450       if (cl->is_alive(*p)) {
 451         cl->keep_alive(p);
 452         if (cl->is_resizing()) {
 453           // We are resizing the table, transfer entry to the new table
 454           _table->transfer(entry, cl->resized_table());
 455         } else {
 456           if (cl->is_rehashing()) {
 457             // We are rehashing the table, rehash the entry but keep it
 458             // in the table. We can't transfer entries into the new table
 459             // at this point since we don't have exclusive access to all
 460             // destination partitions. finish_rehash() will do a single
 461             // threaded transfer of all entries.
 462             typeArrayOop value = (typeArrayOop)*p;
 463             unsigned int hash = hash_code(value);
 464             (*entry)->set_hash(hash);
 465           }
 466 
 467           // Move to next entry
 468           entry = (*entry)->next_addr();
 469         }
 470       } else {
 471         // Not alive, remove entry from table
 472         _table->remove(entry, worker_id);
 473         removed++;
 474       }
 475     }
 476   }
 477 
 478   return removed;
 479 }
 480 
 481 G1StringDedupTable* G1StringDedupTable::prepare_rehash() {
 482   if (!_table->_rehash_needed && !StringDeduplicationRehashALot) {
 483     // Rehash not needed
 484     return NULL;
 485   }
 486 
 487   // Update statistics
 488   _rehash_count++;
 489 
 490   // Compute new hash seed
 491   _table->_hash_seed = AltHashing::compute_seed();
 492 
 493   // Allocate the new table, same size and hash seed
 494   return new G1StringDedupTable(_table->_size, _table->_hash_seed);
 495 }
 496 
 497 void G1StringDedupTable::finish_rehash(G1StringDedupTable* rehashed_table) {
 498   assert(rehashed_table != NULL, "Invalid table");
 499 
 500   // Move all newly rehashed entries into the correct buckets in the new table
 501   for (size_t bucket = 0; bucket < _table->_size; bucket++) {
 502     G1StringDedupEntry** entry = _table->bucket(bucket);
 503     while (*entry != NULL) {
 504       _table->transfer(entry, rehashed_table);
 505     }
 506   }
 507 
 508   rehashed_table->_entries = _table->_entries;
 509 
 510   // Free old table
 511   delete _table;
 512 
 513   // Install new table
 514   _table = rehashed_table;
 515 }
 516 
 517 void G1StringDedupTable::verify() {
 518   for (size_t bucket = 0; bucket < _table->_size; bucket++) {
 519     // Verify entries
 520     G1StringDedupEntry** entry = _table->bucket(bucket);
 521     while (*entry != NULL) {
 522       typeArrayOop value = (*entry)->obj();
 523       guarantee(value != NULL, "Object must not be NULL");
 524       guarantee(G1CollectedHeap::heap()->is_in_reserved(value), "Object must be on the heap");
 525       guarantee(!value->is_forwarded(), "Object must not be forwarded");
 526       guarantee(value->is_typeArray(), "Object must be a typeArrayOop");
 527       unsigned int hash = hash_code(value);
 528       guarantee((*entry)->hash() == hash, "Table entry has inorrect hash");
 529       guarantee(_table->hash_to_index(hash) == bucket, "Table entry has incorrect index");
 530       entry = (*entry)->next_addr();
 531     }
 532 
 533     // Verify that we do not have entries with identical oops or identical arrays.
 534     // We only need to compare entries in the same bucket. If the same oop or an
 535     // identical array has been inserted more than once into different/incorrect
 536     // buckets the verification step above will catch that.
 537     G1StringDedupEntry** entry1 = _table->bucket(bucket);
 538     while (*entry1 != NULL) {
 539       typeArrayOop value1 = (*entry1)->obj();
 540       G1StringDedupEntry** entry2 = (*entry1)->next_addr();
 541       while (*entry2 != NULL) {
 542         typeArrayOop value2 = (*entry2)->obj();
 543         guarantee(!equals(value1, value2), "Table entries must not have identical arrays");
 544         entry2 = (*entry2)->next_addr();
 545       }
 546       entry1 = (*entry1)->next_addr();
 547     }
 548   }
 549 }
 550 
 551 void G1StringDedupTable::trim_entry_cache() {
 552   MutexLockerEx ml(StringDedupTable_lock, Mutex::_no_safepoint_check_flag);
 553   size_t max_cache_size = (size_t)(_table->_size * _max_cache_factor);
 554   _entry_cache->trim(max_cache_size);
 555 }
 556 
 557 void G1StringDedupTable::print_statistics() {
 558   log_trace(gc, stringdedup)(
 559     "   [Table]\n"
 560     "      [Memory Usage: " G1_STRDEDUP_BYTES_FORMAT_NS "]\n"
 561     "      [Size: " SIZE_FORMAT ", Min: " SIZE_FORMAT ", Max: " SIZE_FORMAT "]\n"
 562     "      [Entries: " UINTX_FORMAT ", Load: " G1_STRDEDUP_PERCENT_FORMAT_NS ", Cached: " UINTX_FORMAT ", Added: " UINTX_FORMAT ", Removed: " UINTX_FORMAT "]\n"
 563     "      [Resize Count: " UINTX_FORMAT ", Shrink Threshold: " UINTX_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT_NS "), Grow Threshold: " UINTX_FORMAT "(" G1_STRDEDUP_PERCENT_FORMAT_NS ")]\n"
 564     "      [Rehash Count: " UINTX_FORMAT ", Rehash Threshold: " UINTX_FORMAT ", Hash Seed: 0x%x]\n"
 565     "      [Age Threshold: " UINTX_FORMAT "]",
 566     G1_STRDEDUP_BYTES_PARAM(_table->_size * sizeof(G1StringDedupEntry*) + (_table->_entries + _entry_cache->size()) * sizeof(G1StringDedupEntry)),
 567     _table->_size, _min_size, _max_size,
 568     _table->_entries, (double)_table->_entries / (double)_table->_size * 100.0, _entry_cache->size(), _entries_added, _entries_removed,
 569     _resize_count, _table->_shrink_threshold, _shrink_load_factor * 100.0, _table->_grow_threshold, _grow_load_factor * 100.0,
 570     _rehash_count, _rehash_threshold, _table->_hash_seed,
 571     StringDeduplicationAgeThreshold);
 572 }