1 /*
  2  * Copyright (c) 1997, 2023, 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 #ifndef SHARE_GC_SHARED_SPACE_HPP
 26 #define SHARE_GC_SHARED_SPACE_HPP
 27 
 28 #include "gc/shared/blockOffsetTable.hpp"
 29 #include "gc/shared/cardTable.hpp"
 30 #include "gc/shared/workerThread.hpp"
 31 #include "memory/allocation.hpp"
 32 #include "memory/iterator.hpp"
 33 #include "memory/memRegion.hpp"
 34 #include "oops/markWord.hpp"
 35 #include "runtime/mutexLocker.hpp"
 36 #include "utilities/align.hpp"
 37 #include "utilities/macros.hpp"
 38 #if INCLUDE_SERIALGC
 39 #include "gc/serial/serialBlockOffsetTable.hpp"
 40 #endif
 41 
 42 // A space is an abstraction for the "storage units" backing
 43 // up the generation abstraction. It includes specific
 44 // implementations for keeping track of free and used space,
 45 // for iterating over objects and free blocks, etc.
 46 
 47 // Forward decls.
 48 class Space;
 49 class ContiguousSpace;
 50 #if INCLUDE_SERIALGC
 51 class BlockOffsetArray;
 52 class BlockOffsetArrayContigSpace;
 53 class BlockOffsetTable;
 54 #endif
 55 class Generation;
 56 class ContiguousSpace;
 57 class CardTableRS;
 58 class DirtyCardToOopClosure;
 59 class FilteringClosure;
 60 
 61 // A Space describes a heap area. Class Space is an abstract
 62 // base class.
 63 //
 64 // Space supports allocation, size computation and GC support is provided.
 65 //
 66 // Invariant: bottom() and end() are on page_size boundaries and
 67 // bottom() <= top() <= end()
 68 // top() is inclusive and end() is exclusive.
 69 
 70 class Space: public CHeapObj<mtGC> {
 71   friend class VMStructs;
 72  protected:
 73   HeapWord* _bottom;
 74   HeapWord* _end;
 75 
 76   // Used in support of save_marks()
 77   HeapWord* _saved_mark_word;
 78 
 79   Space():
 80     _bottom(nullptr), _end(nullptr) { }
 81 
 82  public:
 83   // Accessors
 84   HeapWord* bottom() const         { return _bottom; }
 85   HeapWord* end() const            { return _end;    }
 86   virtual void set_bottom(HeapWord* value) { _bottom = value; }
 87   virtual void set_end(HeapWord* value)    { _end = value; }
 88 
 89   virtual HeapWord* saved_mark_word() const  { return _saved_mark_word; }
 90 
 91   void set_saved_mark_word(HeapWord* p) { _saved_mark_word = p; }
 92 
 93   // Returns true if this object has been allocated since a
 94   // generation's "save_marks" call.
 95   virtual bool obj_allocated_since_save_marks(const oop obj) const {
 96     return cast_from_oop<HeapWord*>(obj) >= saved_mark_word();
 97   }
 98 
 99   // Returns a subregion of the space containing only the allocated objects in
100   // the space.
101   virtual MemRegion used_region() const = 0;
102 
103   // Returns a region that is guaranteed to contain (at least) all objects
104   // allocated at the time of the last call to "save_marks".  If the space
105   // initializes its DirtyCardToOopClosure's specifying the "contig" option
106   // (that is, if the space is contiguous), then this region must contain only
107   // such objects: the memregion will be from the bottom of the region to the
108   // saved mark.  Otherwise, the "obj_allocated_since_save_marks" method of
109   // the space must distinguish between objects in the region allocated before
110   // and after the call to save marks.
111   MemRegion used_region_at_save_marks() const {
112     return MemRegion(bottom(), saved_mark_word());
113   }
114 
115   // Initialization.
116   // "initialize" should be called once on a space, before it is used for
117   // any purpose.  The "mr" arguments gives the bounds of the space, and
118   // the "clear_space" argument should be true unless the memory in "mr" is
119   // known to be zeroed.
120   virtual void initialize(MemRegion mr, bool clear_space, bool mangle_space);
121 
122   // The "clear" method must be called on a region that may have
123   // had allocation performed in it, but is now to be considered empty.
124   virtual void clear(bool mangle_space);
125 
126   // For detecting GC bugs.  Should only be called at GC boundaries, since
127   // some unused space may be used as scratch space during GC's.
128   // We also call this when expanding a space to satisfy an allocation
129   // request. See bug #4668531
130   virtual void mangle_unused_area() = 0;
131   virtual void mangle_unused_area_complete() = 0;
132 
133   // Testers
134   bool is_empty() const              { return used() == 0; }
135 
136   // Returns true iff the given the space contains the
137   // given address as part of an allocated object. For
138   // certain kinds of spaces, this might be a potentially
139   // expensive operation. To prevent performance problems
140   // on account of its inadvertent use in product jvm's,
141   // we restrict its use to assertion checks only.
142   bool is_in(const void* p) const {
143     return used_region().contains(p);
144   }
145   bool is_in(oop obj) const {
146     return is_in((void*)obj);
147   }
148 
149   // Returns true iff the given reserved memory of the space contains the
150   // given address.
151   bool is_in_reserved(const void* p) const { return _bottom <= p && p < _end; }
152 
153   // Returns true iff the given block is not allocated.
154   virtual bool is_free_block(const HeapWord* p) const = 0;
155 
156   // Test whether p is double-aligned
157   static bool is_aligned(void* p) {
158     return ::is_aligned(p, sizeof(double));
159   }
160 
161   // Size computations.  Sizes are in bytes.
162   size_t capacity()     const { return byte_size(bottom(), end()); }
163   virtual size_t used() const = 0;
164   virtual size_t free() const = 0;
165 
166   // Iterate over all the ref-containing fields of all objects in the
167   // space, calling "cl.do_oop" on each.  Fields in objects allocated by
168   // applications of the closure are not included in the iteration.
169   virtual void oop_iterate(OopIterateClosure* cl);
170 
171   // Iterate over all objects in the space, calling "cl.do_object" on
172   // each.  Objects allocated by applications of the closure are not
173   // included in the iteration.
174   virtual void object_iterate(ObjectClosure* blk) = 0;
175 
176   // If "p" is in the space, returns the address of the start of the
177   // "block" that contains "p".  We say "block" instead of "object" since
178   // some heaps may not pack objects densely; a chunk may either be an
179   // object or a non-object.  If "p" is not in the space, return null.
180   virtual HeapWord* block_start_const(const void* p) const = 0;
181 
182   // The non-const version may have benevolent side effects on the data
183   // structure supporting these calls, possibly speeding up future calls.
184   // The default implementation, however, is simply to call the const
185   // version.
186   virtual HeapWord* block_start(const void* p);
187 
188   // Requires "addr" to be the start of a chunk, and returns its size.
189   // "addr + size" is required to be the start of a new chunk, or the end
190   // of the active area of the heap.
191   virtual size_t block_size(const HeapWord* addr) const = 0;
192 
193   // Requires "addr" to be the start of a block, and returns "TRUE" iff
194   // the block is an object.
195   virtual bool block_is_obj(const HeapWord* addr) const = 0;
196 
197   // Requires "addr" to be the start of a block, and returns "TRUE" iff
198   // the block is an object and the object is alive.
199   virtual bool obj_is_alive(const HeapWord* addr) const;
200 
201   // Allocation (return null if full).  Assumes the caller has established
202   // mutually exclusive access to the space.
203   virtual HeapWord* allocate(size_t word_size) = 0;
204 
205   // Allocation (return null if full).  Enforces mutual exclusion internally.
206   virtual HeapWord* par_allocate(size_t word_size) = 0;
207 
208 #if INCLUDE_SERIALGC
209   // Mark-sweep-compact support: all spaces can update pointers to objects
210   // moving as a part of compaction.
211   virtual void adjust_pointers() = 0;
212 #endif
213 
214   virtual void print() const;
215   virtual void print_on(outputStream* st) const;
216   virtual void print_short() const;
217   virtual void print_short_on(outputStream* st) const;
218 
219 
220   // IF "this" is a ContiguousSpace, return it, else return null.
221   virtual ContiguousSpace* toContiguousSpace() {
222     return nullptr;
223   }
224 
225   // Debugging
226   virtual void verify() const = 0;
227 };
228 
229 // A dirty card to oop closure for contiguous spaces (ContiguousSpace and
230 // sub-classes). It knows how to filter out objects that are outside of the
231 // _boundary.
232 // (Note that because of the imprecise nature of the write barrier, this may
233 // iterate over oops beyond the region.)
234 //
235 // Assumptions:
236 // 1. That the actual top of any area in a memory region
237 //    contained by the space is bounded by the end of the contiguous
238 //    region of the space.
239 // 2. That the space is really made up of objects and not just
240 //    blocks.
241 
242 class DirtyCardToOopClosure: public MemRegionClosure {
243 protected:
244   OopIterateClosure* _cl;
245   Space* _sp;
246   HeapWord* _min_done;          // Need a downwards traversal to compensate
247                                 // imprecise write barrier; this is the
248                                 // lowest location already done (or,
249                                 // alternatively, the lowest address that
250                                 // shouldn't be done again.  null means infinity.)
251   NOT_PRODUCT(HeapWord* _last_bottom;)
252 
253   // Get the actual top of the area on which the closure will
254   // operate, given where the top is assumed to be (the end of the
255   // memory region passed to do_MemRegion) and where the object
256   // at the top is assumed to start. For example, an object may
257   // start at the top but actually extend past the assumed top,
258   // in which case the top becomes the end of the object.
259   HeapWord* get_actual_top(HeapWord* top, HeapWord* top_obj);
260 
261   // Walk the given memory region from bottom to (actual) top
262   // looking for objects and applying the oop closure (_cl) to
263   // them. The base implementation of this treats the area as
264   // blocks, where a block may or may not be an object. Sub-
265   // classes should override this to provide more accurate
266   // or possibly more efficient walking.
267   void walk_mem_region(MemRegion mr, HeapWord* bottom, HeapWord* top);
268 
269   // Walk the given memory region, from bottom to top, applying
270   // the given oop closure to (possibly) all objects found. The
271   // given oop closure may or may not be the same as the oop
272   // closure with which this closure was created, as it may
273   // be a filtering closure which makes use of the _boundary.
274   // We offer two signatures, so the FilteringClosure static type is
275   // apparent.
276   void walk_mem_region_with_cl(MemRegion mr,
277                                HeapWord* bottom, HeapWord* top,
278                                OopIterateClosure* cl);
279 public:
280   DirtyCardToOopClosure(Space* sp, OopIterateClosure* cl) :
281     _cl(cl), _sp(sp), _min_done(nullptr) {
282     NOT_PRODUCT(_last_bottom = nullptr);
283   }
284 
285   void do_MemRegion(MemRegion mr) override;
286 };
287 
288 // A structure to represent a point at which objects are being copied
289 // during compaction.
290 class CompactPoint : public StackObj {
291 public:
292   Generation* gen;
293   ContiguousSpace* space;
294 
295   CompactPoint(Generation* g = nullptr) :
296     gen(g), space(nullptr) {}
297 };
298 
299 class GenSpaceMangler;
300 
301 // A space in which the free area is contiguous.  It therefore supports
302 // faster allocation, and compaction.
303 class ContiguousSpace: public Space {
304   friend class VMStructs;
305 
306 private:
307   HeapWord* _compaction_top;
308   ContiguousSpace* _next_compaction_space;
309 
310   static inline void verify_up_to_first_dead(ContiguousSpace* space) NOT_DEBUG_RETURN;
311 
312   static inline void clear_empty_region(ContiguousSpace* space);
313 
314  protected:
315   HeapWord* _top;
316   // A helper for mangling the unused area of the space in debug builds.
317   GenSpaceMangler* _mangler;
318 
319   // Used during compaction.
320   HeapWord* _first_dead;
321   HeapWord* _end_of_live;
322 
323   // This the function to invoke when an allocation of an object covering
324   // "start" to "end" occurs to update other internal data structures.
325   virtual void alloc_block(HeapWord* start, HeapWord* the_end) { }
326 
327   GenSpaceMangler* mangler() { return _mangler; }
328 
329   // Allocation helpers (return null if full).
330   inline HeapWord* allocate_impl(size_t word_size);
331   inline HeapWord* par_allocate_impl(size_t word_size);
332 
333  public:
334   ContiguousSpace();
335   ~ContiguousSpace();
336 
337   void initialize(MemRegion mr, bool clear_space, bool mangle_space) override;
338 
339   void clear(bool mangle_space) override;
340 
341   // Used temporarily during a compaction phase to hold the value
342   // top should have when compaction is complete.
343   HeapWord* compaction_top() const { return _compaction_top;    }
344 
345   void set_compaction_top(HeapWord* value) {
346     assert(value == nullptr || (value >= bottom() && value <= end()),
347       "should point inside space");
348     _compaction_top = value;
349   }
350 
351   // Returns the next space (in the current generation) to be compacted in
352   // the global compaction order.  Also is used to select the next
353   // space into which to compact.
354 
355   virtual ContiguousSpace* next_compaction_space() const {
356     return _next_compaction_space;
357   }
358 
359   void set_next_compaction_space(ContiguousSpace* csp) {
360     _next_compaction_space = csp;
361   }
362 
363 #if INCLUDE_SERIALGC
364   // MarkSweep support phase2
365 
366   // Start the process of compaction of the current space: compute
367   // post-compaction addresses, and insert forwarding pointers.  The fields
368   // "cp->gen" and "cp->compaction_space" are the generation and space into
369   // which we are currently compacting.  This call updates "cp" as necessary,
370   // and leaves the "compaction_top" of the final value of
371   // "cp->compaction_space" up-to-date.  Offset tables may be updated in
372   // this phase as if the final copy had occurred; if so, "cp->threshold"
373   // indicates when the next such action should be taken.
374   void prepare_for_compaction(CompactPoint* cp);
375   // MarkSweep support phase3
376   void adjust_pointers() override;
377   // MarkSweep support phase4
378   virtual void compact();
379 #endif // INCLUDE_SERIALGC
380 
381   // The maximum percentage of objects that can be dead in the compacted
382   // live part of a compacted space ("deadwood" support.)
383   virtual size_t allowed_dead_ratio() const { return 0; };
384 
385   // Some contiguous spaces may maintain some data structures that should
386   // be updated whenever an allocation crosses a boundary.  This function
387   // initializes these data structures for further updates.
388   virtual void initialize_threshold() { }
389 
390   // "q" is an object of the given "size" that should be forwarded;
391   // "cp" names the generation ("gen") and containing "this" (which must
392   // also equal "cp->space").  "compact_top" is where in "this" the
393   // next object should be forwarded to.  If there is room in "this" for
394   // the object, insert an appropriate forwarding pointer in "q".
395   // If not, go to the next compaction space (there must
396   // be one, since compaction must succeed -- we go to the first space of
397   // the previous generation if necessary, updating "cp"), reset compact_top
398   // and then forward.  In either case, returns the new value of "compact_top".
399   // Invokes the "alloc_block" function of the then-current compaction
400   // space.
401   virtual HeapWord* forward(oop q, size_t size, CompactPoint* cp,
402                     HeapWord* compact_top);
403 
404   // Accessors
405   HeapWord* top() const            { return _top;    }
406   void set_top(HeapWord* value)    { _top = value; }
407 
408   void set_saved_mark()            { _saved_mark_word = top();    }
409 
410   bool saved_mark_at_top() const { return saved_mark_word() == top(); }
411 
412   // In debug mode mangle (write it with a particular bit
413   // pattern) the unused part of a space.
414 
415   // Used to save the address in a space for later use during mangling.
416   void set_top_for_allocations(HeapWord* v) PRODUCT_RETURN;
417   // Used to save the space's current top for later use during mangling.
418   void set_top_for_allocations() PRODUCT_RETURN;
419 
420   // Mangle regions in the space from the current top up to the
421   // previously mangled part of the space.
422   void mangle_unused_area() override PRODUCT_RETURN;
423   // Mangle [top, end)
424   void mangle_unused_area_complete() override PRODUCT_RETURN;
425 
426   // Do some sparse checking on the area that should have been mangled.
427   void check_mangled_unused_area(HeapWord* limit) PRODUCT_RETURN;
428   // Check the complete area that should have been mangled.
429   // This code may be null depending on the macro DEBUG_MANGLING.
430   void check_mangled_unused_area_complete() PRODUCT_RETURN;
431 
432   // Size computations: sizes in bytes.
433   size_t used() const override   { return byte_size(bottom(), top()); }
434   size_t free() const override   { return byte_size(top(),    end()); }
435 
436   bool is_free_block(const HeapWord* p) const override;
437 
438   // In a contiguous space we have a more obvious bound on what parts
439   // contain objects.
440   MemRegion used_region() const override { return MemRegion(bottom(), top()); }
441 
442   // Allocation (return null if full)
443   HeapWord* allocate(size_t word_size) override;
444   HeapWord* par_allocate(size_t word_size) override;
445 
446   // Iteration
447   void oop_iterate(OopIterateClosure* cl) override;
448   void object_iterate(ObjectClosure* blk) override;
449 
450   // Compaction support
451   void reset_after_compaction() {
452     assert(compaction_top() >= bottom() && compaction_top() <= end(), "should point inside space");
453     set_top(compaction_top());
454   }
455 
456   // Apply "blk->do_oop" to the addresses of all reference fields in objects
457   // starting with the _saved_mark_word, which was noted during a generation's
458   // save_marks and is required to denote the head of an object.
459   // Fields in objects allocated by applications of the closure
460   // *are* included in the iteration.
461   // Updates _saved_mark_word to point to just after the last object
462   // iterated over.
463   template <typename OopClosureType>
464   void oop_since_save_marks_iterate(OopClosureType* blk);
465 
466   // Same as object_iterate, but starting from "mark", which is required
467   // to denote the start of an object.  Objects allocated by
468   // applications of the closure *are* included in the iteration.
469   virtual void object_iterate_from(HeapWord* mark, ObjectClosure* blk);
470 
471   // Very inefficient implementation.
472   HeapWord* block_start_const(const void* p) const override;
473   size_t block_size(const HeapWord* p) const override;
474   // If a block is in the allocated area, it is an object.
475   bool block_is_obj(const HeapWord* p) const override { return p < top(); }
476 
477   // Addresses for inlined allocation
478   HeapWord** top_addr() { return &_top; }
479   HeapWord** end_addr() { return &_end; }
480 
481   void print_on(outputStream* st) const override;
482 
483   // Checked dynamic downcasts.
484   ContiguousSpace* toContiguousSpace() override {
485     return this;
486   }
487 
488   // Debugging
489   void verify() const override;
490 };
491 
492 #if INCLUDE_SERIALGC
493 
494 // Class TenuredSpace is used by TenuredGeneration; it supports an efficient
495 // "block_start" operation via a BlockOffsetArray (whose BlockOffsetSharedArray
496 // may be shared with other spaces.)
497 
498 class TenuredSpace: public ContiguousSpace {
499   friend class VMStructs;
500  protected:
501   BlockOffsetArrayContigSpace _offsets;
502   Mutex _par_alloc_lock;
503 
504   // Mark sweep support
505   size_t allowed_dead_ratio() const override;
506  public:
507   // Constructor
508   TenuredSpace(BlockOffsetSharedArray* sharedOffsetArray,
509                MemRegion mr);
510 
511   void set_bottom(HeapWord* value) override;
512   void set_end(HeapWord* value) override;
513 
514   void clear(bool mangle_space) override;
515 
516   inline HeapWord* block_start_const(const void* p) const override;
517 
518   // Add offset table update.
519   inline HeapWord* allocate(size_t word_size) override;
520   inline HeapWord* par_allocate(size_t word_size) override;
521 
522   // MarkSweep support phase3
523   void initialize_threshold() override;
524   void alloc_block(HeapWord* start, HeapWord* end) override;
525 
526   void print_on(outputStream* st) const override;
527 
528   // Debugging
529   void verify() const override;
530 };
531 #endif //INCLUDE_SERIALGC
532 
533 #endif // SHARE_GC_SHARED_SPACE_HPP