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