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