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