threadLocalAllocBuffer.cpp revision 9727:f944761a3ce3
1/*
2 * Copyright (c) 1999, 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 "gc/shared/genCollectedHeap.hpp"
27#include "gc/shared/threadLocalAllocBuffer.inline.hpp"
28#include "logging/log.hpp"
29#include "memory/resourceArea.hpp"
30#include "memory/universe.inline.hpp"
31#include "oops/oop.inline.hpp"
32#include "runtime/thread.inline.hpp"
33#include "utilities/copy.hpp"
34
35// Thread-Local Edens support
36
37// static member initialization
38size_t           ThreadLocalAllocBuffer::_max_size       = 0;
39unsigned         ThreadLocalAllocBuffer::_target_refills = 0;
40GlobalTLABStats* ThreadLocalAllocBuffer::_global_stats   = NULL;
41
42void ThreadLocalAllocBuffer::clear_before_allocation() {
43  _slow_refill_waste += (unsigned)remaining();
44  make_parsable(true);   // also retire the TLAB
45}
46
47void ThreadLocalAllocBuffer::accumulate_statistics_before_gc() {
48  global_stats()->initialize();
49
50  for (JavaThread *thread = Threads::first(); thread != NULL; thread = thread->next()) {
51    thread->tlab().accumulate_statistics();
52    thread->tlab().initialize_statistics();
53  }
54
55  // Publish new stats if some allocation occurred.
56  if (global_stats()->allocation() != 0) {
57    global_stats()->publish();
58    global_stats()->print();
59  }
60}
61
62void ThreadLocalAllocBuffer::accumulate_statistics() {
63  Thread* thread = myThread();
64  size_t capacity = Universe::heap()->tlab_capacity(thread);
65  size_t used     = Universe::heap()->tlab_used(thread);
66
67  _gc_waste += (unsigned)remaining();
68  size_t total_allocated = thread->allocated_bytes();
69  size_t allocated_since_last_gc = total_allocated - _allocated_before_last_gc;
70  _allocated_before_last_gc = total_allocated;
71
72  print_stats("gc");
73
74  if (_number_of_refills > 0) {
75    // Update allocation history if a reasonable amount of eden was allocated.
76    bool update_allocation_history = used > 0.5 * capacity;
77
78    if (update_allocation_history) {
79      // Average the fraction of eden allocated in a tlab by this
80      // thread for use in the next resize operation.
81      // _gc_waste is not subtracted because it's included in
82      // "used".
83      // The result can be larger than 1.0 due to direct to old allocations.
84      // These allocations should ideally not be counted but since it is not possible
85      // to filter them out here we just cap the fraction to be at most 1.0.
86      double alloc_frac = MIN2(1.0, (double) allocated_since_last_gc / used);
87      _allocation_fraction.sample(alloc_frac);
88    }
89    global_stats()->update_allocating_threads();
90    global_stats()->update_number_of_refills(_number_of_refills);
91    global_stats()->update_allocation(_number_of_refills * desired_size());
92    global_stats()->update_gc_waste(_gc_waste);
93    global_stats()->update_slow_refill_waste(_slow_refill_waste);
94    global_stats()->update_fast_refill_waste(_fast_refill_waste);
95
96  } else {
97    assert(_number_of_refills == 0 && _fast_refill_waste == 0 &&
98           _slow_refill_waste == 0 && _gc_waste          == 0,
99           "tlab stats == 0");
100  }
101  global_stats()->update_slow_allocations(_slow_allocations);
102}
103
104// Fills the current tlab with a dummy filler array to create
105// an illusion of a contiguous Eden and optionally retires the tlab.
106// Waste accounting should be done in caller as appropriate; see,
107// for example, clear_before_allocation().
108void ThreadLocalAllocBuffer::make_parsable(bool retire) {
109  if (end() != NULL) {
110    invariants();
111
112    if (retire) {
113      myThread()->incr_allocated_bytes(used_bytes());
114    }
115
116    CollectedHeap::fill_with_object(top(), hard_end(), retire);
117
118    if (retire || ZeroTLAB) {  // "Reset" the TLAB
119      set_start(NULL);
120      set_top(NULL);
121      set_pf_top(NULL);
122      set_end(NULL);
123    }
124  }
125  assert(!(retire || ZeroTLAB)  ||
126         (start() == NULL && end() == NULL && top() == NULL),
127         "TLAB must be reset");
128}
129
130void ThreadLocalAllocBuffer::resize_all_tlabs() {
131  if (ResizeTLAB) {
132    for (JavaThread *thread = Threads::first(); thread != NULL; thread = thread->next()) {
133      thread->tlab().resize();
134    }
135  }
136}
137
138void ThreadLocalAllocBuffer::resize() {
139  // Compute the next tlab size using expected allocation amount
140  assert(ResizeTLAB, "Should not call this otherwise");
141  size_t alloc = (size_t)(_allocation_fraction.average() *
142                          (Universe::heap()->tlab_capacity(myThread()) / HeapWordSize));
143  size_t new_size = alloc / _target_refills;
144
145  new_size = MIN2(MAX2(new_size, min_size()), max_size());
146
147  size_t aligned_new_size = align_object_size(new_size);
148
149  log_trace(gc, tlab)("TLAB new size: thread: " INTPTR_FORMAT " [id: %2d]"
150                      " refills %d  alloc: %8.6f desired_size: " SIZE_FORMAT " -> " SIZE_FORMAT,
151                      p2i(myThread()), myThread()->osthread()->thread_id(),
152                      _target_refills, _allocation_fraction.average(), desired_size(), aligned_new_size);
153
154  set_desired_size(aligned_new_size);
155  set_refill_waste_limit(initial_refill_waste_limit());
156}
157
158void ThreadLocalAllocBuffer::initialize_statistics() {
159    _number_of_refills = 0;
160    _fast_refill_waste = 0;
161    _slow_refill_waste = 0;
162    _gc_waste          = 0;
163    _slow_allocations  = 0;
164}
165
166void ThreadLocalAllocBuffer::fill(HeapWord* start,
167                                  HeapWord* top,
168                                  size_t    new_size) {
169  _number_of_refills++;
170  print_stats("fill");
171  assert(top <= start + new_size - alignment_reserve(), "size too small");
172  initialize(start, top, start + new_size - alignment_reserve());
173
174  // Reset amount of internal fragmentation
175  set_refill_waste_limit(initial_refill_waste_limit());
176}
177
178void ThreadLocalAllocBuffer::initialize(HeapWord* start,
179                                        HeapWord* top,
180                                        HeapWord* end) {
181  set_start(start);
182  set_top(top);
183  set_pf_top(top);
184  set_end(end);
185  invariants();
186}
187
188void ThreadLocalAllocBuffer::initialize() {
189  initialize(NULL,                    // start
190             NULL,                    // top
191             NULL);                   // end
192
193  set_desired_size(initial_desired_size());
194
195  // Following check is needed because at startup the main (primordial)
196  // thread is initialized before the heap is.  The initialization for
197  // this thread is redone in startup_initialization below.
198  if (Universe::heap() != NULL) {
199    size_t capacity   = Universe::heap()->tlab_capacity(myThread()) / HeapWordSize;
200    double alloc_frac = desired_size() * target_refills() / (double) capacity;
201    _allocation_fraction.sample(alloc_frac);
202  }
203
204  set_refill_waste_limit(initial_refill_waste_limit());
205
206  initialize_statistics();
207}
208
209void ThreadLocalAllocBuffer::startup_initialization() {
210
211  // Assuming each thread's active tlab is, on average,
212  // 1/2 full at a GC
213  _target_refills = 100 / (2 * TLABWasteTargetPercent);
214  _target_refills = MAX2(_target_refills, (unsigned)1U);
215
216  _global_stats = new GlobalTLABStats();
217
218  // During jvm startup, the main (primordial) thread is initialized
219  // before the heap is initialized.  So reinitialize it now.
220  guarantee(Thread::current()->is_Java_thread(), "tlab initialization thread not Java thread");
221  Thread::current()->tlab().initialize();
222
223  log_develop_trace(gc, tlab)("TLAB min: " SIZE_FORMAT " initial: " SIZE_FORMAT " max: " SIZE_FORMAT,
224                               min_size(), Thread::current()->tlab().initial_desired_size(), max_size());
225}
226
227size_t ThreadLocalAllocBuffer::initial_desired_size() {
228  size_t init_sz = 0;
229
230  if (TLABSize > 0) {
231    init_sz = TLABSize / HeapWordSize;
232  } else if (global_stats() != NULL) {
233    // Initial size is a function of the average number of allocating threads.
234    unsigned nof_threads = global_stats()->allocating_threads_avg();
235
236    init_sz  = (Universe::heap()->tlab_capacity(myThread()) / HeapWordSize) /
237                      (nof_threads * target_refills());
238    init_sz = align_object_size(init_sz);
239  }
240  init_sz = MIN2(MAX2(init_sz, min_size()), max_size());
241  return init_sz;
242}
243
244void ThreadLocalAllocBuffer::print_stats(const char* tag) {
245  LogHandle(gc, tlab) log;
246  if (!log.is_trace()) {
247    return;
248  }
249
250  Thread* thrd = myThread();
251  size_t waste = _gc_waste + _slow_refill_waste + _fast_refill_waste;
252  size_t alloc = _number_of_refills * _desired_size;
253  double waste_percent = alloc == 0 ? 0.0 :
254                      100.0 * waste / alloc;
255  size_t tlab_used  = Universe::heap()->tlab_used(thrd);
256  log.trace("TLAB: %s thread: " INTPTR_FORMAT " [id: %2d]"
257            " desired_size: " SIZE_FORMAT "KB"
258            " slow allocs: %d  refill waste: " SIZE_FORMAT "B"
259            " alloc:%8.5f %8.0fKB refills: %d waste %4.1f%% gc: %dB"
260            " slow: %dB fast: %dB",
261            tag, p2i(thrd), thrd->osthread()->thread_id(),
262            _desired_size / (K / HeapWordSize),
263            _slow_allocations, _refill_waste_limit * HeapWordSize,
264            _allocation_fraction.average(),
265            _allocation_fraction.average() * tlab_used / K,
266            _number_of_refills, waste_percent,
267            _gc_waste * HeapWordSize,
268            _slow_refill_waste * HeapWordSize,
269            _fast_refill_waste * HeapWordSize);
270}
271
272void ThreadLocalAllocBuffer::verify() {
273  HeapWord* p = start();
274  HeapWord* t = top();
275  HeapWord* prev_p = NULL;
276  while (p < t) {
277    oop(p)->verify();
278    prev_p = p;
279    p += oop(p)->size();
280  }
281  guarantee(p == top(), "end of last object must match end of space");
282}
283
284Thread* ThreadLocalAllocBuffer::myThread() {
285  return (Thread*)(((char *)this) +
286                   in_bytes(start_offset()) -
287                   in_bytes(Thread::tlab_start_offset()));
288}
289
290
291GlobalTLABStats::GlobalTLABStats() :
292  _allocating_threads_avg(TLABAllocationWeight) {
293
294  initialize();
295
296  _allocating_threads_avg.sample(1); // One allocating thread at startup
297
298  if (UsePerfData) {
299
300    EXCEPTION_MARK;
301    ResourceMark rm;
302
303    char* cname = PerfDataManager::counter_name("tlab", "allocThreads");
304    _perf_allocating_threads =
305      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_None, CHECK);
306
307    cname = PerfDataManager::counter_name("tlab", "fills");
308    _perf_total_refills =
309      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_None, CHECK);
310
311    cname = PerfDataManager::counter_name("tlab", "maxFills");
312    _perf_max_refills =
313      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_None, CHECK);
314
315    cname = PerfDataManager::counter_name("tlab", "alloc");
316    _perf_allocation =
317      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
318
319    cname = PerfDataManager::counter_name("tlab", "gcWaste");
320    _perf_gc_waste =
321      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
322
323    cname = PerfDataManager::counter_name("tlab", "maxGcWaste");
324    _perf_max_gc_waste =
325      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
326
327    cname = PerfDataManager::counter_name("tlab", "slowWaste");
328    _perf_slow_refill_waste =
329      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
330
331    cname = PerfDataManager::counter_name("tlab", "maxSlowWaste");
332    _perf_max_slow_refill_waste =
333      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
334
335    cname = PerfDataManager::counter_name("tlab", "fastWaste");
336    _perf_fast_refill_waste =
337      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
338
339    cname = PerfDataManager::counter_name("tlab", "maxFastWaste");
340    _perf_max_fast_refill_waste =
341      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes, CHECK);
342
343    cname = PerfDataManager::counter_name("tlab", "slowAlloc");
344    _perf_slow_allocations =
345      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_None, CHECK);
346
347    cname = PerfDataManager::counter_name("tlab", "maxSlowAlloc");
348    _perf_max_slow_allocations =
349      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_None, CHECK);
350  }
351}
352
353void GlobalTLABStats::initialize() {
354  // Clear counters summarizing info from all threads
355  _allocating_threads      = 0;
356  _total_refills           = 0;
357  _max_refills             = 0;
358  _total_allocation        = 0;
359  _total_gc_waste          = 0;
360  _max_gc_waste            = 0;
361  _total_slow_refill_waste = 0;
362  _max_slow_refill_waste   = 0;
363  _total_fast_refill_waste = 0;
364  _max_fast_refill_waste   = 0;
365  _total_slow_allocations  = 0;
366  _max_slow_allocations    = 0;
367}
368
369void GlobalTLABStats::publish() {
370  _allocating_threads_avg.sample(_allocating_threads);
371  if (UsePerfData) {
372    _perf_allocating_threads   ->set_value(_allocating_threads);
373    _perf_total_refills        ->set_value(_total_refills);
374    _perf_max_refills          ->set_value(_max_refills);
375    _perf_allocation           ->set_value(_total_allocation);
376    _perf_gc_waste             ->set_value(_total_gc_waste);
377    _perf_max_gc_waste         ->set_value(_max_gc_waste);
378    _perf_slow_refill_waste    ->set_value(_total_slow_refill_waste);
379    _perf_max_slow_refill_waste->set_value(_max_slow_refill_waste);
380    _perf_fast_refill_waste    ->set_value(_total_fast_refill_waste);
381    _perf_max_fast_refill_waste->set_value(_max_fast_refill_waste);
382    _perf_slow_allocations     ->set_value(_total_slow_allocations);
383    _perf_max_slow_allocations ->set_value(_max_slow_allocations);
384  }
385}
386
387void GlobalTLABStats::print() {
388  LogHandle(gc, tlab) log;
389  if (!log.is_debug()) {
390    return;
391  }
392
393  size_t waste = _total_gc_waste + _total_slow_refill_waste + _total_fast_refill_waste;
394  double waste_percent = _total_allocation == 0 ? 0.0 :
395                         100.0 * waste / _total_allocation;
396  log.debug("TLAB totals: thrds: %d  refills: %d max: %d"
397            " slow allocs: %d max %d waste: %4.1f%%"
398            " gc: " SIZE_FORMAT "B max: " SIZE_FORMAT "B"
399            " slow: " SIZE_FORMAT "B max: " SIZE_FORMAT "B"
400            " fast: " SIZE_FORMAT "B max: " SIZE_FORMAT "B",
401            _allocating_threads,
402            _total_refills, _max_refills,
403            _total_slow_allocations, _max_slow_allocations,
404            waste_percent,
405            _total_gc_waste * HeapWordSize,
406            _max_gc_waste * HeapWordSize,
407            _total_slow_refill_waste * HeapWordSize,
408            _max_slow_refill_waste * HeapWordSize,
409            _total_fast_refill_waste * HeapWordSize,
410            _max_fast_refill_waste * HeapWordSize);
411}
412