1 /*
  2  * Copyright (c) 1997, 2021, 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/vmClasses.hpp"
 27 #include "classfile/vmSymbols.hpp"
 28 #include "gc/shared/blockOffsetTable.inline.hpp"
 29 #include "gc/shared/collectedHeap.inline.hpp"
 30 #include "gc/shared/genCollectedHeap.hpp"
 31 #include "gc/shared/genOopClosures.inline.hpp"
 32 #include "gc/shared/slidingForwarding.inline.hpp"
 33 #include "gc/shared/space.hpp"
 34 #include "gc/shared/space.inline.hpp"
 35 #include "gc/shared/spaceDecorator.inline.hpp"
 36 #include "memory/iterator.inline.hpp"
 37 #include "memory/universe.hpp"
 38 #include "oops/oop.inline.hpp"
 39 #include "runtime/atomic.hpp"
 40 #include "runtime/java.hpp"
 41 #include "runtime/prefetch.inline.hpp"
 42 #include "runtime/safepoint.hpp"
 43 #include "utilities/align.hpp"
 44 #include "utilities/copy.hpp"
 45 #include "utilities/globalDefinitions.hpp"
 46 #include "utilities/macros.hpp"
 47 #if INCLUDE_SERIALGC
 48 #include "gc/serial/defNewGeneration.hpp"
 49 #endif
 50 
 51 HeapWord* DirtyCardToOopClosure::get_actual_top(HeapWord* top,
 52                                                 HeapWord* top_obj) {
 53   if (top_obj != NULL) {
 54     if (_sp->block_is_obj(top_obj)) {
 55       if (_precision == CardTable::ObjHeadPreciseArray) {
 56         if (cast_to_oop(top_obj)->is_objArray() || cast_to_oop(top_obj)->is_typeArray()) {
 57           // An arrayOop is starting on the dirty card - since we do exact
 58           // store checks for objArrays we are done.
 59         } else {
 60           // Otherwise, it is possible that the object starting on the dirty
 61           // card spans the entire card, and that the store happened on a
 62           // later card.  Figure out where the object ends.
 63           // Use the block_size() method of the space over which
 64           // the iteration is being done.  That space (e.g. CMS) may have
 65           // specific requirements on object sizes which will
 66           // be reflected in the block_size() method.
 67           top = top_obj + cast_to_oop(top_obj)->size();
 68         }
 69       }
 70     } else {
 71       top = top_obj;
 72     }
 73   } else {
 74     assert(top == _sp->end(), "only case where top_obj == NULL");
 75   }
 76   return top;
 77 }
 78 
 79 void DirtyCardToOopClosure::walk_mem_region(MemRegion mr,
 80                                             HeapWord* bottom,
 81                                             HeapWord* top) {
 82   // 1. Blocks may or may not be objects.
 83   // 2. Even when a block_is_obj(), it may not entirely
 84   //    occupy the block if the block quantum is larger than
 85   //    the object size.
 86   // We can and should try to optimize by calling the non-MemRegion
 87   // version of oop_iterate() for all but the extremal objects
 88   // (for which we need to call the MemRegion version of
 89   // oop_iterate()) To be done post-beta XXX
 90   for (; bottom < top; bottom += _sp->block_size(bottom)) {
 91     // As in the case of contiguous space above, we'd like to
 92     // just use the value returned by oop_iterate to increment the
 93     // current pointer; unfortunately, that won't work in CMS because
 94     // we'd need an interface change (it seems) to have the space
 95     // "adjust the object size" (for instance pad it up to its
 96     // block alignment or minimum block size restrictions. XXX
 97     if (_sp->block_is_obj(bottom) &&
 98         !_sp->obj_allocated_since_save_marks(cast_to_oop(bottom))) {
 99       cast_to_oop(bottom)->oop_iterate(_cl, mr);
100     }
101   }
102 }
103 
104 // We get called with "mr" representing the dirty region
105 // that we want to process. Because of imprecise marking,
106 // we may need to extend the incoming "mr" to the right,
107 // and scan more. However, because we may already have
108 // scanned some of that extended region, we may need to
109 // trim its right-end back some so we do not scan what
110 // we (or another worker thread) may already have scanned
111 // or planning to scan.
112 void DirtyCardToOopClosure::do_MemRegion(MemRegion mr) {
113   HeapWord* bottom = mr.start();
114   HeapWord* last = mr.last();
115   HeapWord* top = mr.end();
116   HeapWord* bottom_obj;
117   HeapWord* top_obj;
118 
119   assert(_precision == CardTable::ObjHeadPreciseArray ||
120          _precision == CardTable::Precise,
121          "Only ones we deal with for now.");
122 
123   assert(_precision != CardTable::ObjHeadPreciseArray ||
124          _last_bottom == NULL || top <= _last_bottom,
125          "Not decreasing");
126   NOT_PRODUCT(_last_bottom = mr.start());
127 
128   bottom_obj = _sp->block_start(bottom);
129   top_obj    = _sp->block_start(last);
130 
131   assert(bottom_obj <= bottom, "just checking");
132   assert(top_obj    <= top,    "just checking");
133 
134   // Given what we think is the top of the memory region and
135   // the start of the object at the top, get the actual
136   // value of the top.
137   top = get_actual_top(top, top_obj);
138 
139   // If the previous call did some part of this region, don't redo.
140   if (_precision == CardTable::ObjHeadPreciseArray &&
141       _min_done != NULL &&
142       _min_done < top) {
143     top = _min_done;
144   }
145 
146   // Top may have been reset, and in fact may be below bottom,
147   // e.g. the dirty card region is entirely in a now free object
148   // -- something that could happen with a concurrent sweeper.
149   bottom = MIN2(bottom, top);
150   MemRegion extended_mr = MemRegion(bottom, top);
151   assert(bottom <= top &&
152          (_precision != CardTable::ObjHeadPreciseArray ||
153           _min_done == NULL ||
154           top <= _min_done),
155          "overlap!");
156 
157   // Walk the region if it is not empty; otherwise there is nothing to do.
158   if (!extended_mr.is_empty()) {
159     walk_mem_region(extended_mr, bottom_obj, top);
160   }
161 
162   _min_done = bottom;
163 }
164 
165 DirtyCardToOopClosure* Space::new_dcto_cl(OopIterateClosure* cl,
166                                           CardTable::PrecisionStyle precision,
167                                           HeapWord* boundary) {
168   return new DirtyCardToOopClosure(this, cl, precision, boundary);
169 }
170 
171 HeapWord* ContiguousSpaceDCTOC::get_actual_top(HeapWord* top,
172                                                HeapWord* top_obj) {
173   if (top_obj != NULL && top_obj < (_sp->toContiguousSpace())->top()) {
174     if (_precision == CardTable::ObjHeadPreciseArray) {
175       if (cast_to_oop(top_obj)->is_objArray() || cast_to_oop(top_obj)->is_typeArray()) {
176         // An arrayOop is starting on the dirty card - since we do exact
177         // store checks for objArrays we are done.
178       } else {
179         // Otherwise, it is possible that the object starting on the dirty
180         // card spans the entire card, and that the store happened on a
181         // later card.  Figure out where the object ends.
182         assert(_sp->block_size(top_obj) == cast_to_oop(top_obj)->size(),
183           "Block size and object size mismatch");
184         top = top_obj + cast_to_oop(top_obj)->size();
185       }
186     }
187   } else {
188     top = (_sp->toContiguousSpace())->top();
189   }
190   return top;
191 }
192 
193 void FilteringDCTOC::walk_mem_region(MemRegion mr,
194                                      HeapWord* bottom,
195                                      HeapWord* top) {
196   // Note that this assumption won't hold if we have a concurrent
197   // collector in this space, which may have freed up objects after
198   // they were dirtied and before the stop-the-world GC that is
199   // examining cards here.
200   assert(bottom < top, "ought to be at least one obj on a dirty card.");
201 
202   if (_boundary != NULL) {
203     // We have a boundary outside of which we don't want to look
204     // at objects, so create a filtering closure around the
205     // oop closure before walking the region.
206     FilteringClosure filter(_boundary, _cl);
207     walk_mem_region_with_cl(mr, bottom, top, &filter);
208   } else {
209     // No boundary, simply walk the heap with the oop closure.
210     walk_mem_region_with_cl(mr, bottom, top, _cl);
211   }
212 
213 }
214 
215 // We must replicate this so that the static type of "FilteringClosure"
216 // (see above) is apparent at the oop_iterate calls.
217 #define ContiguousSpaceDCTOC__walk_mem_region_with_cl_DEFN(ClosureType) \
218 void ContiguousSpaceDCTOC::walk_mem_region_with_cl(MemRegion mr,        \
219                                                    HeapWord* bottom,    \
220                                                    HeapWord* top,       \
221                                                    ClosureType* cl) {   \
222   bottom += cast_to_oop(bottom)->oop_iterate_size(cl, mr);              \
223   if (bottom < top) {                                                   \
224     HeapWord* next_obj = bottom + cast_to_oop(bottom)->size();          \
225     while (next_obj < top) {                                            \
226       /* Bottom lies entirely below top, so we can call the */          \
227       /* non-memRegion version of oop_iterate below. */                 \
228       cast_to_oop(bottom)->oop_iterate(cl);                             \
229       bottom = next_obj;                                                \
230       next_obj = bottom + cast_to_oop(bottom)->size();                  \
231     }                                                                   \
232     /* Last object. */                                                  \
233     cast_to_oop(bottom)->oop_iterate(cl, mr);                           \
234   }                                                                     \
235 }
236 
237 // (There are only two of these, rather than N, because the split is due
238 // only to the introduction of the FilteringClosure, a local part of the
239 // impl of this abstraction.)
240 ContiguousSpaceDCTOC__walk_mem_region_with_cl_DEFN(OopIterateClosure)
241 ContiguousSpaceDCTOC__walk_mem_region_with_cl_DEFN(FilteringClosure)
242 
243 DirtyCardToOopClosure*
244 ContiguousSpace::new_dcto_cl(OopIterateClosure* cl,
245                              CardTable::PrecisionStyle precision,
246                              HeapWord* boundary) {
247   return new ContiguousSpaceDCTOC(this, cl, precision, boundary);
248 }
249 
250 void Space::initialize(MemRegion mr,
251                        bool clear_space,
252                        bool mangle_space) {
253   HeapWord* bottom = mr.start();
254   HeapWord* end    = mr.end();
255   assert(Universe::on_page_boundary(bottom) && Universe::on_page_boundary(end),
256          "invalid space boundaries");
257   set_bottom(bottom);
258   set_end(end);
259   if (clear_space) clear(mangle_space);
260 }
261 
262 void Space::clear(bool mangle_space) {
263   if (ZapUnusedHeapArea && mangle_space) {
264     mangle_unused_area();
265   }
266 }
267 
268 ContiguousSpace::ContiguousSpace(): CompactibleSpace(), _top(NULL) {
269   _mangler = new GenSpaceMangler(this);
270 }
271 
272 ContiguousSpace::~ContiguousSpace() {
273   delete _mangler;
274 }
275 
276 void ContiguousSpace::initialize(MemRegion mr,
277                                  bool clear_space,
278                                  bool mangle_space)
279 {
280   CompactibleSpace::initialize(mr, clear_space, mangle_space);
281 }
282 
283 void ContiguousSpace::clear(bool mangle_space) {
284   set_top(bottom());
285   set_saved_mark();
286   CompactibleSpace::clear(mangle_space);
287 }
288 
289 bool ContiguousSpace::is_free_block(const HeapWord* p) const {
290   return p >= _top;
291 }
292 
293 void OffsetTableContigSpace::clear(bool mangle_space) {
294   ContiguousSpace::clear(mangle_space);
295   _offsets.initialize_threshold();
296 }
297 
298 void OffsetTableContigSpace::set_bottom(HeapWord* new_bottom) {
299   Space::set_bottom(new_bottom);
300   _offsets.set_bottom(new_bottom);
301 }
302 
303 void OffsetTableContigSpace::set_end(HeapWord* new_end) {
304   // Space should not advertise an increase in size
305   // until after the underlying offset table has been enlarged.
306   _offsets.resize(pointer_delta(new_end, bottom()));
307   Space::set_end(new_end);
308 }
309 
310 #ifndef PRODUCT
311 
312 void ContiguousSpace::set_top_for_allocations(HeapWord* v) {
313   mangler()->set_top_for_allocations(v);
314 }
315 void ContiguousSpace::set_top_for_allocations() {
316   mangler()->set_top_for_allocations(top());
317 }
318 void ContiguousSpace::check_mangled_unused_area(HeapWord* limit) {
319   mangler()->check_mangled_unused_area(limit);
320 }
321 
322 void ContiguousSpace::check_mangled_unused_area_complete() {
323   mangler()->check_mangled_unused_area_complete();
324 }
325 
326 // Mangled only the unused space that has not previously
327 // been mangled and that has not been allocated since being
328 // mangled.
329 void ContiguousSpace::mangle_unused_area() {
330   mangler()->mangle_unused_area();
331 }
332 void ContiguousSpace::mangle_unused_area_complete() {
333   mangler()->mangle_unused_area_complete();
334 }
335 #endif  // NOT_PRODUCT
336 
337 void CompactibleSpace::initialize(MemRegion mr,
338                                   bool clear_space,
339                                   bool mangle_space) {
340   Space::initialize(mr, clear_space, mangle_space);
341   set_compaction_top(bottom());
342   _next_compaction_space = NULL;
343 }
344 
345 void CompactibleSpace::clear(bool mangle_space) {
346   Space::clear(mangle_space);
347   _compaction_top = bottom();
348 }
349 
350 HeapWord* CompactibleSpace::forward(oop q, size_t size,
351                                     CompactPoint* cp, HeapWord* compact_top, SlidingForwarding* const forwarding) {
352   // q is alive
353   // First check if we should switch compaction space
354   assert(this == cp->space, "'this' should be current compaction space.");
355   size_t compaction_max_size = pointer_delta(end(), compact_top);
356   while (size > compaction_max_size) {
357     // switch to next compaction space
358     cp->space->set_compaction_top(compact_top);
359     cp->space = cp->space->next_compaction_space();
360     if (cp->space == NULL) {
361       cp->gen = GenCollectedHeap::heap()->young_gen();
362       assert(cp->gen != NULL, "compaction must succeed");
363       cp->space = cp->gen->first_compaction_space();
364       assert(cp->space != NULL, "generation must have a first compaction space");
365     }
366     compact_top = cp->space->bottom();
367     cp->space->set_compaction_top(compact_top);
368     cp->space->initialize_threshold();
369     compaction_max_size = pointer_delta(cp->space->end(), compact_top);
370   }
371 
372   // store the forwarding pointer into the mark word
373   if (cast_from_oop<HeapWord*>(q) != compact_top) {
374     forwarding->forward_to(q, cast_to_oop(compact_top));
375     assert(q->is_gc_marked(), "encoding the pointer should preserve the mark");
376   } else {
377     // if the object isn't moving we can just set the mark to the default
378     // mark and handle it specially later on.
379     q->init_mark();
380     assert(!q->is_forwarded(), "should not be forwarded");
381   }
382 
383   compact_top += size;
384 
385   // We need to update the offset table so that the beginnings of objects can be
386   // found during scavenge.  Note that we are updating the offset table based on
387   // where the object will be once the compaction phase finishes.
388   cp->space->alloc_block(compact_top - size, compact_top);
389   return compact_top;
390 }
391 
392 #if INCLUDE_SERIALGC
393 
394 void ContiguousSpace::prepare_for_compaction(CompactPoint* cp) {
395   // Compute the new addresses for the live objects and store it in the mark
396   // Used by universe::mark_sweep_phase2()
397 
398   // We're sure to be here before any objects are compacted into this
399   // space, so this is a good time to initialize this:
400   set_compaction_top(bottom());
401 
402   if (cp->space == NULL) {
403     assert(cp->gen != NULL, "need a generation");
404     assert(cp->gen->first_compaction_space() == this, "just checking");
405     cp->space = cp->gen->first_compaction_space();
406     cp->space->initialize_threshold();
407     cp->space->set_compaction_top(cp->space->bottom());
408   }
409 
410   HeapWord* compact_top = cp->space->compaction_top(); // This is where we are currently compacting to.
411 
412   DeadSpacer dead_spacer(this);
413 
414   HeapWord*  end_of_live = bottom();  // One byte beyond the last byte of the last live object.
415   HeapWord*  first_dead = NULL; // The first dead object.
416 
417   const intx interval = PrefetchScanIntervalInBytes;
418 
419   HeapWord* cur_obj = bottom();
420   HeapWord* scan_limit = top();
421 
422   SlidingForwarding* const forwarding = GenCollectedHeap::heap()->forwarding();
423   while (cur_obj < scan_limit) {
424     if (cast_to_oop(cur_obj)->is_gc_marked()) {
425       // prefetch beyond cur_obj
426       Prefetch::write(cur_obj, interval);
427       size_t size = cast_to_oop(cur_obj)->size();
428       compact_top = cp->space->forward(cast_to_oop(cur_obj), size, cp, compact_top, forwarding);
429       cur_obj += size;
430       end_of_live = cur_obj;
431     } else {
432       // run over all the contiguous dead objects
433       HeapWord* end = cur_obj;
434       do {
435         // prefetch beyond end
436         Prefetch::write(end, interval);
437         end += cast_to_oop(end)->size();
438       } while (end < scan_limit && !cast_to_oop(end)->is_gc_marked());
439 
440       // see if we might want to pretend this object is alive so that
441       // we don't have to compact quite as often.
442       if (cur_obj == compact_top && dead_spacer.insert_deadspace(cur_obj, end)) {
443         oop obj = cast_to_oop(cur_obj);
444         compact_top = cp->space->forward(obj, obj->size(), cp, compact_top, forwarding);
445         end_of_live = end;
446       } else {
447         // otherwise, it really is a free region.
448 
449         // cur_obj is a pointer to a dead object. Use this dead memory to store a pointer to the next live object.
450         *(HeapWord**)cur_obj = end;
451 
452         // see if this is the first dead region.
453         if (first_dead == NULL) {
454           first_dead = cur_obj;
455         }
456       }
457 
458       // move on to the next object
459       cur_obj = end;
460     }
461   }
462 
463   assert(cur_obj == scan_limit, "just checking");
464   _end_of_live = end_of_live;
465   if (first_dead != NULL) {
466     _first_dead = first_dead;
467   } else {
468     _first_dead = end_of_live;
469   }
470 
471   // save the compaction_top of the compaction space.
472   cp->space->set_compaction_top(compact_top);
473 }
474 
475 void CompactibleSpace::adjust_pointers() {
476   // Check first is there is any work to do.
477   if (used() == 0) {
478     return;   // Nothing to do.
479   }
480 
481   // adjust all the interior pointers to point at the new locations of objects
482   // Used by MarkSweep::mark_sweep_phase3()
483 
484   HeapWord* cur_obj = bottom();
485   HeapWord* const end_of_live = _end_of_live;  // Established by prepare_for_compaction().
486   HeapWord* const first_dead = _first_dead;    // Established by prepare_for_compaction().
487   const SlidingForwarding* const forwarding = GenCollectedHeap::heap()->forwarding();
488 
489   assert(first_dead <= end_of_live, "Stands to reason, no?");
490 
491   const intx interval = PrefetchScanIntervalInBytes;
492 
493   debug_only(HeapWord* prev_obj = NULL);
494   while (cur_obj < end_of_live) {
495     Prefetch::write(cur_obj, interval);
496     if (cur_obj < first_dead || cast_to_oop(cur_obj)->is_gc_marked()) {
497       // cur_obj is alive
498       // point all the oops to the new location
499       size_t size = MarkSweep::adjust_pointers(forwarding, cast_to_oop(cur_obj));
500       debug_only(prev_obj = cur_obj);
501       cur_obj += size;
502     } else {
503       debug_only(prev_obj = cur_obj);
504       // cur_obj is not a live object, instead it points at the next live object
505       cur_obj = *(HeapWord**)cur_obj;
506       assert(cur_obj > prev_obj, "we should be moving forward through memory, cur_obj: " PTR_FORMAT ", prev_obj: " PTR_FORMAT, p2i(cur_obj), p2i(prev_obj));
507     }
508   }
509 
510   assert(cur_obj == end_of_live, "just checking");
511 }
512 
513 void CompactibleSpace::compact() {
514   // Copy all live objects to their new location
515   // Used by MarkSweep::mark_sweep_phase4()
516 
517   verify_up_to_first_dead(this);
518 
519   HeapWord* const start = bottom();
520   HeapWord* const end_of_live = _end_of_live;
521 
522   assert(_first_dead <= end_of_live, "Invariant. _first_dead: " PTR_FORMAT " <= end_of_live: " PTR_FORMAT, p2i(_first_dead), p2i(end_of_live));
523   if (_first_dead == end_of_live && (start == end_of_live || !cast_to_oop(start)->is_gc_marked())) {
524     // Nothing to compact. The space is either empty or all live object should be left in place.
525     clear_empty_region(this);
526     return;
527   }
528 
529   const intx scan_interval = PrefetchScanIntervalInBytes;
530   const intx copy_interval = PrefetchCopyIntervalInBytes;
531 
532   assert(start < end_of_live, "bottom: " PTR_FORMAT " should be < end_of_live: " PTR_FORMAT, p2i(start), p2i(end_of_live));
533   HeapWord* cur_obj = start;
534   if (_first_dead > cur_obj && !cast_to_oop(cur_obj)->is_gc_marked()) {
535     // All object before _first_dead can be skipped. They should not be moved.
536     // A pointer to the first live object is stored at the memory location for _first_dead.
537     cur_obj = *(HeapWord**)(_first_dead);
538   }
539 
540   const SlidingForwarding* const forwarding = GenCollectedHeap::heap()->forwarding();
541 
542   debug_only(HeapWord* prev_obj = NULL);
543   while (cur_obj < end_of_live) {
544     if (!cast_to_oop(cur_obj)->is_forwarded()) {
545       debug_only(prev_obj = cur_obj);
546       // The first word of the dead object contains a pointer to the next live object or end of space.
547       cur_obj = *(HeapWord**)cur_obj;
548       assert(cur_obj > prev_obj, "we should be moving forward through memory");
549     } else {
550       // prefetch beyond q
551       Prefetch::read(cur_obj, scan_interval);
552 
553       // size and destination
554       size_t size = cast_to_oop(cur_obj)->size();
555       HeapWord* compaction_top = cast_from_oop<HeapWord*>(forwarding->forwardee(cast_to_oop(cur_obj)));
556 
557       // prefetch beyond compaction_top
558       Prefetch::write(compaction_top, copy_interval);
559 
560       // copy object and reinit its mark
561       assert(cur_obj != compaction_top, "everything in this pass should be moving");
562       Copy::aligned_conjoint_words(cur_obj, compaction_top, size);
563       cast_to_oop(compaction_top)->init_mark();
564       assert(cast_to_oop(compaction_top)->klass() != NULL, "should have a class");
565 
566       debug_only(prev_obj = cur_obj);
567       cur_obj += size;
568     }
569   }
570 
571   clear_empty_region(this);
572 }
573 
574 #endif // INCLUDE_SERIALGC
575 
576 void Space::print_short() const { print_short_on(tty); }
577 
578 void Space::print_short_on(outputStream* st) const {
579   st->print(" space " SIZE_FORMAT "K, %3d%% used", capacity() / K,
580               (int) ((double) used() * 100 / capacity()));
581 }
582 
583 void Space::print() const { print_on(tty); }
584 
585 void Space::print_on(outputStream* st) const {
586   print_short_on(st);
587   st->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ")",
588                 p2i(bottom()), p2i(end()));
589 }
590 
591 void ContiguousSpace::print_on(outputStream* st) const {
592   print_short_on(st);
593   st->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
594                 p2i(bottom()), p2i(top()), p2i(end()));
595 }
596 
597 void OffsetTableContigSpace::print_on(outputStream* st) const {
598   print_short_on(st);
599   st->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", "
600                 INTPTR_FORMAT ", " INTPTR_FORMAT ")",
601               p2i(bottom()), p2i(top()), p2i(_offsets.threshold()), p2i(end()));
602 }
603 
604 void ContiguousSpace::verify() const {
605   HeapWord* p = bottom();
606   HeapWord* t = top();
607   HeapWord* prev_p = NULL;
608   while (p < t) {
609     oopDesc::verify(cast_to_oop(p));
610     prev_p = p;
611     p += cast_to_oop(p)->size();
612   }
613   guarantee(p == top(), "end of last object must match end of space");
614   if (top() != end()) {
615     guarantee(top() == block_start_const(end()-1) &&
616               top() == block_start_const(top()),
617               "top should be start of unallocated block, if it exists");
618   }
619 }
620 
621 void Space::oop_iterate(OopIterateClosure* blk) {
622   ObjectToOopClosure blk2(blk);
623   object_iterate(&blk2);
624 }
625 
626 bool Space::obj_is_alive(const HeapWord* p) const {
627   assert (block_is_obj(p), "The address should point to an object");
628   return true;
629 }
630 
631 void ContiguousSpace::oop_iterate(OopIterateClosure* blk) {
632   if (is_empty()) return;
633   HeapWord* obj_addr = bottom();
634   HeapWord* t = top();
635   // Could call objects iterate, but this is easier.
636   while (obj_addr < t) {
637     obj_addr += cast_to_oop(obj_addr)->oop_iterate_size(blk);
638   }
639 }
640 
641 void ContiguousSpace::object_iterate(ObjectClosure* blk) {
642   if (is_empty()) return;
643   object_iterate_from(bottom(), blk);
644 }
645 
646 void ContiguousSpace::object_iterate_from(HeapWord* mark, ObjectClosure* blk) {
647   while (mark < top()) {
648     blk->do_object(cast_to_oop(mark));
649     mark += cast_to_oop(mark)->size();
650   }
651 }
652 
653 // Very general, slow implementation.
654 HeapWord* ContiguousSpace::block_start_const(const void* p) const {
655   assert(MemRegion(bottom(), end()).contains(p),
656          "p (" PTR_FORMAT ") not in space [" PTR_FORMAT ", " PTR_FORMAT ")",
657          p2i(p), p2i(bottom()), p2i(end()));
658   if (p >= top()) {
659     return top();
660   } else {
661     HeapWord* last = bottom();
662     HeapWord* cur = last;
663     while (cur <= p) {
664       last = cur;
665       cur += cast_to_oop(cur)->size();
666     }
667     assert(oopDesc::is_oop(cast_to_oop(last)), PTR_FORMAT " should be an object start", p2i(last));
668     return last;
669   }
670 }
671 
672 size_t ContiguousSpace::block_size(const HeapWord* p) const {
673   assert(MemRegion(bottom(), end()).contains(p),
674          "p (" PTR_FORMAT ") not in space [" PTR_FORMAT ", " PTR_FORMAT ")",
675          p2i(p), p2i(bottom()), p2i(end()));
676   HeapWord* current_top = top();
677   assert(p <= current_top,
678          "p > current top - p: " PTR_FORMAT ", current top: " PTR_FORMAT,
679          p2i(p), p2i(current_top));
680   assert(p == current_top || oopDesc::is_oop(cast_to_oop(p)),
681          "p (" PTR_FORMAT ") is not a block start - "
682          "current_top: " PTR_FORMAT ", is_oop: %s",
683          p2i(p), p2i(current_top), BOOL_TO_STR(oopDesc::is_oop(cast_to_oop(p))));
684   if (p < current_top) {
685     return cast_to_oop(p)->size();
686   } else {
687     assert(p == current_top, "just checking");
688     return pointer_delta(end(), (HeapWord*) p);
689   }
690 }
691 
692 // This version requires locking.
693 inline HeapWord* ContiguousSpace::allocate_impl(size_t size) {
694   assert(Heap_lock->owned_by_self() ||
695          (SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread()),
696          "not locked");
697   HeapWord* obj = top();
698   if (pointer_delta(end(), obj) >= size) {
699     HeapWord* new_top = obj + size;
700     set_top(new_top);
701     assert(is_aligned(obj) && is_aligned(new_top), "checking alignment");
702     return obj;
703   } else {
704     return NULL;
705   }
706 }
707 
708 // This version is lock-free.
709 inline HeapWord* ContiguousSpace::par_allocate_impl(size_t size) {
710   do {
711     HeapWord* obj = top();
712     if (pointer_delta(end(), obj) >= size) {
713       HeapWord* new_top = obj + size;
714       HeapWord* result = Atomic::cmpxchg(top_addr(), obj, new_top);
715       // result can be one of two:
716       //  the old top value: the exchange succeeded
717       //  otherwise: the new value of the top is returned.
718       if (result == obj) {
719         assert(is_aligned(obj) && is_aligned(new_top), "checking alignment");
720         return obj;
721       }
722     } else {
723       return NULL;
724     }
725   } while (true);
726 }
727 
728 // Requires locking.
729 HeapWord* ContiguousSpace::allocate(size_t size) {
730   return allocate_impl(size);
731 }
732 
733 // Lock-free.
734 HeapWord* ContiguousSpace::par_allocate(size_t size) {
735   return par_allocate_impl(size);
736 }
737 
738 void ContiguousSpace::allocate_temporary_filler(int factor) {
739   // allocate temporary type array decreasing free size with factor 'factor'
740   assert(factor >= 0, "just checking");
741   size_t size = pointer_delta(end(), top());
742 
743   // if space is full, return
744   if (size == 0) return;
745 
746   if (factor > 0) {
747     size -= size/factor;
748   }
749   size = align_object_size(size);
750 
751   const size_t array_header_size = typeArrayOopDesc::header_size(T_INT);
752   if (size >= align_object_size(array_header_size)) {
753     size_t length = (size - array_header_size) * (HeapWordSize / sizeof(jint));
754     // allocate uninitialized int array
755     typeArrayOop t = (typeArrayOop) cast_to_oop(allocate(size));
756     assert(t != NULL, "allocation should succeed");
757     t->set_mark(Universe::intArrayKlassObj()->prototype_header());
758     t->set_klass(Universe::intArrayKlassObj());
759     t->set_length((int)length);
760   } else {
761     assert(size == CollectedHeap::min_fill_size(),
762            "size for smallest fake object doesn't match");
763     instanceOop obj = (instanceOop) cast_to_oop(allocate(size));
764     obj->set_mark(vmClasses::Object_klass()->prototype_header());
765     obj->set_klass_gap(0);
766     obj->set_klass(vmClasses::Object_klass());
767   }
768 }
769 
770 void OffsetTableContigSpace::initialize_threshold() {
771   _offsets.initialize_threshold();
772 }
773 
774 void OffsetTableContigSpace::alloc_block(HeapWord* start, HeapWord* end) {
775   _offsets.alloc_block(start, end);
776 }
777 
778 OffsetTableContigSpace::OffsetTableContigSpace(BlockOffsetSharedArray* sharedOffsetArray,
779                                                MemRegion mr) :
780   _offsets(sharedOffsetArray, mr),
781   _par_alloc_lock(Mutex::safepoint, "OffsetTableContigSpaceParAlloc_lock", true)
782 {
783   _offsets.set_contig_space(this);
784   initialize(mr, SpaceDecorator::Clear, SpaceDecorator::Mangle);
785 }
786 
787 #define OBJ_SAMPLE_INTERVAL 0
788 #define BLOCK_SAMPLE_INTERVAL 100
789 
790 void OffsetTableContigSpace::verify() const {
791   HeapWord* p = bottom();
792   HeapWord* prev_p = NULL;
793   int objs = 0;
794   int blocks = 0;
795 
796   if (VerifyObjectStartArray) {
797     _offsets.verify();
798   }
799 
800   while (p < top()) {
801     size_t size = cast_to_oop(p)->size();
802     // For a sampling of objects in the space, find it using the
803     // block offset table.
804     if (blocks == BLOCK_SAMPLE_INTERVAL) {
805       guarantee(p == block_start_const(p + (size/2)),
806                 "check offset computation");
807       blocks = 0;
808     } else {
809       blocks++;
810     }
811 
812     if (objs == OBJ_SAMPLE_INTERVAL) {
813       oopDesc::verify(cast_to_oop(p));
814       objs = 0;
815     } else {
816       objs++;
817     }
818     prev_p = p;
819     p += size;
820   }
821   guarantee(p == top(), "end of last object must match end of space");
822 }
823 
824 
825 size_t TenuredSpace::allowed_dead_ratio() const {
826   return MarkSweepDeadRatio;
827 }