1 /*
   2  * Copyright (c) 2001, 2017, 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 "gc/g1/g1ConcurrentRefine.hpp"
  27 #include "gc/g1/g1ConcurrentRefineThread.hpp"
  28 #include "logging/log.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "runtime/java.hpp"
  31 #include "runtime/thread.hpp"
  32 #include "utilities/debug.hpp"
  33 #include "utilities/globalDefinitions.hpp"
  34 #include "utilities/pair.hpp"
  35 #include <math.h>
  36 
  37 G1ConcurrentRefineThread* G1ConcurrentRefineThreadControl::create_refinement_thread(uint worker_id, bool initializing) {
  38   G1ConcurrentRefineThread* result = NULL;
  39   if (initializing || !InjectGCWorkerCreationFailure) {
  40     result = new G1ConcurrentRefineThread(_cr, worker_id);
  41   }
  42   if (result == NULL || result->osthread() == NULL) {
  43     log_warning(gc)("Failed to create refinement thread %u, no more %s",
  44                     worker_id,
  45                     result == NULL ? "memory" : "OS threads");
  46   }
  47   return result;
  48 }
  49 
  50 G1ConcurrentRefineThreadControl::G1ConcurrentRefineThreadControl() :
  51   _cr(NULL),
  52   _threads(NULL),
  53   _num_max_threads(0)
  54 {
  55 }
  56 
  57 G1ConcurrentRefineThreadControl::~G1ConcurrentRefineThreadControl() {
  58   for (uint i = 0; i < _num_max_threads; i++) {
  59     G1ConcurrentRefineThread* t = _threads[i];
  60     if (t != NULL) {
  61       delete t;
  62     }
  63   }
  64   FREE_C_HEAP_ARRAY(G1ConcurrentRefineThread*, _threads);
  65 }
  66 
  67 jint G1ConcurrentRefineThreadControl::initialize(G1ConcurrentRefine* cr, uint num_max_threads) {
  68   assert(cr != NULL, "G1ConcurrentRefine must not be NULL");
  69   _cr = cr;
  70   _num_max_threads = num_max_threads;
  71 
  72   _threads = NEW_C_HEAP_ARRAY_RETURN_NULL(G1ConcurrentRefineThread*, num_max_threads, mtGC);
  73   if (_threads == NULL) {
  74     vm_shutdown_during_initialization("Could not allocate thread holder array.");
  75     return JNI_ENOMEM;
  76   }
  77 
  78   for (uint i = 0; i < num_max_threads; i++) {
  79     if (UseDynamicNumberOfGCThreads && i != 0 /* Always start first thread. */) {
  80       _threads[i] = NULL;
  81     } else {
  82       _threads[i] = create_refinement_thread(i, true);
  83       if (_threads[i] == NULL) {
  84         vm_shutdown_during_initialization("Could not allocate refinement threads.");
  85         return JNI_ENOMEM;
  86       }
  87     }
  88   }
  89   return JNI_OK;
  90 }
  91 
  92 void G1ConcurrentRefineThreadControl::maybe_activate_next(uint cur_worker_id) {
  93   assert(cur_worker_id < _num_max_threads,
  94          "Activating another thread from %u not allowed since there can be at most %u",
  95          cur_worker_id, _num_max_threads);
  96   if (cur_worker_id == (_num_max_threads - 1)) {
  97     // Already the last thread, there is no more thread to activate.
  98     return;
  99   }
 100 
 101   uint worker_id = cur_worker_id + 1;
 102   G1ConcurrentRefineThread* thread_to_activate = _threads[worker_id];
 103   if (thread_to_activate == NULL) {
 104     // Still need to create the thread...
 105     _threads[worker_id] = create_refinement_thread(worker_id, false);
 106     thread_to_activate = _threads[worker_id];
 107   }
 108   if (thread_to_activate != NULL && !thread_to_activate->is_active()) {
 109     thread_to_activate->activate();
 110   }
 111 }
 112 
 113 void G1ConcurrentRefineThreadControl::print_on(outputStream* st) const {
 114   for (uint i = 0; i < _num_max_threads; ++i) {
 115     if (_threads[i] != NULL) {
 116       _threads[i]->print_on(st);
 117       st->cr();
 118     }
 119   }
 120 }
 121 
 122 void G1ConcurrentRefineThreadControl::worker_threads_do(ThreadClosure* tc) {
 123   for (uint i = 0; i < _num_max_threads; i++) {
 124     if (_threads[i] != NULL) {
 125       tc->do_thread(_threads[i]);
 126     }
 127   }
 128 }
 129 
 130 void G1ConcurrentRefineThreadControl::stop() {
 131   for (uint i = 0; i < _num_max_threads; i++) {
 132     if (_threads[i] != NULL) {
 133       _threads[i]->stop();
 134     }
 135   }
 136 }
 137 
 138 // Arbitrary but large limits, to simplify some of the zone calculations.
 139 // The general idea is to allow expressions like
 140 //   MIN2(x OP y, max_XXX_zone)
 141 // without needing to check for overflow in "x OP y", because the
 142 // ranges for x and y have been restricted.
 143 STATIC_ASSERT(sizeof(LP64_ONLY(jint) NOT_LP64(jshort)) <= (sizeof(size_t)/2));
 144 const size_t max_yellow_zone = LP64_ONLY(max_jint) NOT_LP64(max_jshort);
 145 const size_t max_green_zone = max_yellow_zone / 2;
 146 const size_t max_red_zone = INT_MAX; // For dcqs.set_max_completed_queue.
 147 STATIC_ASSERT(max_yellow_zone <= max_red_zone);
 148 
 149 // Range check assertions for green zone values.
 150 #define assert_zone_constraints_g(green)                        \
 151   do {                                                          \
 152     size_t azc_g_green = (green);                               \
 153     assert(azc_g_green <= max_green_zone,                       \
 154            "green exceeds max: " SIZE_FORMAT, azc_g_green);     \
 155   } while (0)
 156 
 157 // Range check assertions for green and yellow zone values.
 158 #define assert_zone_constraints_gy(green, yellow)                       \
 159   do {                                                                  \
 160     size_t azc_gy_green = (green);                                      \
 161     size_t azc_gy_yellow = (yellow);                                    \
 162     assert_zone_constraints_g(azc_gy_green);                            \
 163     assert(azc_gy_yellow <= max_yellow_zone,                            \
 164            "yellow exceeds max: " SIZE_FORMAT, azc_gy_yellow);          \
 165     assert(azc_gy_green <= azc_gy_yellow,                               \
 166            "green (" SIZE_FORMAT ") exceeds yellow (" SIZE_FORMAT ")",  \
 167            azc_gy_green, azc_gy_yellow);                                \
 168   } while (0)
 169 
 170 // Range check assertions for green, yellow, and red zone values.
 171 #define assert_zone_constraints_gyr(green, yellow, red)                 \
 172   do {                                                                  \
 173     size_t azc_gyr_green = (green);                                     \
 174     size_t azc_gyr_yellow = (yellow);                                   \
 175     size_t azc_gyr_red = (red);                                         \
 176     assert_zone_constraints_gy(azc_gyr_green, azc_gyr_yellow);          \
 177     assert(azc_gyr_red <= max_red_zone,                                 \
 178            "red exceeds max: " SIZE_FORMAT, azc_gyr_red);               \
 179     assert(azc_gyr_yellow <= azc_gyr_red,                               \
 180            "yellow (" SIZE_FORMAT ") exceeds red (" SIZE_FORMAT ")",    \
 181            azc_gyr_yellow, azc_gyr_red);                                \
 182   } while (0)
 183 
 184 // Logging tag sequence for refinement control updates.
 185 #define CTRL_TAGS gc, ergo, refine
 186 
 187 // For logging zone values, ensuring consistency of level and tags.
 188 #define LOG_ZONES(...) log_debug( CTRL_TAGS )(__VA_ARGS__)
 189 
 190 // Package for pair of refinement thread activation and deactivation
 191 // thresholds.  The activation and deactivation levels are resp. the first
 192 // and second values of the pair.
 193 typedef Pair<size_t, size_t> Thresholds;
 194 inline size_t activation_level(const Thresholds& t) { return t.first; }
 195 inline size_t deactivation_level(const Thresholds& t) { return t.second; }
 196 
 197 static Thresholds calc_thresholds(size_t green_zone,
 198                                   size_t yellow_zone,
 199                                   uint worker_i) {
 200   double yellow_size = yellow_zone - green_zone;
 201   double step = yellow_size / G1ConcurrentRefine::max_num_threads();
 202   if (worker_i == 0) {
 203     // Potentially activate worker 0 more aggressively, to keep
 204     // available buffers near green_zone value.  When yellow_size is
 205     // large we don't want to allow a full step to accumulate before
 206     // doing any processing, as that might lead to significantly more
 207     // than green_zone buffers to be processed by update_rs.
 208     step = MIN2(step, ParallelGCThreads / 2.0);
 209   }
 210   size_t activate_offset = static_cast<size_t>(ceil(step * (worker_i + 1)));
 211   size_t deactivate_offset = static_cast<size_t>(floor(step * worker_i));
 212   return Thresholds(green_zone + activate_offset,
 213                     green_zone + deactivate_offset);
 214 }
 215 
 216 G1ConcurrentRefine::G1ConcurrentRefine(size_t green_zone,
 217                                        size_t yellow_zone,
 218                                        size_t red_zone,
 219                                        size_t min_yellow_zone_size) :
 220   _thread_control(),
 221   _green_zone(green_zone),
 222   _yellow_zone(yellow_zone),
 223   _red_zone(red_zone),
 224   _min_yellow_zone_size(min_yellow_zone_size)
 225 {
 226   assert_zone_constraints_gyr(green_zone, yellow_zone, red_zone);
 227 }
 228 
 229 jint G1ConcurrentRefine::initialize() {
 230   return _thread_control.initialize(this, max_num_threads());
 231 }
 232 
 233 static size_t calc_min_yellow_zone_size() {
 234   size_t step = G1ConcRefinementThresholdStep;
 235   uint n_workers = G1ConcurrentRefine::max_num_threads();
 236   if ((max_yellow_zone / step) < n_workers) {
 237     return max_yellow_zone;
 238   } else {
 239     return step * n_workers;
 240   }
 241 }
 242 
 243 static size_t calc_init_green_zone() {
 244   size_t green = G1ConcRefinementGreenZone;
 245   if (FLAG_IS_DEFAULT(G1ConcRefinementGreenZone)) {
 246     green = ParallelGCThreads;
 247   }
 248   return MIN2(green, max_green_zone);
 249 }
 250 
 251 static size_t calc_init_yellow_zone(size_t green, size_t min_size) {
 252   size_t config = G1ConcRefinementYellowZone;
 253   size_t size = 0;
 254   if (FLAG_IS_DEFAULT(G1ConcRefinementYellowZone)) {
 255     size = green * 2;
 256   } else if (green < config) {
 257     size = config - green;
 258   }
 259   size = MAX2(size, min_size);
 260   size = MIN2(size, max_yellow_zone);
 261   return MIN2(green + size, max_yellow_zone);
 262 }
 263 
 264 static size_t calc_init_red_zone(size_t green, size_t yellow) {
 265   size_t size = yellow - green;
 266   if (!FLAG_IS_DEFAULT(G1ConcRefinementRedZone)) {
 267     size_t config = G1ConcRefinementRedZone;
 268     if (yellow < config) {
 269       size = MAX2(size, config - yellow);
 270     }
 271   }
 272   return MIN2(yellow + size, max_red_zone);
 273 }
 274 
 275 G1ConcurrentRefine* G1ConcurrentRefine::create(jint* ecode) {
 276   size_t min_yellow_zone_size = calc_min_yellow_zone_size();
 277   size_t green_zone = calc_init_green_zone();
 278   size_t yellow_zone = calc_init_yellow_zone(green_zone, min_yellow_zone_size);
 279   size_t red_zone = calc_init_red_zone(green_zone, yellow_zone);
 280 
 281   LOG_ZONES("Initial Refinement Zones: "
 282             "green: " SIZE_FORMAT ", "
 283             "yellow: " SIZE_FORMAT ", "
 284             "red: " SIZE_FORMAT ", "
 285             "min yellow size: " SIZE_FORMAT,
 286             green_zone, yellow_zone, red_zone, min_yellow_zone_size);
 287 
 288   G1ConcurrentRefine* cr = new G1ConcurrentRefine(green_zone,
 289                                                   yellow_zone,
 290                                                   red_zone,
 291                                                   min_yellow_zone_size);
 292 
 293   if (cr == NULL) {
 294     *ecode = JNI_ENOMEM;
 295     vm_shutdown_during_initialization("Could not create G1ConcurrentRefine");
 296     return NULL;
 297   }
 298 
 299   *ecode = cr->initialize();
 300   return cr;
 301 }
 302 
 303 void G1ConcurrentRefine::stop() {
 304   _thread_control.stop();
 305 }
 306 
 307 G1ConcurrentRefine::~G1ConcurrentRefine() {
 308 }
 309 
 310 void G1ConcurrentRefine::threads_do(ThreadClosure *tc) {
 311   _thread_control.worker_threads_do(tc);
 312 }
 313 
 314 uint G1ConcurrentRefine::max_num_threads() {
 315   return G1ConcRefinementThreads;
 316 }
 317 
 318 void G1ConcurrentRefine::print_threads_on(outputStream* st) const {
 319   _thread_control.print_on(st);
 320 }
 321 
 322 static size_t calc_new_green_zone(size_t green,
 323                                   double update_rs_time,
 324                                   size_t update_rs_processed_buffers,
 325                                   double goal_ms) {
 326   // Adjust green zone based on whether we're meeting the time goal.
 327   // Limit to max_green_zone.
 328   const double inc_k = 1.1, dec_k = 0.9;
 329   if (update_rs_time > goal_ms) {
 330     if (green > 0) {
 331       green = static_cast<size_t>(green * dec_k);
 332     }
 333   } else if (update_rs_time < goal_ms &&
 334              update_rs_processed_buffers > green) {
 335     green = static_cast<size_t>(MAX2(green * inc_k, green + 1.0));
 336     green = MIN2(green, max_green_zone);
 337   }
 338   return green;
 339 }
 340 
 341 static size_t calc_new_yellow_zone(size_t green, size_t min_yellow_size) {
 342   size_t size = green * 2;
 343   size = MAX2(size, min_yellow_size);
 344   return MIN2(green + size, max_yellow_zone);
 345 }
 346 
 347 static size_t calc_new_red_zone(size_t green, size_t yellow) {
 348   return MIN2(yellow + (yellow - green), max_red_zone);
 349 }
 350 
 351 void G1ConcurrentRefine::update_zones(double update_rs_time,
 352                                       size_t update_rs_processed_buffers,
 353                                       double goal_ms) {
 354   log_trace( CTRL_TAGS )("Updating Refinement Zones: "
 355                          "update_rs time: %.3fms, "
 356                          "update_rs buffers: " SIZE_FORMAT ", "
 357                          "update_rs goal time: %.3fms",
 358                          update_rs_time,
 359                          update_rs_processed_buffers,
 360                          goal_ms);
 361 
 362   _green_zone = calc_new_green_zone(_green_zone,
 363                                     update_rs_time,
 364                                     update_rs_processed_buffers,
 365                                     goal_ms);
 366   _yellow_zone = calc_new_yellow_zone(_green_zone, _min_yellow_zone_size);
 367   _red_zone = calc_new_red_zone(_green_zone, _yellow_zone);
 368 
 369   assert_zone_constraints_gyr(_green_zone, _yellow_zone, _red_zone);
 370   LOG_ZONES("Updated Refinement Zones: "
 371             "green: " SIZE_FORMAT ", "
 372             "yellow: " SIZE_FORMAT ", "
 373             "red: " SIZE_FORMAT,
 374             _green_zone, _yellow_zone, _red_zone);
 375 }
 376 
 377 void G1ConcurrentRefine::adjust(double update_rs_time,
 378                                 size_t update_rs_processed_buffers,
 379                                 double goal_ms) {
 380   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 381 
 382   if (G1UseAdaptiveConcRefinement) {
 383     update_zones(update_rs_time, update_rs_processed_buffers, goal_ms);
 384 
 385     // Change the barrier params
 386     if (max_num_threads() == 0) {
 387       // Disable dcqs notification when there are no threads to notify.
 388       dcqs.set_process_completed_threshold(INT_MAX);
 389     } else {
 390       // Worker 0 is the primary; wakeup is via dcqs notification.
 391       STATIC_ASSERT(max_yellow_zone <= INT_MAX);
 392       size_t activate = activation_threshold(0);
 393       dcqs.set_process_completed_threshold((int)activate);
 394     }
 395     dcqs.set_max_completed_queue((int)red_zone());
 396   }
 397 
 398   size_t curr_queue_size = dcqs.completed_buffers_num();
 399   if (curr_queue_size >= yellow_zone()) {
 400     dcqs.set_completed_queue_padding(curr_queue_size);
 401   } else {
 402     dcqs.set_completed_queue_padding(0);
 403   }
 404   dcqs.notify_if_necessary();
 405 }
 406 
 407 size_t G1ConcurrentRefine::activation_threshold(uint worker_id) const {
 408   Thresholds thresholds = calc_thresholds(_green_zone, _yellow_zone, worker_id);
 409   return activation_level(thresholds);
 410 }
 411 
 412 size_t G1ConcurrentRefine::deactivation_threshold(uint worker_id) const {
 413   Thresholds thresholds = calc_thresholds(_green_zone, _yellow_zone, worker_id);
 414   return deactivation_level(thresholds);
 415 }
 416 
 417 uint G1ConcurrentRefine::worker_id_offset() {
 418   return DirtyCardQueueSet::num_par_ids();
 419 }
 420 
 421 void G1ConcurrentRefine::maybe_activate_more_threads(uint worker_id, size_t num_cur_buffers) {
 422   if (num_cur_buffers > activation_threshold(worker_id + 1)) {
 423     _thread_control.maybe_activate_next(worker_id);
 424   }
 425 }
 426 
 427 bool G1ConcurrentRefine::do_refinement_step(uint worker_id) {
 428   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 429 
 430   size_t curr_buffer_num = dcqs.completed_buffers_num();
 431   // If the number of the buffers falls down into the yellow zone,
 432   // that means that the transition period after the evacuation pause has ended.
 433   // Since the value written to the DCQS is the same for all threads, there is no
 434   // need to synchronize.
 435   if (dcqs.completed_queue_padding() > 0 && curr_buffer_num <= yellow_zone()) {
 436     dcqs.set_completed_queue_padding(0);
 437   }
 438 
 439   maybe_activate_more_threads(worker_id, curr_buffer_num);
 440 
 441   // Process the next buffer, if there are enough left.
 442   return dcqs.refine_completed_buffer_concurrently(worker_id + worker_id_offset(),
 443                                                    deactivation_threshold(worker_id));
 444 }