1 /*
  2  * Copyright (c) 2001, 2026, 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 "gc/parallel/mutableSpace.hpp"
 26 #include "gc/shared/pretouchTask.hpp"
 27 #include "gc/shared/spaceDecorator.hpp"
 28 #include "memory/iterator.inline.hpp"
 29 #include "memory/universe.hpp"
 30 #include "oops/oop.inline.hpp"
 31 #include "runtime/javaThread.hpp"
 32 #include "runtime/safepoint.hpp"
 33 #include "utilities/align.hpp"
 34 #include "utilities/macros.hpp"
 35 
 36 MutableSpace::MutableSpace(size_t page_size) :
 37   _last_setup_region(),
 38   _page_size(page_size),
 39   _bottom(nullptr),
 40   _top(nullptr),
 41   _end(nullptr) {}
 42 
 43 void MutableSpace::numa_setup_pages(MemRegion mr, bool clear_space) {
 44   assert(is_aligned(mr.start(), page_size()), "precondition");
 45   assert(is_aligned(mr.end(), page_size()), "precondition");
 46 
 47   if (mr.is_empty()) {
 48     return;
 49   }
 50 
 51   if (clear_space) {
 52     // Prefer page reallocation to migration.
 53     os::disclaim_memory((char*) mr.start(), mr.byte_size());
 54   }
 55   os::numa_make_global((char*) mr.start(), mr.byte_size());
 56 }
 57 
 58 void MutableSpace::initialize(MemRegion mr,
 59                               bool clear_space,
 60                               bool mangle_space,
 61                               bool setup_pages,
 62                               WorkerThreads* pretouch_workers) {
 63 
 64   assert(Universe::on_page_boundary(mr.start()) && Universe::on_page_boundary(mr.end()),
 65          "invalid space boundaries");
 66 
 67   if (setup_pages && (UseNUMA || AlwaysPreTouch)) {
 68     // The space may move left and right or expand/shrink.
 69     // We'd like to enforce the desired page placement.
 70     MemRegion head, tail;
 71     if (last_setup_region().is_empty()) {
 72       // If it's the first initialization don't limit the amount of work.
 73       head = mr;
 74       tail = MemRegion(mr.end(), mr.end());
 75     } else {
 76       // Is there an intersection with the address space?
 77       MemRegion intersection = last_setup_region().intersection(mr);
 78       if (intersection.is_empty()) {
 79         intersection = MemRegion(mr.end(), mr.end());
 80       }
 81       // All the sizes below are in words.
 82       size_t head_size = 0, tail_size = 0;
 83       if (mr.start() <= intersection.start()) {
 84         head_size = pointer_delta(intersection.start(), mr.start());
 85       }
 86       if(intersection.end() <= mr.end()) {
 87         tail_size = pointer_delta(mr.end(), intersection.end());
 88       }
 89       // Limit the amount of page manipulation if necessary.
 90       if (NUMASpaceResizeRate > 0 && !AlwaysPreTouch) {
 91         const size_t change_size = head_size + tail_size;
 92         const float setup_rate_words = NUMASpaceResizeRate >> LogBytesPerWord;
 93         head_size = MIN2((size_t)(setup_rate_words * head_size / change_size),
 94                          head_size);
 95         tail_size = MIN2((size_t)(setup_rate_words * tail_size / change_size),
 96                          tail_size);
 97       }
 98       head = MemRegion(intersection.start() - head_size, intersection.start());
 99       tail = MemRegion(intersection.end(), intersection.end() + tail_size);
100     }
101     assert(mr.contains(head) && mr.contains(tail), "Sanity");
102 
103     if (UseNUMA) {
104       numa_setup_pages(head, clear_space);
105       numa_setup_pages(tail, clear_space);
106     }
107 
108     if (AlwaysPreTouch) {
109       PretouchTask::pretouch("ParallelGC PreTouch head", (char*)head.start(), (char*)head.end(),
110                              page_size(), pretouch_workers);
111 
112       PretouchTask::pretouch("ParallelGC PreTouch tail", (char*)tail.start(), (char*)tail.end(),
113                              page_size(), pretouch_workers);
114     }
115 
116     // Remember where we stopped so that we can continue later.
117     set_last_setup_region(MemRegion(head.start(), tail.end()));
118   }
119 
120   set_bottom(mr.start());
121   // When expanding concurrently with callers of cas_allocate, setting end
122   // makes the new space available for allocation by other threads.  So this
123   // assignment must follow all other configuration and initialization that
124   // might be done for expansion.
125   _end.release_store(mr.end());
126 
127   if (clear_space) {
128     clear(mangle_space);
129   }
130 }
131 
132 void MutableSpace::clear(bool mangle_space) {
133   set_top(bottom());
134   if (ZapUnusedHeapArea && mangle_space) {
135     mangle_unused_area();
136   }
137 }
138 
139 #ifndef PRODUCT
140 
141 void MutableSpace::mangle_unused_area() {
142   mangle_region(MemRegion(top(), end()));
143 }
144 
145 void MutableSpace::mangle_region(MemRegion mr) {
146   SpaceMangler::mangle_region(mr);
147 }
148 
149 #endif
150 
151 HeapWord* MutableSpace::cas_allocate(size_t size) {
152   do {
153     // Read top before end, else the range check may pass when it shouldn't.
154     // If end is read first, other threads may advance end and top such that
155     // current top > old end and current top + size > current end.  Then
156     // pointer_delta underflows, allowing installation of top > current end.
157     HeapWord* obj = _top.load_acquire();
158     if (pointer_delta(end(), obj) >= size) {
159       HeapWord* new_top = obj + size;
160       if (!_top.compare_set(obj, new_top)) {
161         continue; // another thread beat us to the allocation, try again
162       }
163       assert(is_object_aligned(obj) && is_object_aligned(new_top),
164              "checking alignment");
165       return obj;
166     } else {
167       return nullptr;
168     }
169   } while (true);
170 }
171 
172 // Try to deallocate previous allocation. Returns true upon success.
173 bool MutableSpace::cas_deallocate(HeapWord *obj, size_t size) {
174   HeapWord* expected_top = obj + size;
175   return _top.compare_set(expected_top, obj);
176 }
177 
178 void MutableSpace::oop_iterate(OopIterateClosure* cl) {
179   HeapWord* obj_addr = bottom();
180   HeapWord* t = top();
181   // Could call objects iterate, but this is easier.
182   while (obj_addr < t) {
183     obj_addr += cast_to_oop(obj_addr)->oop_iterate_size(cl);
184   }
185 }
186 
187 void MutableSpace::object_iterate(ObjectClosure* cl) {
188   HeapWord* p = bottom();
189   while (p < top()) {
190     oop obj = cast_to_oop(p);
191     // When promotion-failure occurs during Young GC, eden/from space is not cleared,
192     // so we can encounter objects with "forwarded" markword.
193     // They are essentially dead, so skipping them
194     if (obj->is_forwarded()) {
195       assert(!obj->is_self_forwarded(), "must not be self-forwarded");
196       // It is safe to use the forwardee here. Parallel GC only uses
197       // header-based forwarding during promotion. Full GC doesn't
198       // use the object header for forwarding at all.
199       p += obj->forwardee()->size();
200     } else {
201       cl->do_object(obj);
202       p += obj->size();
203     }
204   }
205 }
206 
207 void MutableSpace::print_short() const { print_short_on(tty); }
208 void MutableSpace::print_short_on( outputStream* st) const {
209   st->print("space %zuK, %d%% used", capacity_in_bytes() / K,
210             (int) ((double) used_in_bytes() * 100 / capacity_in_bytes()));
211 }
212 
213 void MutableSpace::print() const { print_on(tty, ""); }
214 void MutableSpace::print_on(outputStream* st, const char* prefix) const {
215   st->print("%s", prefix);
216   MutableSpace::print_short_on(st);
217   st->print_cr(" [" PTR_FORMAT "," PTR_FORMAT "," PTR_FORMAT ")",
218                  p2i(bottom()), p2i(top()), p2i(end()));
219 }
220 
221 void MutableSpace::verify() {
222   HeapWord* p = bottom();
223   HeapWord* t = top();
224   while (p < t) {
225     oopDesc::verify(cast_to_oop(p));
226     p += cast_to_oop(p)->size();
227   }
228   guarantee(p == top(), "end of last object must match end of space");
229 }