parCardTableModRefBS.cpp revision 8528:01d947f8d411
1/*
2 * Copyright (c) 2007, 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/cardTableModRefBS.hpp"
27#include "gc/shared/cardTableRS.hpp"
28#include "gc/shared/collectedHeap.hpp"
29#include "gc/shared/genCollectedHeap.hpp"
30#include "gc/shared/space.inline.hpp"
31#include "memory/allocation.inline.hpp"
32#include "memory/virtualspace.hpp"
33#include "oops/oop.inline.hpp"
34#include "runtime/java.hpp"
35#include "runtime/mutexLocker.hpp"
36#include "runtime/orderAccess.inline.hpp"
37#include "runtime/vmThread.hpp"
38
39void CardTableModRefBS::non_clean_card_iterate_parallel_work(Space* sp, MemRegion mr,
40                                                             OopsInGenClosure* cl,
41                                                             CardTableRS* ct,
42                                                             uint n_threads) {
43  assert(n_threads > 0, "expected n_threads > 0");
44  assert(n_threads <= ParallelGCThreads,
45         err_msg("n_threads: %u > ParallelGCThreads: %u", n_threads, ParallelGCThreads));
46
47  // Make sure the LNC array is valid for the space.
48  jbyte**   lowest_non_clean;
49  uintptr_t lowest_non_clean_base_chunk_index;
50  size_t    lowest_non_clean_chunk_size;
51  get_LNC_array_for_space(sp, lowest_non_clean,
52                          lowest_non_clean_base_chunk_index,
53                          lowest_non_clean_chunk_size);
54
55  uint n_strides = n_threads * ParGCStridesPerThread;
56  SequentialSubTasksDone* pst = sp->par_seq_tasks();
57  // Sets the condition for completion of the subtask (how many threads
58  // need to finish in order to be done).
59  pst->set_n_threads(n_threads);
60  pst->set_n_tasks(n_strides);
61
62  uint stride = 0;
63  while (!pst->is_task_claimed(/* reference */ stride)) {
64    process_stride(sp, mr, stride, n_strides,
65                   cl, ct,
66                   lowest_non_clean,
67                   lowest_non_clean_base_chunk_index,
68                   lowest_non_clean_chunk_size);
69  }
70  if (pst->all_tasks_completed()) {
71    // Clear lowest_non_clean array for next time.
72    intptr_t first_chunk_index = addr_to_chunk_index(mr.start());
73    uintptr_t last_chunk_index  = addr_to_chunk_index(mr.last());
74    for (uintptr_t ch = first_chunk_index; ch <= last_chunk_index; ch++) {
75      intptr_t ind = ch - lowest_non_clean_base_chunk_index;
76      assert(0 <= ind && ind < (intptr_t)lowest_non_clean_chunk_size,
77             "Bounds error");
78      lowest_non_clean[ind] = NULL;
79    }
80  }
81}
82
83void
84CardTableModRefBS::
85process_stride(Space* sp,
86               MemRegion used,
87               jint stride, int n_strides,
88               OopsInGenClosure* cl,
89               CardTableRS* ct,
90               jbyte** lowest_non_clean,
91               uintptr_t lowest_non_clean_base_chunk_index,
92               size_t    lowest_non_clean_chunk_size) {
93  // We go from higher to lower addresses here; it wouldn't help that much
94  // because of the strided parallelism pattern used here.
95
96  // Find the first card address of the first chunk in the stride that is
97  // at least "bottom" of the used region.
98  jbyte*    start_card  = byte_for(used.start());
99  jbyte*    end_card    = byte_after(used.last());
100  uintptr_t start_chunk = addr_to_chunk_index(used.start());
101  uintptr_t start_chunk_stride_num = start_chunk % n_strides;
102  jbyte* chunk_card_start;
103
104  if ((uintptr_t)stride >= start_chunk_stride_num) {
105    chunk_card_start = (jbyte*)(start_card +
106                                (stride - start_chunk_stride_num) *
107                                ParGCCardsPerStrideChunk);
108  } else {
109    // Go ahead to the next chunk group boundary, then to the requested stride.
110    chunk_card_start = (jbyte*)(start_card +
111                                (n_strides - start_chunk_stride_num + stride) *
112                                ParGCCardsPerStrideChunk);
113  }
114
115  while (chunk_card_start < end_card) {
116    // Even though we go from lower to higher addresses below, the
117    // strided parallelism can interleave the actual processing of the
118    // dirty pages in various ways. For a specific chunk within this
119    // stride, we take care to avoid double scanning or missing a card
120    // by suitably initializing the "min_done" field in process_chunk_boundaries()
121    // below, together with the dirty region extension accomplished in
122    // DirtyCardToOopClosure::do_MemRegion().
123    jbyte*    chunk_card_end = chunk_card_start + ParGCCardsPerStrideChunk;
124    // Invariant: chunk_mr should be fully contained within the "used" region.
125    MemRegion chunk_mr       = MemRegion(addr_for(chunk_card_start),
126                                         chunk_card_end >= end_card ?
127                                           used.end() : addr_for(chunk_card_end));
128    assert(chunk_mr.word_size() > 0, "[chunk_card_start > used_end)");
129    assert(used.contains(chunk_mr), "chunk_mr should be subset of used");
130
131    // This function is used by the parallel card table iteration.
132    const bool parallel = true;
133
134    DirtyCardToOopClosure* dcto_cl = sp->new_dcto_cl(cl, precision(),
135                                                     cl->gen_boundary(),
136                                                     parallel);
137    ClearNoncleanCardWrapper clear_cl(dcto_cl, ct, parallel);
138
139
140    // Process the chunk.
141    process_chunk_boundaries(sp,
142                             dcto_cl,
143                             chunk_mr,
144                             used,
145                             lowest_non_clean,
146                             lowest_non_clean_base_chunk_index,
147                             lowest_non_clean_chunk_size);
148
149    // We want the LNC array updates above in process_chunk_boundaries
150    // to be visible before any of the card table value changes as a
151    // result of the dirty card iteration below.
152    OrderAccess::storestore();
153
154    // We want to clear the cards: clear_cl here does the work of finding
155    // contiguous dirty ranges of cards to process and clear.
156    clear_cl.do_MemRegion(chunk_mr);
157
158    // Find the next chunk of the stride.
159    chunk_card_start += ParGCCardsPerStrideChunk * n_strides;
160  }
161}
162
163
164// If you want a talkative process_chunk_boundaries,
165// then #define NOISY(x) x
166#ifdef NOISY
167#error "Encountered a global preprocessor flag, NOISY, which might clash with local definition to follow"
168#else
169#define NOISY(x)
170#endif
171
172void
173CardTableModRefBS::
174process_chunk_boundaries(Space* sp,
175                         DirtyCardToOopClosure* dcto_cl,
176                         MemRegion chunk_mr,
177                         MemRegion used,
178                         jbyte** lowest_non_clean,
179                         uintptr_t lowest_non_clean_base_chunk_index,
180                         size_t    lowest_non_clean_chunk_size)
181{
182  // We must worry about non-array objects that cross chunk boundaries,
183  // because such objects are both precisely and imprecisely marked:
184  // .. if the head of such an object is dirty, the entire object
185  //    needs to be scanned, under the interpretation that this
186  //    was an imprecise mark
187  // .. if the head of such an object is not dirty, we can assume
188  //    precise marking and it's efficient to scan just the dirty
189  //    cards.
190  // In either case, each scanned reference must be scanned precisely
191  // once so as to avoid cloning of a young referent. For efficiency,
192  // our closures depend on this property and do not protect against
193  // double scans.
194
195  uintptr_t start_chunk_index = addr_to_chunk_index(chunk_mr.start());
196  assert(start_chunk_index >= lowest_non_clean_base_chunk_index, "Bounds error.");
197  uintptr_t cur_chunk_index   = start_chunk_index - lowest_non_clean_base_chunk_index;
198
199  NOISY(tty->print_cr("===========================================================================");)
200  NOISY(tty->print_cr(" process_chunk_boundary: Called with [" PTR_FORMAT "," PTR_FORMAT ")",
201                      chunk_mr.start(), chunk_mr.end());)
202
203  // First, set "our" lowest_non_clean entry, which would be
204  // used by the thread scanning an adjoining left chunk with
205  // a non-array object straddling the mutual boundary.
206  // Find the object that spans our boundary, if one exists.
207  // first_block is the block possibly straddling our left boundary.
208  HeapWord* first_block = sp->block_start(chunk_mr.start());
209  assert((chunk_mr.start() != used.start()) || (first_block == chunk_mr.start()),
210         "First chunk should always have a co-initial block");
211  // Does the block straddle the chunk's left boundary, and is it
212  // a non-array object?
213  if (first_block < chunk_mr.start()        // first block straddles left bdry
214      && sp->block_is_obj(first_block)      // first block is an object
215      && !(oop(first_block)->is_objArray()  // first block is not an array (arrays are precisely dirtied)
216           || oop(first_block)->is_typeArray())) {
217    // Find our least non-clean card, so that a left neighbor
218    // does not scan an object straddling the mutual boundary
219    // too far to the right, and attempt to scan a portion of
220    // that object twice.
221    jbyte* first_dirty_card = NULL;
222    jbyte* last_card_of_first_obj =
223        byte_for(first_block + sp->block_size(first_block) - 1);
224    jbyte* first_card_of_cur_chunk = byte_for(chunk_mr.start());
225    jbyte* last_card_of_cur_chunk = byte_for(chunk_mr.last());
226    jbyte* last_card_to_check =
227      (jbyte*) MIN2((intptr_t) last_card_of_cur_chunk,
228                    (intptr_t) last_card_of_first_obj);
229    // Note that this does not need to go beyond our last card
230    // if our first object completely straddles this chunk.
231    for (jbyte* cur = first_card_of_cur_chunk;
232         cur <= last_card_to_check; cur++) {
233      jbyte val = *cur;
234      if (card_will_be_scanned(val)) {
235        first_dirty_card = cur; break;
236      } else {
237        assert(!card_may_have_been_dirty(val), "Error");
238      }
239    }
240    if (first_dirty_card != NULL) {
241      NOISY(tty->print_cr(" LNC: Found a dirty card at " PTR_FORMAT " in current chunk",
242                    first_dirty_card);)
243      assert(cur_chunk_index < lowest_non_clean_chunk_size, "Bounds error.");
244      assert(lowest_non_clean[cur_chunk_index] == NULL,
245             "Write exactly once : value should be stable hereafter for this round");
246      lowest_non_clean[cur_chunk_index] = first_dirty_card;
247    } NOISY(else {
248      tty->print_cr(" LNC: Found no dirty card in current chunk; leaving LNC entry NULL");
249      // In the future, we could have this thread look for a non-NULL value to copy from its
250      // right neighbor (up to the end of the first object).
251      if (last_card_of_cur_chunk < last_card_of_first_obj) {
252        tty->print_cr(" LNC: BEWARE!!! first obj straddles past right end of chunk:\n"
253                      "   might be efficient to get value from right neighbor?");
254      }
255    })
256  } else {
257    // In this case we can help our neighbor by just asking them
258    // to stop at our first card (even though it may not be dirty).
259    NOISY(tty->print_cr(" LNC: first block is not a non-array object; setting LNC to first card of current chunk");)
260    assert(lowest_non_clean[cur_chunk_index] == NULL, "Write once : value should be stable hereafter");
261    jbyte* first_card_of_cur_chunk = byte_for(chunk_mr.start());
262    lowest_non_clean[cur_chunk_index] = first_card_of_cur_chunk;
263  }
264  NOISY(tty->print_cr(" process_chunk_boundary: lowest_non_clean[" INTPTR_FORMAT "] = " PTR_FORMAT
265                "   which corresponds to the heap address " PTR_FORMAT,
266                cur_chunk_index, lowest_non_clean[cur_chunk_index],
267                (lowest_non_clean[cur_chunk_index] != NULL)
268                ? addr_for(lowest_non_clean[cur_chunk_index])
269                : NULL);)
270  NOISY(tty->print_cr("---------------------------------------------------------------------------");)
271
272  // Next, set our own max_to_do, which will strictly/exclusively bound
273  // the highest address that we will scan past the right end of our chunk.
274  HeapWord* max_to_do = NULL;
275  if (chunk_mr.end() < used.end()) {
276    // This is not the last chunk in the used region.
277    // What is our last block? We check the first block of
278    // the next (right) chunk rather than strictly check our last block
279    // because it's potentially more efficient to do so.
280    HeapWord* const last_block = sp->block_start(chunk_mr.end());
281    assert(last_block <= chunk_mr.end(), "In case this property changes.");
282    if ((last_block == chunk_mr.end())     // our last block does not straddle boundary
283        || !sp->block_is_obj(last_block)   // last_block isn't an object
284        || oop(last_block)->is_objArray()  // last_block is an array (precisely marked)
285        || oop(last_block)->is_typeArray()) {
286      max_to_do = chunk_mr.end();
287      NOISY(tty->print_cr(" process_chunk_boundary: Last block on this card is not a non-array object;\n"
288                         "   max_to_do left at " PTR_FORMAT, max_to_do);)
289    } else {
290      assert(last_block < chunk_mr.end(), "Tautology");
291      // It is a non-array object that straddles the right boundary of this chunk.
292      // last_obj_card is the card corresponding to the start of the last object
293      // in the chunk.  Note that the last object may not start in
294      // the chunk.
295      jbyte* const last_obj_card = byte_for(last_block);
296      const jbyte val = *last_obj_card;
297      if (!card_will_be_scanned(val)) {
298        assert(!card_may_have_been_dirty(val), "Error");
299        // The card containing the head is not dirty.  Any marks on
300        // subsequent cards still in this chunk must have been made
301        // precisely; we can cap processing at the end of our chunk.
302        max_to_do = chunk_mr.end();
303        NOISY(tty->print_cr(" process_chunk_boundary: Head of last object on this card is not dirty;\n"
304                            "   max_to_do left at " PTR_FORMAT,
305                            max_to_do);)
306      } else {
307        // The last object must be considered dirty, and extends onto the
308        // following chunk.  Look for a dirty card in that chunk that will
309        // bound our processing.
310        jbyte* limit_card = NULL;
311        const size_t last_block_size = sp->block_size(last_block);
312        jbyte* const last_card_of_last_obj =
313          byte_for(last_block + last_block_size - 1);
314        jbyte* const first_card_of_next_chunk = byte_for(chunk_mr.end());
315        // This search potentially goes a long distance looking
316        // for the next card that will be scanned, terminating
317        // at the end of the last_block, if no earlier dirty card
318        // is found.
319        assert(byte_for(chunk_mr.end()) - byte_for(chunk_mr.start()) == ParGCCardsPerStrideChunk,
320               "last card of next chunk may be wrong");
321        for (jbyte* cur = first_card_of_next_chunk;
322             cur <= last_card_of_last_obj; cur++) {
323          const jbyte val = *cur;
324          if (card_will_be_scanned(val)) {
325            NOISY(tty->print_cr(" Found a non-clean card " PTR_FORMAT " with value 0x%x",
326                                cur, (int)val);)
327            limit_card = cur; break;
328          } else {
329            assert(!card_may_have_been_dirty(val), "Error: card can't be skipped");
330          }
331        }
332        if (limit_card != NULL) {
333          max_to_do = addr_for(limit_card);
334          assert(limit_card != NULL && max_to_do != NULL, "Error");
335          NOISY(tty->print_cr(" process_chunk_boundary: Found a dirty card at " PTR_FORMAT
336                        "   max_to_do set at " PTR_FORMAT " which is before end of last block in chunk: "
337                        PTR_FORMAT " + " PTR_FORMAT " = " PTR_FORMAT,
338                        limit_card, max_to_do, last_block, last_block_size, (last_block+last_block_size));)
339        } else {
340          // The following is a pessimistic value, because it's possible
341          // that a dirty card on a subsequent chunk has been cleared by
342          // the time we get to look at it; we'll correct for that further below,
343          // using the LNC array which records the least non-clean card
344          // before cards were cleared in a particular chunk.
345          limit_card = last_card_of_last_obj;
346          max_to_do = last_block + last_block_size;
347          assert(limit_card != NULL && max_to_do != NULL, "Error");
348          NOISY(tty->print_cr(" process_chunk_boundary: Found no dirty card before end of last block in chunk\n"
349                              "   Setting limit_card to " PTR_FORMAT
350                              " and max_to_do " PTR_FORMAT " + " PTR_FORMAT " = " PTR_FORMAT,
351                              limit_card, last_block, last_block_size, max_to_do);)
352        }
353        assert(0 < cur_chunk_index+1 && cur_chunk_index+1 < lowest_non_clean_chunk_size,
354               "Bounds error.");
355        // It is possible that a dirty card for the last object may have been
356        // cleared before we had a chance to examine it. In that case, the value
357        // will have been logged in the LNC for that chunk.
358        // We need to examine as many chunks to the right as this object
359        // covers. However, we need to bound this checking to the largest
360        // entry in the LNC array: this is because the heap may expand
361        // after the LNC array has been created but before we reach this point,
362        // and the last block in our chunk may have been expanded to include
363        // the expansion delta (and possibly subsequently allocated from, so
364        // it wouldn't be sufficient to check whether that last block was
365        // or was not an object at this point).
366        uintptr_t last_chunk_index_to_check = addr_to_chunk_index(last_block + last_block_size - 1)
367                                              - lowest_non_clean_base_chunk_index;
368        const uintptr_t last_chunk_index    = addr_to_chunk_index(used.last())
369                                              - lowest_non_clean_base_chunk_index;
370        if (last_chunk_index_to_check > last_chunk_index) {
371          assert(last_block + last_block_size > used.end(),
372                 err_msg("Inconsistency detected: last_block [" PTR_FORMAT "," PTR_FORMAT "]"
373                         " does not exceed used.end() = " PTR_FORMAT ","
374                         " yet last_chunk_index_to_check " INTPTR_FORMAT
375                         " exceeds last_chunk_index " INTPTR_FORMAT,
376                         p2i(last_block), p2i(last_block + last_block_size),
377                         p2i(used.end()),
378                         last_chunk_index_to_check, last_chunk_index));
379          assert(sp->used_region().end() > used.end(),
380                 err_msg("Expansion did not happen: "
381                         "[" PTR_FORMAT "," PTR_FORMAT ") -> [" PTR_FORMAT "," PTR_FORMAT ")",
382                         p2i(sp->used_region().start()), p2i(sp->used_region().end()),
383                         p2i(used.start()), p2i(used.end())));
384          NOISY(tty->print_cr(" process_chunk_boundary: heap expanded; explicitly bounding last_chunk");)
385          last_chunk_index_to_check = last_chunk_index;
386        }
387        for (uintptr_t lnc_index = cur_chunk_index + 1;
388             lnc_index <= last_chunk_index_to_check;
389             lnc_index++) {
390          jbyte* lnc_card = lowest_non_clean[lnc_index];
391          if (lnc_card != NULL) {
392            // we can stop at the first non-NULL entry we find
393            if (lnc_card <= limit_card) {
394              NOISY(tty->print_cr(" process_chunk_boundary: LNC card " PTR_FORMAT " is lower than limit_card " PTR_FORMAT,
395                                  "   max_to_do will be lowered to " PTR_FORMAT " from " PTR_FORMAT,
396                                  lnc_card, limit_card, addr_for(lnc_card), max_to_do);)
397              limit_card = lnc_card;
398              max_to_do = addr_for(limit_card);
399              assert(limit_card != NULL && max_to_do != NULL, "Error");
400            }
401            // In any case, we break now
402            break;
403          }  // else continue to look for a non-NULL entry if any
404        }
405        assert(limit_card != NULL && max_to_do != NULL, "Error");
406      }
407      assert(max_to_do != NULL, "OOPS 1 !");
408    }
409    assert(max_to_do != NULL, "OOPS 2!");
410  } else {
411    max_to_do = used.end();
412    NOISY(tty->print_cr(" process_chunk_boundary: Last chunk of this space;\n"
413                  "   max_to_do left at " PTR_FORMAT,
414                  max_to_do);)
415  }
416  assert(max_to_do != NULL, "OOPS 3!");
417  // Now we can set the closure we're using so it doesn't to beyond
418  // max_to_do.
419  dcto_cl->set_min_done(max_to_do);
420#ifndef PRODUCT
421  dcto_cl->set_last_bottom(max_to_do);
422#endif
423  NOISY(tty->print_cr("===========================================================================\n");)
424}
425
426#undef NOISY
427
428void
429CardTableModRefBS::
430get_LNC_array_for_space(Space* sp,
431                        jbyte**& lowest_non_clean,
432                        uintptr_t& lowest_non_clean_base_chunk_index,
433                        size_t& lowest_non_clean_chunk_size) {
434
435  int       i        = find_covering_region_containing(sp->bottom());
436  MemRegion covered  = _covered[i];
437  size_t    n_chunks = chunks_to_cover(covered);
438
439  // Only the first thread to obtain the lock will resize the
440  // LNC array for the covered region.  Any later expansion can't affect
441  // the used_at_save_marks region.
442  // (I observed a bug in which the first thread to execute this would
443  // resize, and then it would cause "expand_and_allocate" that would
444  // increase the number of chunks in the covered region.  Then a second
445  // thread would come and execute this, see that the size didn't match,
446  // and free and allocate again.  So the first thread would be using a
447  // freed "_lowest_non_clean" array.)
448
449  // Do a dirty read here. If we pass the conditional then take the rare
450  // event lock and do the read again in case some other thread had already
451  // succeeded and done the resize.
452  int cur_collection = GenCollectedHeap::heap()->total_collections();
453  if (_last_LNC_resizing_collection[i] != cur_collection) {
454    MutexLocker x(ParGCRareEvent_lock);
455    if (_last_LNC_resizing_collection[i] != cur_collection) {
456      if (_lowest_non_clean[i] == NULL ||
457          n_chunks != _lowest_non_clean_chunk_size[i]) {
458
459        // Should we delete the old?
460        if (_lowest_non_clean[i] != NULL) {
461          assert(n_chunks != _lowest_non_clean_chunk_size[i],
462                 "logical consequence");
463          FREE_C_HEAP_ARRAY(CardPtr, _lowest_non_clean[i]);
464          _lowest_non_clean[i] = NULL;
465        }
466        // Now allocate a new one if necessary.
467        if (_lowest_non_clean[i] == NULL) {
468          _lowest_non_clean[i]                  = NEW_C_HEAP_ARRAY(CardPtr, n_chunks, mtGC);
469          _lowest_non_clean_chunk_size[i]       = n_chunks;
470          _lowest_non_clean_base_chunk_index[i] = addr_to_chunk_index(covered.start());
471          for (int j = 0; j < (int)n_chunks; j++)
472            _lowest_non_clean[i][j] = NULL;
473        }
474      }
475      _last_LNC_resizing_collection[i] = cur_collection;
476    }
477  }
478  // In any case, now do the initialization.
479  lowest_non_clean                  = _lowest_non_clean[i];
480  lowest_non_clean_base_chunk_index = _lowest_non_clean_base_chunk_index[i];
481  lowest_non_clean_chunk_size       = _lowest_non_clean_chunk_size[i];
482}
483